无法在主 Java 方法中接收用户输入。

huangapple 未分类评论50阅读模式
英文:

Cannot take user input in main java method

问题

    }
    public static void main(String[] args) {
    	Scanner userInputs = new Scanner(System.in);
 
        loadCurrencyCodes();
        showCurrencies();
        findMyCurrency();
        
	    System.out.print("Try again (Y/N): ");
		String yesNo = userInputs.next();
    }

}

Exception in thread "main" 尝试重新运行代码时,我从用户处获取y/n的输入时出现java.util.NoSuchElementException异常。

英文:
    }
    public static void main(String[] args) {
    	Scanner userInputs = new Scanner(System.in);
 
        loadCurrencyCodes();
        showCurrencies();
        findMyCurrency();
        
	    System.out.print("Try again (Y/N): ");
		String yesNo = userInputs.next();
    }

}

Exception in thread "main" Try again (Y/N): java.util.NoSuchElementException

at java.util.Scanner.throwFor(Unknown Source)

at java.util.Scanner.next(Unknown Source)

at CheckCurrencyCode.main(CheckCurrencyCode.java:69)

I'm attempting to take in an input of y/n from the user, when I run the code I get the above exception.

答案1

得分: 0

你应该在它的工作完成后关闭 userInput 对象:

System.out.print("再试一次(Y/N):");
String yesNo = userInputs.next();
userInputs.close();
英文:

You should close object userInput object when its work is over :

System.out.print("Try again (Y/N): ");
String yesNo = userInputs.next();
userInputs.close();

答案2

得分: 0

Sure, here's the translated code snippet:

您可以使用 try-with-resources 结构它会自动处理流的关闭

try (Scanner userInputs = new Scanner(System.in)) {
    System.out.print("再试一次(Y/N):");
    String yesNo = userInputs.next();
}
英文:

> You can use try with resource and it will automatically handle closing stream for you.

   try(Scanner userInputs = new Scanner(System.in)){
		 System.out.print("Try again (Y/N): ");
	        String yesNo = userInputs.next();
	 }

huangapple
  • 本文由 发表于 2020年7月24日 12:02:39
  • 转载请务必保留本文链接:https://java.coder-hub.com/63066616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定