import java.util.Scanner;
public class test{
public static void main(String[]args){
Scanner gogosi = new Scanner(System.in);
if(gogosi.nextInt()<=0) {
System.out.print("Error");
}else if(gogosi.nextInt()<=51){
System.out.print("Please go take your order");
}else if(gogosi.nextInt()>=51){
System.out.print("Your gonna get fat");
}else{
System.out.print("Error");
}
}
}
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at test.main(test.java:10)
所以..我不t see what is wrong, i tried, but didnt find any solutuions, please help?
I scanned the code but it still doesn
不工作。
dsfsfsdfsdfsdfsdfsd
标清
F
自卫队
自卫队
sdfsdfsdfsdfsdf
自卫队
sdfsdsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
答案 0 :(得分:1)
这在JavaDocs中有很好的文档说明,您在调用nextInt()时没有检查是否还有要读取的内容,如果没有要读取的内容,则将引发NoSuchElementException。确保使用hasNextInt()读取整数:
Scanner gogosi = new Scanner(System.in);
if (gogosi.hasNextInt()) {
int i = gogosi.nextInt();
if (i <= 0) {
System.out.print("Error");
} else if (i <= 51) {
System.out.print("Please go take your order");
} else if (i >= 51) {
System.out.print("Your gonna get fat");
} else {
System.out.print("Error");
}
}
gogosi.close();
另外,您可能(取决于您要执行的操作)希望在第一个输入失败后才能输入另一个输入。为此,您可以在前面的代码周围包裹一个while循环,例如:
Scanner gogosi = new Scanner(System.in);
// possibility to exit the loop when you enter 0
boolean exit = false;
while (gogosi.hasNextInt() && !exit) {
int i = gogosi.nextInt();
if (i == 0) {
System.out.print("Exit");
exit = true;
} else if (i < 0) {
System.out.print("Error");
} else if (i <= 51) {
System.out.print("Please go take your order");
} else if (i >= 51) {
System.out.print("Your gonna get fat");
}
// note: else removed because it will never be reached anyway
}
gogosi.close();
答案 1 :(得分:0)
命令行参数存储在args
参数中。
参见:Command-Line Arguments。
启动应用程序时,运行时系统将传递 通过数组对应用程序的main方法的命令行参数 的
Strings
。
如果您仅传递一个数字,那么它将在args[0]
中。
然后,您只需要获取它,将其存储在变量中,然后进行比较即可。
public static void main(String[] args)
{
//Scanner gogosi = new Scanner(System.in);
//int x = gogosi.nextInt();
int x = Integer.parseInt(args[0]);
if (x<=0) {
System.out.print("Error");
} else if(x<=51) {
System.out.print("Please go take your order");
} else if(x>=51) {
System.out.print("Your gonna get fat");
} else {
System.out.print("Error");
}
}
不需要Scanner
。