gpt4 book ai didi

java - 为什么使用 do while 循环时会跳过 nextLine

转载 作者:行者123 更新时间:2023-12-01 08:10:37 25 4
gpt4 key购买 nike

我必须为我的类(class)编写一个程序,该程序接受用户输入的作业、实验、测试等,将它们放入一个字符串中,并且有一个单独的类将它们分成单独的“双”数字并包含一个 writeToFile将学生的成绩写入文件的方法。

但我一直遇到问题..当我第一次询问用户的名字时,它工作正常,但如果用户决定再次进入 do-while 循环,则会跳过“你叫什么名字”它直接转到 id。我知道这与最后一个输入不是字符串有关,解决方案是放置一个“keyboard.nextLine();”在问题上方,但我尝试过,它只是在询问问题之前询问用户的姓名..

import java.util.Scanner; 
import java.io.*;
import java.text.DecimalFormat;

public class GradeApplication
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);

//Define variables
String name;
int id;
String homework;
String labs;
String tests;
double project;
double discussion;
int answer;

do
{
System.out.print("\nWhat is your name? ");
name=keyboard.nextLine();

System.out.print("\nWhat is your student ID? ");
id=keyboard.nextInt();

homework = keyboard.nextLine();
System.out.println("\nPlease enter homework grades separated by spaces:");
homework = keyboard.nextLine();

System.out.println("Please enter lab grades separated by spaces:");
labs = keyboard.nextLine();

System.out.println("Please enter test grades separated by spaces:");
tests = keyboard.nextLine();

System.out.println("Please enter project grade:");
project = keyboard.nextDouble();

System.out.println("Please enter discussion grade:");
discussion = keyboard.nextDouble();

System.out.println("\nResults: ");
//Call toString method
Student_Khazma s = new Student_Khazma(name,id,homework,labs,tests,project,discussion);
System.out.print(s.toString());

//Open file
PrintWriter outputFile= new PrintWriter("gradeReport.txt");
System.out.println(s.writeToFile());
outputFile.close();

System.out.print("\n\nWould you like to see your grade report again? (1 is yes, 2 is no): ");
answer=keyboard.nextInt();

System.out.print("\n\nWould you like to see your grade report again? (1 is yes, 2 is no): ");
answer=keyboard.nextInt();

}while(answer==1);

}
}

最佳答案

您最后一次调用Scanner#nextInt() :

    ...
System.out.print("\n\nWould you like to see your grade report again? (1 is yes, 2 is no): ");
answer=keyboard.nextInt();

} while(answer==1);

不消耗换行符,因此它会传递到您第一次调用 Scanner#nextLine()。因此,扫描操作不会阻塞等待输入(详细信息请参阅javadoc)。要解决这个问题,您需要添加keyboard.nextLine();:

    ...
System.out.print("\n\nWould you like to see your grade report again? (1 is yes, 2 is no): ");
answer=keyboard.nextInt();
keyboard.nextLine(); // <== line added here
} while(answer==1);

这样您对 nextLine() 的第一次调用将阻止输入(当循环重新启动时)。

关于java - 为什么使用 do while 循环时会跳过 nextLine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17758651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com