当前位置: 首页 > 知识库问答 >
问题:

线程“main”java.lang.NumberFormatException中的异常:对于输入字符串:

司徒英卓
2023-03-14

我正在研究背包问题,我是Java新手。我可以像这样手动添加数字:

 // Fill the bag of weights. 
 //myWeights.bagOfWeights.add(18);
 //myWeights.bagOfWeights.add(2);
 //System.out.println("Possible answers: ");
 //myWeights.fillKnapSack(20);
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);
    }
    
    

谢谢你的帮助。

共有1个答案

吕衡
2023-03-14

您正在使用字符串18 7 4 6调用ParseInt方法。由于这不是有效的整数,因此引发NumberFormatException。

您已经将输入拆分字符串[]sar。在for循环中,您已经对sar中的每个值调用了parseint,这些值都是有效的整数。好像你什么都准备好了;只需删除int target=integer.parseint(input);行。

 类似资料: