Java 运行代码时,nextLine()不会出现
我正在使用:Java 运行代码时,nextLine()不会出现,java,Java,我正在使用: public static final Scanner CONSOLE = new Scanner(System.in); 然后在我的主要方法中: System.out.print("\nPlease choose a color for the circle between the following options:\nBlack\nRandom"); String colorChoice = CONSOLE.nextLine(); colorChoice = colorCh
public static final Scanner CONSOLE = new Scanner(System.in);
然后在我的主要方法中:
System.out.print("\nPlease choose a color for the circle between the following options:\nBlack\nRandom");
String colorChoice = CONSOLE.nextLine();
colorChoice = colorChoice.trim();
程序显示“请选择颜色”,但在允许任何用户输入之前终止。我不明白为什么它不起作用 这是输出: 请为50到400之间的圆输入半径:[DrJava输入框] 请在以下选项之间选择圆的颜色: 黑色 随机> 编辑1: 我更改了行
System.out.print(“\n请在以下选项之间为圆圈选择一种颜色:\n黑色\n随机”)
到系统输出打印(“\n请在以下选项之间为圆圈选择一种颜色:黑色,随机”)
查看\n
是否是问题所在。它仍然不起作用
我在后面包含了一个while循环(用于检查值),因此代码如下所示:
System.out.print("\nPlease choose a color for the circle between the following options: Black, Random");
String colorChoice = CONSOLE.nextLine();
colorChoice = colorChoice.trim();
boolean matchesChoice = matchesChoice(colorChoice, "black", "random");
while(matchesChoice != true){
System.out.print("\nInvalid color choice. Please try again.");
colorChoice = CONSOLE.nextLine();
colorChoice = colorChoice.trim();
matchesChoice = matchesChoice(colorChoice, "black", "random");
}
此文件的输出为:
请为50到400之间的圆输入半径:[DrJava输入框]
请在以下选项之间为圆圈选择颜色:黑色、随机
无效的颜色选择。请再试一次。[DrJava输入框]
因此CONSOLE.nextLine()在循环内部工作,而不是在循环外部。无论我插入什么作为用户输入(正确与否),它只是重复“无效颜色选择”行和输入
import java.util.Scanner;
import javax.swing;
public class (NAME) {
public static void main(String args[])throws Exception{
Scanner CONSOLE = new Scanner(System.in);
System.out.println(("Please enter a radius for the circle between 50 and 400")
int radius = Integer.parseInt(JOptionPane.showInputDialog("Please choose a number from 50 to 400:"));
System.out.println("Radius is " + radius.toString();
System.out.println(("Please choose a color for the circle between the following options: Black Random");
String colorChoice = CONSOLE.nextLine();
colorChoice = colorChoice.trim();
-> System.out.println("You chose " + colorChoice);
}
代码中缺少箭头所在的行。它实际上接受colorChoice的值,但不显示它,因为您忘记显示它。:)
这也可以。如果您希望扫描仪是公共的。如果您愿意,它可以是私有的,特别是当您只处理一个文件/类时
附言:总是有无缘无故的选民倒台。即使只是看问题本身,它可能需要多个答案,而我们大多数人都不知道具体提供什么。尝试使用
while(CONSOLE.hasNextLine())
在将其分配给colorChoice之前。我认为这是由缓冲区延迟引起的,nextLine会一直读取,直到找到换行符
\n
然后停止,您正在打印的语句会在其中打印两个换行符。我猜CONSOLE.nextLine()
是在输出缓冲区打印所有print
语句之前执行的,因此当print语句继续时,它提供了nextLine()。如果是这样的话,那就太奇怪了。尝试这样打印:“…选项:黑色,随机:
”然后在允许任何用户输入之前终止。“它确实允许我在IDE上终止之前输入一些内容。您需要提供与问题相关的孔代码,,,您是否收到错误/异常???没有错误/异常似乎跳过了那行代码。我包括了一个编辑,它显示了一个while循环,它接受输入,但永远卡在循环中。解决方法可能是尝试不同的想法。我的程序只是卡在while循环中,但至少要求用户输入。
while(CONSOLE.hasNextLine())