0

時,這是我的代碼InputMismatchException時使用Sacnner nextLine絃樂

import java.io.*; 
import java.util.*; 
class student 
{ 
    String name; 
    int age; 
    float cgpa; 
} 
public class getdata 
{ 

    public static void main(String args[]) throws IOException 
    { 
     Scanner in=new Scanner(System.in); 
     int n; 
     n=in.nextInt(); 
     student[] s=new student[n]; 
     for(int i=0;i<n;i++) 
     { 
      try 
      { 
       s[i]=new student(); 
       s[i].name=in.nextLine(); 
       in.nextLine(); 
       s[i].age=in.nextInt(); 
       s[i].cgpa=in.nextFloat(); 
      } 
      catch(InputMismatchException e) 
      { 
       System.out.println(e.getMessage()); 
      } 
     } 
     System.out.println(); 
     System.out.println("Name\tAge\tCGPA\n"); 
     for(int i=0;i<n;i++) 
     { 
      System.out.println(s[i].name+"\t"+s[i].age+"\t"+s[i].cgpa+"\n"); 
     } 
    } 
} 

編譯程序沒有給出問題。但是當執行時,我嘗試輸入一個字符串空間,它將字符串作爲兩個單獨的字符串,並將其中一個的所有其他值指定爲null。爲例如,如果我輸入

mike hannigan 
5 
6.5 

輸出是

mike 0 0.0 
hannigan 5 6.5 

我試圖獲得僅具有單個in.nextLine();的字符串,但導致要採取的字符串作爲空(拋出InputMismatchException時)。用try和catch塊

with try block

並沒有try塊,這是輸出我得到

enter image description here

+0

這是因爲'nextInt'和'nextFloat'不會消耗換行符,所以後續的'nextLine'不會捕獲您期望的結果。我確定有一個重複的地方解釋了這個... – 4castle

回答

2

我的建議是始終掃描整個行字符串,並將其轉換爲所需的數據類型使用解析方法。請看下面:

public static void main(String args[]) throws IOException 
{ 
    Scanner in=new Scanner(System.in); 
    int n; 
    n=Integer.parseInt(in.nextLine()); 
    student[] s=new student[n]; 
    for(int i=0;i<n;i++) 
    { 
      s[i]=new student(); 
      s[i].name=in.nextLine(); 
      s[i].age=Integer.parseInt(in.nextLine()); 
      s[i].cgpa=Float.parseFloat(in.nextLine()); 

    } 
    System.out.println(); 
    System.out.println("Name\tAge\tCGPA\n"); 
    for(int i=0;i<n;i++) 
    { 
     System.out.println(s[i].name+"\t"+s[i].age+"\t"+s[i].cgpa+"\n"); 
    } 
} 
0

你的問題是在理解Scanner很常見的錯誤。

調用nextInt()nextFloat()或大多數其他nextXxx()方法將在未處理的數字後面留下換行符。

到任何的nextXxx()方法的後續調用,以外nextLine(),會自動跳過換行符,作爲標記之間的空白。

然而,nextLine()確實跳過前導空白,任何其他nextXxx()方法後,因此調用nextLine(),會返回一個空字符串(或者更確切地說,無論是上線的最後一個令牌之後的其餘部分)。

所以,當混合nextXxx()電話與nextLine()電話,你必須通過調用nextLine()第一沖洗(丟棄)前行的末尾。

這意味着你的代碼應該是:

Scanner in = new Scanner(System.in); 
int n = in.nextInt(); 
in.nextLine(); // Ignore rest of line after int 
student[] s = new student[n]; 
for (int i = 0; i < n; i++) { 
    s[i] = new student(); 
    s[i].name = in.nextLine(); 
    s[i].age = in.nextInt(); 
    s[i].cgpa = in.nextFloat(); 
    in.nextLine(); // Ignore rest of line after float 
} 
System.out.println(); 
System.out.println("Name\tAge\tCGPA"); 
for (int i = 0; i < n; i++) { 
    System.out.println(s[i].name + "\t" + s[i].age + "\t" + s[i].cgpa); 
} 

更重要的是,不要將answer by @JaganathanNanthakumar說的話:一定要使用nextLine()和自己分析的數量。

+0

這是非常常見的,所以實際上有一個規範的答案(我鏈接) – 4castle

+0

@ 4castle你說得對,我忘了它是什麼。 – Andreas

+0

當然沒有任何反應的答案。爲OP提供具體的解決方案以獲得想法是很好的。 – 4castle