Java 使用scanner类时出现问题。在System.out.println(“请输入学生1的分数”)之后;,它跳过了两个问题
}更换:-Java 使用scanner类时出现问题。在System.out.println(“请输入学生1的分数”)之后;,它跳过了两个问题,java,java.util.scanner,Java,Java.util.scanner,}更换:- package findingthehighestscore; import java.util.Scanner; public class FindingTheHighestScore { public static void main(String[] args) { Scanner kybd = new Scanner(System.in); // store students names String student1; String
package findingthehighestscore;
import java.util.Scanner;
public class FindingTheHighestScore
{
public static void main(String[] args)
{
Scanner kybd = new Scanner(System.in);
// store students names
String student1;
String student2;
String student3;
String tempStudent;
// store students scores
double score1;
double score2;
double score3;
double tempScore;
//Prompt user for input of each student and their score
System.out.println("Please enter the name of Student 1");
student1 = kybd.nextLine();
System.out.println("Please enter the score of student 1");
score1 = kybd.nextByte();
System.out.println("Please enter the name of Student 2");
student2 = kybd.nextLine();
System.out.println("Please enter the score of student 2");
score2 = kybd.nextByte();
System.out.println("Please enter the name of Student 3");
student3 = kybd.nextLine();
System.out.println("Please enter the score of student 3");
score3 = kybd.nextByte();
//if score2 is greater then score1 then swap scores. Score 1 will be printed as highest score
if(score2 > score1)
{
tempScore = score1;
score1 = score2;
score2 = tempScore;
tempStudent = student1;
student1 = student2;
student2 = tempStudent;
}
//if score3 is greater then score1 then swap scores.
if(score3 > score1)
{
tempScore = score1;
score1 = score3;
score3 = tempScore;
tempStudent = student1;
student1 = student3;
student3 = tempStudent;
}
System.out.print(student1 + " has the highest score of " + score1);
}
与:-
student1 = kybd.nextLine();
nextLine()方法不读取当前输入末尾的换行符。。因此,在下一次调用scanner.nextByte()
。。它读取的不是字节而是换行符
因此,它基本上跳过下一行(当它从上一个输入中读取换行符时),并在下一行之后移动光标。。因此,您的nextByte()
方法被跳过
因此,要阅读换行符,可以使用
next()
方法。。这样,在下一次迭代中将不会留下任何内容供阅读。感谢您提供的解决方案,但您能否用更简单的术语解释原因,因为我是一名初学者。@user1718135。。我已经在我的帖子里解释过了。。读一读scanner.nextLine()
读取当前行,但跳过行末尾的换行(\n)
。。所以,当我们试图读取下一个用户输入时,新行被读取。。因此,如果执行sc.nextByte()
操作,它将实际读取上一个输入上的换行符(\n)
。。这就是为什么它被跳过。。因为它已经读取了用户输入的(\n)
。。
student1 = kybd.next();