2012-11-05 64 views
1

好的,所以我在編程任務時遇到了很多麻煩。我們將從文本文件中讀取信息並使用我們創建的某些方法對其進行格式化。我能夠從文本文件的第一行中讀取信息,但後綴出現錯誤。我的代碼如下:如何在java中解析多個字符串到int中

String name1 = scan.nextLine(); 
    String name2 = scan.nextLine(); 
    scan.close(); 
    int length = name1.length(); 
    int count = 0; 
    int a = 0; 
    int b = 1; 
    while(end != true) 
    { 

     String check = name1.substring(a,b); 
     a++; 
     b++; 
     count++; 
     char z = check.charAt(0); 
     if(z == '0' || z == '1' || z == '2' || z == '3' || z == '4' || z == '5' || z == '6' || z == '7' || z == '8' || z == '9') 
     { 
      end = true; 

     } 
     if(count == length) 
     { 
      end = true; 

     } 
    } 
    String number1 = name1.substring(count,length); 
    int number01 = Integer.parseInt(number1); 
    name1=name1.substring(0, count-1); 
    int d = name1.indexOf(" "); 
    int length1 = name1.length(); 
    String name1first = name1.substring(0,d); 
    name1first = name1first.trim(); 
    String name1last = name1.substring(d,length1); 
    name1last = name1last.trim(); 

    System.out.println(name1first); 
    System.out.println(name1last); 
    System.out.println(number01); 


    length = name2.length(); 
    int countt = 0; 
int aa = 0; 
int bb = 1; 
    while(end != true) 
    { 

     String check = name2.substring(aa,bb); 
     aa++; 
     bb++; 
     countt++; 
     char z = check.charAt(0); 
     if(z == '0' || z == '1' || z == '2' || z == '3' || z == '4' || z == '5' || z == '6' || z == '7' || z == '8' || z == '9') 
     { 
      end = true; 

     } 
     if(countt == length) 
     { 
      end = true; 

     } 
    } 
    String number2 = name2.substring(countt,length); 
    int number02 = Integer.parseInt(number2); 
    name2=name2.substring(0, countt-1); 
    d = name2.indexOf(" "); 
    int length2 = name2.length(); 
    String name2first = name2.substring(0,d); 
    name2first = name2first.trim(); 
    String name2last = name2.substring(d,length2); 
    name2last = name2last.trim(); 

    System.out.println(name2first); 
    System.out.println(name2last); 
    System.out.println(number02); 

,我得到這個錯誤:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Jennifer Sutter 52114" 
at java.lang.NumberFormatException.forInputString(Unknown Source) 
at java.lang.Integer.parseInt(Unknown Source) 
at java.lang.Integer.parseInt(Unknown Source) 
at Salary.main(Salary.java:101) 
+1

錯誤告訴你到底你在做什麼錯:你試圖將非數字文本解析爲一個數字,而這顯然不起作用。解決方案:不要這樣做。 –

+1

但除此之外,你想做什麼? –

+0

我以爲我分開了我的代碼中的文本值的數值。這就是while循環是 – user1799156

回答

0

這可是顯而易見的,爲什麼你得到例外:

你想轉換「珍妮弗·薩特52114「爲一個整數。

解決方法是首先使用try{}catch()塊,同時嘗試呼叫Integer.parseInt()

我認爲什麼是你想要得到的字符串的最後一點,並將其轉換爲整數:既然你使用Scanner你可以在上面nextInt()像這樣:

new Scanner(theStringWhichMightHaveANumber).nextInt();

+0

雖然這是怎麼發生的?在第一個代碼塊中,我做的是完全相同的事情,它只將數字轉換爲整數 – user1799156

+0

@ user1799156我沒有必須對其進行測試的完整代碼,因此我實際上無法給您一個理由對於這個問題! –