[英]How do I get while input (except when the user inputs 0 that terminates the program) in Java?
我是Java的新手。 我希望得到循环输入,除非用户输入0以Java结束程序。 我知道如何在C ++中实现它(如下所示),但我编写的Java代码不起作用。
C ++:
while (cin >> n, n) {
GraphAdjList G;
CreateAdjListGraph(G, n);
n = 0;
}
Java的:
Scanner sc = new Scanner(System. in );
n = sc.nextInt();
while (n != 0) {
Graph G = new Graph();
G.CreateAdjListGraph(n);
//G.print();
n = sc.nextInt();
}
这就是我要的。 程序仅在用户输入0时终止。
2
qRj dIm
aTy oFu
4
qRj aTy
qRj oFu
oFu cLq
aTy qUr
0
nextInt()
不适用于您的情况,如果您的输入包含非整数字,则抛出InputMismatchException
。 您最好使用nextLine()
并尝试使用Integer.parseInt
将每个单词转换为int
。
例如:
int n = -1;
Scanner sc = new Scanner(System.in);
String line;
while (n != 0){
line = sc.nextLine();
String[] splits = line.split(" ");
System.out.println(Arrays.toString(splits));
for (String split : splits) {
try {
n = Integer.parseInt(split);
if (n == 0)
break;
//Graph G = new Graph();
//G.CreateAdjListGraph(n);
} catch (NumberFormatException e) {
// handling
}
}
}
即使您在同一行中提供所有输入,这也应该有效。
您不应该使用scan.nextInt()
因为在您的示例程序运行中,您将一些non-inetger values
作为输入,因此,在这种情况下,您的代码将失败。
使用scan.nextLine()
这将参数作为String
而不是Integer
。 现在,您可以更改比较While loop
的结果。
工作守则:
import java.util.Scanner;
public class stackScanner
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
// as you are now taking "String" from user so you have to compare it with "0" not 0
while(!(input.equals("0"))) // while input is not 0
{
// your code here
input = scan.nextLine();
}
}
}
注意:我使用的是String.equals()
而不是==
运算符,原因如下:
String.equals()
始终返回boolean value
因此不会通过任何异常。 ==
运算符进行参考比较 (地址比较)和Stinrg.equals()
方法进行内容比较 。 简单来说, ==
检查两个对象是否指向相同的内存位置,而String.equals()
计算对象中值的比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.