【问题标题】:How do I accept the user input and put it into the while condition如何接受用户输入并将其放入 while 条件
【发布时间】:2020-11-04 02:24:58
【问题描述】:
这是我的代码,while 循环没有输入,rep 变量不接受输入:
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "";
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} // This does not accept input
while (rep.equals("y"));
}
}
【问题讨论】:
标签:
java
loops
while-loop
【解决方案1】:
要么在rep = keyboard.nextLine(); 之前再添加一个keyboard.nextLine()(为了清除换行符),要么读取您的 double gpa 值:
double gpa = Double.parseDouble(keyboard.nextLine());
重要点要在这里理解(尤其是如果您是 Java 开发新手),关于为什么您的代码不起作用,是您调用 nextDouble() 作为您的最后一个方法扫描仪实例,它不会将光标移动到下一行。
更多细节:
nextX() 模式下的所有方法(如nextDouble()、nextInt() 等),nextLine() 除外,读取您输入的下一个令牌,但如果令牌不是换行字符,则光标不会移动到下一行。当您输入双精度值并点击Enter 时,您实际上给输入流两个标记:一个双精度值和一个换行符,双精度值被初始化到变量中,换行字符留在输入流中。下次您调用 nextLine() 时,会读取那个非常新的行字符,这就是给您一个空字符串的原因。
【解决方案2】:
这是使用 while 循环而不是 do-while 的相同代码。它按照您想要的方式工作。
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "y";
while (!rep.equals("n")) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name: ");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ",GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
}
}
}
【解决方案3】:
你需要跳过空白行。
public static void main(String[] args) {
String rep;
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
keyboard.skip("\r\n"); // to skip blank lines
}
while (rep.equalsIgnoreCase("y"));
keyboard.close();
}
【解决方案4】:
使用nextLine 代替nextDouble:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String rep = "";
do {
System.out.println("Enter your full name:");
String name = keyboard.nextLine();
System.out.println("Enter your GPA:");
// double gpa = keyboard.nextDouble();
double gpa = Double.parseDouble(keyboard.nextLine());
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} while (rep.equals("y"));
keyboard.close();
}