使用扫描仪的NoSuchElement [英] NoSuchElement using scanner

查看:39
本文介绍了使用扫描仪的NoSuchElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have declared two strings and reading the input using Scanner(System.in).

之后,当我关闭Scanner并再次使用Scanner读取另一个输入时,它抛出错误:NoSuchElementException。 请在这方面给我指点

import java.util.Scanner;
import java.io.*;  

public class NumericInput

{
  public static void main(String[] args)
  {
    // Declarations
    Scanner in = new Scanner(System.in);
    String string1;
    String string2;

   // Prompts 
    System.out.println("Enter the value of the First String .");
   // Read in values  
    string1 = in.nextLine();
    // When i am commenting below line(in.close) code is working properly. 
    in.close();
    Scanner sc = new Scanner(System.in);
    System.out.println("Now enter another value.");
    string2 = sc.next();
    sc.close();

    System.out.println("Here is what you entered: ");
    System.out.println(string1 + " and " + string2);
  }

}

推荐答案

当您close扫描仪也关闭System.in输入流时,您正在再次使用它,但它已关闭,因此当您再次尝试使用Scanner时,找不到打开的System.in流。

这篇关于使用扫描仪的NoSuchElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆