我正在解决这个问题,我似乎遇到了一个奇怪的错误......当我尝试使用 .nextLine(); 存储字符串时;它创建一个新行并保存第二行。
我的代码:公共课平均值{
public static void main (String args[]) {
String studentName = "";
int score1, score2, score3;
float Average = 0f;
int numberTests = 0;
Scanner scr = new Scanner(System.in);
System.out.println("Enter students name");
if(scr.nextLine().equalsIgnoreCase("quit")) {
System.exit(0);
} else {
studentName = scr.next();
}
System.out.println("Enter the amount of tests");
numberTests = scr.nextInt();
System.out.println("Enter students scores");
score1 = scr.nextInt();
score2 = scr.nextInt();
score3 = scr.nextInt();
Average = (score1 + score2 + score3) / numberTests;
System.out.print(studentName + " " + Average);
}}
错误是第一个输入没有被保存,而是转到另一行并保存。运行时这是输出:
输入学生姓名
堆
溢出
输入测试数量
3
输入学生成绩
1
2个
3
溢出 2.0
我知道数学是错误的,但我需要先弄清楚名称部分,如果有人能告诉我我做错了什么,我将不胜感激。
公共静态void main(String args []){
String studentName = "";
int score1, score2, score3;
float Average = 0f;
int numberTests = 0;
Scanner scr = new Scanner(System.in);
System.out.println("Enter students name");
String name = scr.nextLine();
if (name.equalsIgnoreCase("quit"))
{
System.exit(0);
}
System.out.println("Enter the amount of tests");
numberTests = scr.nextInt();
System.out.println("Enter students scores");
score1 = scr.nextInt();
score2 = scr.nextInt();
score3 = scr.nextInt();
Average = (score1 + score2 + score3) / numberTests;
System.out.print(studentName + " " + Average);
}
希望你明白
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句