Reputation: 19
I am working on the knapsack problem, I am new to Java. I am able to add numbers manually like this in the main:
// Fill the bag of weights.
//myWeights.bagOfWeights.add(18);
//myWeights.bagOfWeights.add(2);
//System.out.println("Possible answers: ");
//myWeights.fillKnapSack(20);
However, I am not able to allow the user to input the numbers.
The first number should be the target followed by the weights.
So I have tried to take the user input as a string and split it up with whitespace, and then convert it to an integer.
Next, I tried to do the parseInt 2 ways, but I was unsuccessful both way.
Here is the code:
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);
}
Here is the error:
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)
Thanks for your help.
Upvotes: 1
Views: 32626
Reputation: 1
maybe this could be helpful
//your input
String input = "18 7 4 6";
//split into string array by space
String[] split = input.split(" ");
int[] nums = new int[split.length];
//parse each string into number
for (int i = 0; i < split.length; i++) {
nums[i] = Integer.parseInt(split[i]);
}
System.out.println(Arrays.toString(nums));
Upvotes: -1
Reputation: 925
You are calling the parseInt
method with the String 18 7 4 6
. Since this isn't a valid Integer, the NumberFormatException is thrown.
You are already splitting the input into the String[] sar
. In the for
loop you already call parseInt
on each value in sar
, which are valid Integers. Seems like you have everything in place; just remove the int target = Integer.parseInt(input);
line.
Upvotes: 0