首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 控制台輸入邏輯錯誤導致程序無輸出的排查

     編輯:程式設計綜合問答

問題代碼

Scanner in = new Scanner(System.in);
System.out.print("請輸入您的姓名,性別,年齡,java成績:");
String nname = in.nextLine();
String nsex = in.nextLine();
int nage = in.nextInt();
float nscore = in.nextFloat();
// ... 後續無提示直接等待輸入,用戶不知所措

核心問題

  1. 提示信息不清晰:一次性打印四項提示,用戶不知按何順序、何時按 Enter。
  2. 緩衝區殘留換行符:nextInt()/nextFloat() 後未消耗換行符,若後續有 nextLine() 會讀空行 (本例無後續但屬隱患)。

修正版代碼

Scanner in = new Scanner(System.in);

System.out.print("請輸入您的姓名: ");
String nname = in.nextLine();

System.out.print("請輸入您的性別: ");
String nsex = in.nextLine();

System.out.print("請輸入您的年齡: ");
int nage = in.nextInt();

System.out.print("請輸入您的java成績: ");
float nscore = in.nextFloat();
in.nextLine(); // 消耗殘留換行符,良好習慣

Student stu = new Student();
stu.name = nname;
stu.sex = nsex;
stu.age = nage;
stu.score = nscore;
stu.speak("年齡:" + stu.age + "歲;");
stu.grade(stu.score);

關鍵改進點

  • 分步提示:每個輸入前單獨 print 提示,用戶體驗清晰。
  • 緩衝區處理:最後補 in.nextLine() 防止後續邏輯中 nextLine() 讀空。
  • 異常捕獲:生產代碼應包裹 try-catch 處理 InputMismatchException。

Student 類參考實現

class Student {
    String name, sex;
    int age;
    float score;
    
    public void speak(String inStr) {
        System.out.printf("自我介紹:我叫%s; 性別:%s; %s%n", name, sex, inStr);
    }
    public void grade(float inScore) {
        System.out.printf("java成績:%.1f%n", inScore);
    }
}

運行效果示例

請輸入您的姓名: 張三
請輸入您的性別: 男
請輸入您的年齡: 20
請輸入您的java成績: 95.5
自我介紹:我叫張三; 性別:男; 年齡:20歲;
java成績:95.5
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved