gpt4 book ai didi

java - 扫描仪无法正确读取字符串

转载 作者:行者123 更新时间:2023-11-30 06:51:22 25 4
gpt4 key购买 nike

我正在解决这个问题,我似乎遇到了一个奇怪的错误...每当我尝试使用 .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

我知道数学是错误的,但我需要先弄清楚名称部分,如果有人能告诉我我做错了什么,我将不胜感激。

最佳答案

以下语句使用(但不保存)您的名字:

if(scr.nextLine().equalsIgnoreCase("退出"))

保存在 studentName 变量中的第二个名字是

studentName = scr.next();

如果您也想存储名字,则需要先将其存储在变量中。

关于java - 扫描仪无法正确读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42709797/

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