Java黑皮书课后题第5章:*5.9(找出得最高分的前两个学生)编写程序,提示用户输入学生的个数、每个学生名字及分数,最后显示获得最高分的学生
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Java黑皮书课后题第5章:*5.9(找出得最高分的前两个学生)编写程序,提示用户输入学生的个数、每个学生名字及分数,最后显示获得最高分的学生
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                *5.9(找出得最高分的前兩個學生)編寫程序,提示用戶輸入學生的個數、每個學生名字及分數,最后顯示獲得最高分的學生名字、次高分的學生名字
- 題目
 - 題目概述
 - next()讀取一個字符與nextLine()讀取一行
 - 破題
 
- 代碼
 
題目
題目概述
*5.9(找出得最高分的前兩個學生)編寫程序,提示用戶輸入學生的個數、每個學生名字及分數,最后顯示獲得最高分的學生名字、次高分的學生名字
 使用Scanner類的next()方法而不是nextLine()方法來讀取名字
next()讀取一個字符與nextLine()讀取一行
舉個例子理解:
 Scanner input = new Scanner(System.in);
 這個時候往console控制臺輸入:ABC 123
 String str_next1 = input.next();
 那么str_next1是:“ABC”
 String str_next2 = input.next();
 str_next2為:“123”
Scanner input = new Scanner(System.in);
 這個時候往console控制臺輸入:ABC 123
 String str_nextLine = input.nextLine();
 那么str_nextLine是:“ABC 123”
破題
輸入順序是這樣的:學生個數 學生1名 學生1分數 學生2名 學生2分數 學生3名 學生3分數…學生n名 學生n分數
代碼
import java.util.Scanner;public class Test5_9 {public static void main(String[] args) {// 讀取學生個數Scanner input = new Scanner(System.in);System.out.println("請輸入學生個數:");int i = input.nextInt();// 讀取后續數據+判斷最大值次大值double score = 0.0, biggestScore = 0.0, secondScore = 0.0;String student = "", biggestStudent = "", secondStudent = "";System.out.println("請輸入學生姓名與成績");for(int n = i;n > 0;--n){student = input.next();score = input.nextDouble();// 當輸入值為score biggestScore secondScore最大值if(score > biggestScore){secondScore = biggestScore;secondStudent = biggestStudent;biggestScore = score;biggestStudent = student;}else if((score < biggestScore) && (score > secondScore)){// 當輸入值大于次大、小于最大時secondScore = score;secondStudent = student;} else if (score == biggestScore){secondScore = score;secondStudent = student;}}// 輸出結果System.out.println("最高分學生名為:" + biggestStudent);System.out.println("次高分學生名為:" + secondStudent);} }總結
以上是生活随笔為你收集整理的Java黑皮书课后题第5章:*5.9(找出得最高分的前两个学生)编写程序,提示用户输入学生的个数、每个学生名字及分数,最后显示获得最高分的学生的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: Java黑皮书课后题第5章:5.8(找出
 - 下一篇: Java黑皮书课后题第5章:5.10(找