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.
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.
Related
when i try to run below error code but getting error, i also used "givenArray[i] = sc.next(); or givenArray[i] = sc.nextLine(); " but still failing.
I tried many different ways but still got the same error.
it seems Scanner is unable to read the array
I need help with this code please, Thank you in advance.
Input provided:
Enter length of first Array: 4 and hit enter,
Enter length of second Array: 4 and hit enter,
Enter First array: 2,3,4,5 and hit enter then it throws the below error.
private static boolean firstAndLastTwoArray(int[] firstArray, int[] secondArry){
int firsIndexOFirstArray = firstArray[0];
int lastIndexOfSecondArray = secondArry[secondArry.length -1];
if (firsIndexOFirstArray == lastIndexOfSecondArray) {
return true;
}else {
return false;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter length of first Array: ");
int firstArray = sc.nextInt();
int[] givenArray = new int[firstArray];
System.out.println("Enter length of second Array: ");
int secondArray = sc.nextInt();
int[] givenArray1 = new int[secondArray];
for (int i = 0; i <firstArray; i++) {
System.out.println("Enter First array:");
givenArray[i] = sc.nextInt();
for (int k = 0; k <secondArray; k++){
System.out.println("Enter Second array:");
givenArray1[k] = sc.nextInt();
}
}
System.out.println("Result is: " + firstAndLastTwoArray(givenArray,givenArray1));
}
error:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at w3Resource.Exercise76.main(Exercise76.java:54)
You should enter array elements one by one. Do not enter with comma separated. It will be considered as String not int.
Else, remove the for loop and get the array elements as comma separated using nextLine(), then split the input string based on ',' using string.split(",") which returns an array.
I am new to Java and facing problem while taking input from the console.
Here's my code:
import java.util.*;
class solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
System.out.println(t);
for (int n = 0; n < t; n++) {
for (int i=0;i<4;i++){
int mzeroes = sc.nextInt();
int nones = sc.nextInt();
int stringLength = sc.nextInt();
String string=sc.nextLine();
System.out.println(mzeroes);
System.out.println(nones);
System.out.println(stringLength);
System.out.println(string);
}
}
}
}
Input:
2
2 2 8 11101000
3 4 16 0110111000011111
Error:
Exception in thread "main" java.util.InputMismatchException: For input string: "0110111000011111"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at solution.main(solution.java:13)
I tried the same code but there were no errors and it executed successfully. I think you are making the mistake while giving the input. This is how the input has to be given :
As the first input is two so it will ask for two inputs in the loop and then when you pass the first input for the loop it will print out the there 3 ints one after other and the remaining string at the end. And the same goes for the second input of the loop.
Note: The String string = sc.nextLine(); will give you the string so space before the last number will also be taken in the string.
Hope this helps.
How do I input an array whose length may vary? The input is space delimited and ends when I press enter
public class ArrayInput {
public static void main(String args[]){
ArrayList<Integer> al = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
while(){//what condition to use here?
al.add(sc.nextInt());
}
}
}
An example would be:
1 2 5 9 7 4 //press enter here to mark end of input
Since all your input is in a single line, you can read the entire line and then split it to integers :
String line = sc.nextLine();
String[] tokens = line.split(" ");
int[] numbers = new int[tokens.length];
for (int i=0; i<numbers.length;i++)
numbers[i] = Integer.parseInt(tokens[i]);
Read the entire line using sc.nextLine() and then split() using \\s+. This way, you don't have to worry about size of input (number of elements). Use Integer.parseInt() to parse Strings as integers.
I am very new to java. I am trying to prompt the user to enter 4 integer numbers followed by a space and eventually print them out at the end. I am a little confused with the order of how I write things out and using the split(" ");
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter 4 integer numbers here: ");
int numbers = keyboard.nextInt();
// Need split(" "); here?
} // End main string args here
} // End class calculations here
Any help or advice is appreciated. I have looked at other ways on stackoverflow but somehow I keep getting errors.
Read it in one String with keyboard.nextLine
Use the split method of String for get an array of Strings
Convert every element of the array to int with Integer.parseInt
Print your ints.
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter 4 integer numbers here: ");
// Scan an entire line (containg 4 integers separated by spaces):
String lineWithNumbers = Keyboard.nextLine();
// Split the String by the spaces so that you get an array of size 4 with
// the numbers (in a String).
String[] numbers = lineWithNumbers.split(" ");
// For each String in the array, print them to the screen.
for(String numberString : numbers) {
System.out.println(numberString);
}
} // End main string args here
} // End class calculations here
This code will print all numbers, in case you actually want to do something with the Integers (for example mathematical operations) you can parse the String to an int, like so:
int myNumber = Integer.parseInt(numberString);
Hope this helps.
If would suggest to use the abilities of the Scanner class to retrieve numbers from the user input:
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[4];
System.out.println("Enter 4 integer numbers here: ");
for (int i = 0; i < 4 && keyboard.hasNextInt(); i++) {
numbers[i] = keyboard.nextInt();
}
System.out.println(Arrays.toString(numbers));
This code creates an array of size 4 and then loops over the user input reading the numbers from it. It will stop parsing the input if he has the four numbers, or if the user enters something different than a number. For example, if he enters 1 blub 3 4, then the array will be [1, 0, 0, 0].
This code has some advantages compared to the nextLine approaches of the over answers:
you don't have to care about the integer conversion (exception handling)
you can either write these number onto one line or each number on its own line
If you like to read an arbitrary amount of numbers, then use a List instead:
List<Integer> numbers = new ArrayList<>();
System.out.println("Enter some integer numbers here (enter something else than a number to stop): ");
while (keyboard.hasNextInt()) {
numbers.add(keyboard.nextInt());
}
System.out.println(numbers);
I am a novice Java student and am trying to complete a program that uses the scanner to input 5 students' names, and then a loop within to get 3 grades for each student. I am stuck as I keep getting an Input Mismatch error and I don't know why. I have tried to correctly match what kinds of input are coming in to the variables. Any help would be greatly appreciated!
This is what I have:
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Declare arrays, grades to hold [student #][course] and correspond to the grade. studentNames to be paralell and hold the names.
int [][] grades;
grades = new int[5][3];
String[] studentNames = new String[5];
int studentNumber = 0;
int courseNumber = 0;
// Create loops to put values in both arrays, using student# as a counter
if (studentNumber < 5) {
System.out.println("Enter the student name");
studentNames[studentNumber] = input.next();
// Nested loop to enter the grades
if (courseNumber < 5) {
System.out.println(" Enter a grade for " + studentNames[studentNumber]+" for course #" + courseNumber);
grades[studentNumber][courseNumber] = input.nextInt();
courseNumber = courseNumber + 1;
}
studentNumber = studentNumber + 1;
}
}
}
And this is what I get:
Exception at thread "main" java.util.InputMismatchException
at java.util.Scanner.throwfor{Scanner.java:909}
at java.util.Scanner.next{Scanner.java:1530}
at java.util.Scanner.nextInt{Scanner.java:2160}
at java.util.Scanner.nextInt{Scanner.java:2119}
at StudentGrades.main{StudentGrades.java:20}
Your problem is in line 20.
grades[studentNumber][courseNumber] = input.nextInt();
that means that in the input, it is expecting an int, but it founds another thing, like a double, a char array or anything else
There is also another problem, you declare your grades as:
grades = new int[5][3];
the last number means that you can access to grades from [0..4][0..2]
but your if statement:
if (courseNumber < 5)
means that you will access to a number higher than '2' in
grades[studentNumber][courseNumber] = input.nextInt();
which will raise an OutOfBoundsException
From the docs:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
From your stack trace:
Exception at thread "main" java.util.InputMismatchException
at java.util.Scanner.throwfor{Scanner.java:909}
at java.util.Scanner.next{Scanner.java:1530}
at java.util.Scanner.nextInt{Scanner.java:2160}
at java.util.Scanner.nextInt{Scanner.java:2119}
at StudentGrades.main{StudentGrades.java:20}
the Exception is being thrown by your call to nextInt.
Thus, you're getting an exception because you're requesting an integer and the Scanner is finding something that's not an integer.
Yes, like others have suggested, your problem in in the line:
grades[studentNumber][courseNumber] = input.nextInt();
Because your input is not recognised as an integer.
You should also be aware that your code will not loop through five times, it will go through once and exit since if statements do not repeat.
To loop you should probably use a for loop, something along these lines:
for(int i = 0; i < 5; i++){
//You code should be the same in here
}
Or change your if's to while.