nextInt()與nextLine()方法連用時問題

在nextInt(),next(),nextDouble(),nextFloat()方法與nextLine()連用並放在nextLine()前面時,就會出現如下錯誤:

            System.out.println("請輸入矩陣的行數:");
        int rows = scanner.nextInt();
        
        System.out.println("請輸入一個矩陣字符串,不包含空格:");
        String tmp = scanner.nextLine();
        
        System.out.println("請輸入矩陣的列數:");
        int cols = scanner.nextInt();
 
        System.out.println("請輸入要查詢的字符串:");
        String str = scanner.nextLine();

        scanner.close();  



  nextLine()並未讀取任何輸入,直接轉到了下一行。
    問題分析:
        nextLine()會把nextInt(),next(),nextDouble(),nextFloat()的結束換行符作爲字符串讀入,進而不需要從鍵盤輸入字符串nextLine便已經轉向了下一條語句執行。
    解決辦法:
        在每一個nextInt(),next(),nextDouble(),nextFloat()後都加一個nextLine()語句,將被next()去掉的Enter過濾掉。
代碼如下:
            System.out.println("請輸入矩陣的行數:");
        int rows = scanner.nextInt();
        scanner.nextLine();

        System.out.println("請輸入一個矩陣字符串,不包含空格:");
        String tmp = scanner.nextLine();
        
        System.out.println("請輸入矩陣的列數:");
        int cols = scanner.nextInt();
        scanner.nextLine();
        
        System.out.println("請輸入要查詢的字符串:");
        String str = scanner.nextLine();
        
        scanner.close();
        //SolutionMethod2 solution2 = new SolutionMethod2();
        System.out.println("矩陣中是否包含該字符串:");  

    運行結果:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章