-2
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);       
}

}

4

1 回答 1

3

代替 :-

student1 = kybd.nextLine();

和: -

student1 = kybd.next();

nextLine()方法不会读取当前输入末尾的换行符。因此,换行符将在下一次调用时读取scanner.nextByte()它读取的不是字节而是换行符。

所以,它基本上跳过下一行(因为它从上一个输入中读取换行符)并在下一行之后前进光标。所以,你的nextByte()方法只是被跳过了..

因此,要阅读换行符,您可以使用next()方法.. 这样,下一次迭代将没有任何内容可供阅读..

于 2012-10-03T20:00:41.167 回答