我正在研究这个问题,我似乎有一个奇怪的错误......当我试图使用.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
我理解数学是错误的,但我需要首先找出名称部分,如果有人能告诉我我做错了什么我会非常感激。
答案 0 :(得分:1)
以下语句消耗(但不保存)您的名字:
if(scr.nextLine().equalsIgnoreCase("quit"))
保存在studentName
变量中的第二个名称是
studentName = scr.next();
如果您还要存储名字,则需要先将其存储在变量中。
答案 1 :(得分:0)
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");
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);
}
希望你明白
答案 2 :(得分:0)
错误在scr.nextLine().equalsIgnoreCase("quit")
,因为它没有将用户输入分配给studentName。
使用并查看以下代码。
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");
studentName=scr.nextLine();
if(studentName.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);
}}