获取输入 java
Getting input java
与此相同 我想从用户那里获得输入,而 he/she 给我字符串。但不同的是,现在在我得到 strings 之前,我必须得到 26 个数字。所以这段代码在获取 myStrings
时出错了。我该怎么办?
错误代码:
for (int i = 97; i < 123; i++) {
alphabet[i] = scan.nextFloat();
}
String infix;
int i = 0;
String[] myStrings = new String[100];
while (scan.hasNextLine()) {
infix = scan.nextLine();
if (infix.length() > 0) {
myStrings[i] = infix;
i++;
} else {
break;
}
}
edit: 错误的意思是,当我调试它时,在我将字符串作为输入之前(在给出数字之后),这一行 :(" while (scan.hasNextLine())
") passes , and infix
in this line( infix = scan.nextLine();
is "") 所以 while , 不能正常工作。然后休息。
这是 Java 中的一个常见问题。使用像 nextInt();、nextDouble(); 这样的 Scanner 从用户那里获取输入后等等,您需要使用空 scan.nextLine(); 的行,因为这些方法不使用换行表达式“\n”。 , 在你可以得到一些字符串之前。
问题是从扫描仪读取了一个浮点数后,扫描仪中留下了换行符 "\n"
,这意味着当第一个 scan.nextLine()
运行时,它会得到剩余的换行符,这导致您的代码命中 else 块,并跳出循环。
您可以在循环之前获取下一行:
String infix;
int i = 0;
String[] myStrings = new String[100];
infix = scan.nextLine(); //Get it here to throw away the new line
while (scan.hasNextLine()) {
infix = scan.nextLine(); //Should contain whatever the user entered
//code
}
或者,当你从循环中得到浮点数时,你可以使用 Float.parseFloat()
结合 scan.nextLine()
,像这样:
for (int i = 97; i < 123; i++) {
alphabet[i] = Float.parseFloat(scan.nextLine());
}
这将在您收到最后一个浮点数后停止在扫描仪中留下新行
与此相同myStrings
时出错了。我该怎么办?
错误代码:
for (int i = 97; i < 123; i++) {
alphabet[i] = scan.nextFloat();
}
String infix;
int i = 0;
String[] myStrings = new String[100];
while (scan.hasNextLine()) {
infix = scan.nextLine();
if (infix.length() > 0) {
myStrings[i] = infix;
i++;
} else {
break;
}
}
edit: 错误的意思是,当我调试它时,在我将字符串作为输入之前(在给出数字之后),这一行 :(" while (scan.hasNextLine())
") passes , and infix
in this line( infix = scan.nextLine();
is "") 所以 while , 不能正常工作。然后休息。
这是 Java 中的一个常见问题。使用像 nextInt();、nextDouble(); 这样的 Scanner 从用户那里获取输入后等等,您需要使用空 scan.nextLine(); 的行,因为这些方法不使用换行表达式“\n”。 , 在你可以得到一些字符串之前。
问题是从扫描仪读取了一个浮点数后,扫描仪中留下了换行符 "\n"
,这意味着当第一个 scan.nextLine()
运行时,它会得到剩余的换行符,这导致您的代码命中 else 块,并跳出循环。
您可以在循环之前获取下一行:
String infix;
int i = 0;
String[] myStrings = new String[100];
infix = scan.nextLine(); //Get it here to throw away the new line
while (scan.hasNextLine()) {
infix = scan.nextLine(); //Should contain whatever the user entered
//code
}
或者,当你从循环中得到浮点数时,你可以使用 Float.parseFloat()
结合 scan.nextLine()
,像这样:
for (int i = 97; i < 123; i++) {
alphabet[i] = Float.parseFloat(scan.nextLine());
}
这将在您收到最后一个浮点数后停止在扫描仪中留下新行