請(qǐng)問Scanner在輸入回車后,如何才能退出?
package?com.imooc; import?java.util.Scanner; /*@kernal ?*?功能描述: ?*?為指定成績(jī)加分,直到分?jǐn)?shù)大于等于?60?為止, ?*?輸出加分前和加分后的成績(jī),并統(tǒng)計(jì)加分的次數(shù). ?*/ public?class?addScore?{ public?static?void?main(String[]?args)?{ System.out.print("請(qǐng)輸入需要加分的成績(jī):"); Scanner?sc?=?new?Scanner(System.in); int?score?=?sc.nextInt(); if?(score?>=?60)?{ System.out.print("您的輸入有誤,請(qǐng)重新輸入(小于60的數(shù)字):?"); Scanner?sc2?=?new?Scanner(System.in); int?scoreRtry?=?sc2.nextInt(); System.out.println("重新輸入后需要加分的成績(jī)?yōu)椋?+scoreRtry+"分"); sc2.close(); int?count=0; for(;scoreRtry<=60;scoreRtry++) { while(scoreRtry?<?60) { scoreRtry++; count++; } System.out.println("重新輸入后加分的成績(jī)?yōu)椋?+scoreRtry+"分"); System.out.println("重新輸入后加分的次數(shù)為:"+count); } }else?if?(score?<?60) { System.out.println("加分前的成績(jī)?yōu)椋?+score+"分"); sc.close(); int?count=0; for(;score<=60;score++) { while(score?<?60) { score++; count++; } System.out.println("加分后的成績(jī)?yōu)椋?+score+"分"); System.out.println("加分的次數(shù)為:"+count+"次"); } }else?{ System.out.println("###########"); } } }
老師,你好,這是我寫的代碼,我想要加入一個(gè)當(dāng)Scanner輸入回車后,直接退出并提示“輸入有誤”的功能,毫無頭緒,o(╯□╰)o ,@laurenyang ? O(∩_∩)O謝謝
2016-05-05
雖然不清楚你的具體要求,不過你可以嘗試拋出異常(后面的課程)來實(shí)現(xiàn)
2016-05-05
Sorry,沒有看清楚你的具體要求。
我覺得沒有必要吧,如果什么都不輸,直接回車。程序默認(rèn)還是提示你繼續(xù)輸入,如果輸入的不是自定義的int型信息,程序直接報(bào)錯(cuò)的。
2016-05-05
/*
?* 功能描述:
?* 為指定成績(jī)加分,直到分?jǐn)?shù)大于等于 60 為止,
?* 輸出加分前和加分后的成績(jī),并統(tǒng)計(jì)加分的次數(shù).
?*/
import java.util.Scanner;
?
public class addScore{
public static void main(String[] args){
System.out.println("請(qǐng)輸入需要加分的成績(jī):");
Scanner sc = new Scanner(System.in);
int score = sc.nextInt();
int count=0;
//先循環(huán)判斷輸入的成績(jī)是否大于等于60,如果大于等于的話,提示用戶重新輸入,直到輸入的成績(jī)小于60,退出循環(huán);
while(score>=60){
System.out.println("您的輸入有誤,請(qǐng)重新輸入(小于60的數(shù)字): ");
score = sc.nextInt();
if(score<60){
break;//直到輸入的成績(jī)小于60,退出循環(huán);
}
}
while (score<60) {
score++;
count++;
}
System.out.println("加分后的成績(jī)?yōu)?+score);
System.out.println("加分次數(shù)為"+count);
}
}
我也是初學(xué)者,代碼可能不是很簡(jiǎn)潔,但是可以滿足你的要求。
2016-05-05
..直接關(guān)閉就可以了