2017-10-11 132 views
0

我正在研究揹包問題,我是Java新手。我可以手動添加這樣的數字:線程「main」中的異常java.lang.NumberFormatException:對於輸入字符串:

// Fill the bag of weights. 
//myWeights.bagOfWeights.add(18); 
//myWeights.bagOfWeights.add(2); 
//System.out.println("Possible answers: "); 
//myWeights.fillKnapSack(20); 

但是,我不能讓用戶輸入數字。
第一個數字應該是權重之後的目標。
所以我試圖把用戶輸入作爲一個字符串,並用空格分開,然後將其轉換爲整數。
接下來,我試圖做parseInt 2種方式,但我都沒有成功。
下面是代碼:

import java.util.*; 
 
    
 
    public class KnapSackWeights{ 
 
    
 
    private Sack bagOfWeights = new Sack(); 
 
    private Sack knapSack = new Sack(); 
 
    
 
    public static void main(String[] args){ 
 
     KnapSackWeights myWeights = new KnapSackWeights(); 
 
     Scanner in = new Scanner(System.in); 
 
     System.out.println("Enter the input:"); 
 
     String input = in.nextLine(); 
 
     String[] sar = input.split(" "); 
 
     //System.out.println(inp); 
 
     int target = Integer.parseInt(input); 
 
     System.out.println(target); 
 
     
 
     int[] weights_array = new int[26]; 
 
     
 
     int n = input.length()-1; 
 
     for(int i=1; i<=n; i++) 
 
     { 
 
      weights_array[i - 1] = Integer.parseInt(sar[i]); 
 
     } 
 
     int k = weights_array[0]; 
 
     myWeights.bagOfWeights.add(target); 
 
     //System.out.println(target); 
 
     System.out.println("Possible answers: "); 
 
     myWeights.fillKnapSack(k); 
 
     //myWeights.fillKnapSack(Integer.parseInt(sar[0])); 
 

 
     // Fill the bag of weights. 
 
     //myWeights.bagOfWeights.add(11); 
 
     //myWeights.bagOfWeights.add(8); 
 
     //myWeights.bagOfWeights.add(7); 
 
     //myWeights.bagOfWeights.add(6); 
 
     //myWeights.bagOfWeights.add(5); 
 
     //myWeights.bagOfWeights.add(4); 
 
     
 
     //System.out.println("Possible answers: "); 
 
     //myWeights.fillKnapSack(20); 
 
    } 
 
    
 

以下是錯誤:

Exception in thread "main" java.lang.NumberFormatException: For input string: "18 7 4 6" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at KnapSackWeights.main(KnapSackWeights.java:18)

感謝您的幫助。

+0

你在''String [] sar''中分割''input'',但你甚至沒有使用它。你最終解析這行,當然''Integer''不能用空格解析這樣的字符串。 –

+0

@SchiduLuca有沒有辦法解決這個問題?從String到整數的轉換不能正常工作。所以如果我不用空格解析字符串,那應該解決它? – user8581463

回答

0

您正在使用字符串18 7 4 6調用parseInt方法。由於這不是有效的整數,因此拋出NumberFormatException。

您已將輸入拆分爲String[] sar。在for循環中,您已在sar的每個值上調用parseInt,它們是有效的整數。似乎你擁有一切;只需刪除int target = Integer.parseInt(input);一行。

+0

如果我刪除目標,我可以添加到myWeights.bagOfWeights.add(target);爲它添加內容? – user8581463

+0

@ user8581463這取決於;你想在那裏放什麼?現在'.add(target);'由於例外而沒有達到,如果達到了,它不會對你有任何好處,因爲'target' _不是有效的int。我假設你想放在那裏的int在'sar'數組中,所以你從那裏得到它。 –

+0

插入sar數組也會給我一個錯誤:ArrayIndexOutOfBoundsException:4對於weight_array [i - 1] = Integer.parseInt(sar [i])行; – user8581463

相關問題