作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我必须为我的类(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/
我创建了一个分支来开发新功能。由于这个新功能完全是作为一个新项目开发的,唯一可能的冲突来源是解决方案文件。 随着功能的开发,主分支更新了几次。当我完成开发和测试时,我做了: git checkout
我是一名优秀的程序员,十分优秀!