Unable to take input from console in java - java

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.

Related

Exception in thread "main" java.util.InputMismatchException in Java

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.

loop based on user input java

I want to write a program that queries the user for a "number n" and then output the word repetition n times.
For example the word is "Hello".
So far I've got this:
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Zahl 1:");
int number = scanner.nextInt();
}
Which should end in this ->
Number: 3
Hello
Hello
Hell
.
I don't know how to move forward.
I thank you for your time in advance!
You can use functional programming.
IntStream.range(0, n)
.forEach(System.out.println(variable));
Here n is the number of times that string is to be printed and a variable is a string.
This code out print "Hallo" n times (n = numbers)
String s = "Hello";
for (int i = 0; i < number; i++){
System.out.println(s);
}

Exception in thread "main" java.lang.NumberFormatException: For input string:

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.

NumberFormat Exception during string parsing in Java

I'm writing my solution for a problem which involves, among other things, parsing a string which contains numbers entered by the user, separated with spaces and then storing them as integers.
I'm not sure why I get a numberformat exception, when I'm using the nextLine() method to first accept the string (including spaces) and then using the split method to separate out the integers. What's still weird is that the code has worked in a different problem before, but not here apparently.
Here's the code, and the exception message:
package algorithms.Warmup;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by manishgiri on 4/8/15.
*/
public class ChocolateFeastTest {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter number of test cases:");
int T = sc.nextInt();
ArrayList<Integer> result = new ArrayList<>(T);
for(int i = 0; i < T; i++) {
int[] numbers = new int[3];
System.out.println("Enter N, C, M separated by spaces");
String next = sc.nextLine();
String[] nextSplit = next.split(" ");
int item;
for(int p = 0; p < 3; p++) {
item = Integer.parseInt(nextSplit[p]);
numbers[p] = item;
}
int N = numbers[0];
int C = numbers[1];
int M = numbers[2];
System.out.println(N + C + M);
}
}
}
And the exception messages:
Enter number of test cases:
2
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
Enter N, C, M separated by spaces
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at algorithms.Warmup.ChocolateFeastTest.main(ChocolateFeastTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 1
On tracing the exception, it looks like the error occurs in the line when I use Integer.parseInt(), but even before that, why doesn't the code read in the numbers (with spaces) in the first place? ie: this line doesn't work:
String next = sc.nextLine()
I'd appreciate any help!
You're using nextInt() which only reads the integer, not the new line character \n at the end of the line.
Therefore, when you press an integer and then enter, the line:
int T = sc.nextInt();
Only reads the integer. Next when you do:
String next = sc.nextLine();
It reads the new line character waiting in the input to be read.
Simply change to:
int T = Integer.parseInt(sc.nextLine());
(But of course, doing try/catch on that would be much better)
The problem is nextInt() doesnt use full line so when you do String next = sc.nextLine(); It reads the same line resulting the error.
Problem can be solved by
int T = sc.nextInt();
nextLine(); //adding a next line after nextInt()
I just changed: int T = sc.nextInt();
To: int T = Integer.parseInt(sc.nextLine());
This seems to work.
I tried using BufferedReader and it worked.
Here is the code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
public class ChocolateFeastTest {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
System.out.println("Enter number of test cases:");
int T = sc.nextInt();
ArrayList<Integer> result = new ArrayList<>(T);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i < T; i++) {
int[] numbers = new int[3];
System.out.println("Enter N, C, M separated by spaces");
String next = br.readLine();
String[] nextSplit = next.split(" ");
int item;
for(int p = 0; p < 3; p++) {
item = Integer.parseInt(nextSplit[p]);
numbers[p] = item;
}
int N = numbers[0];
int C = numbers[1];
int M = numbers[2];
System.out.println(N + C + M);
}
}
}
You need to call 'sc.nextLine()' twice, in order to take the input from the next line. The first call will take you to the next line and the second call will grab the input on the second line.
String next = sc.nextLine();
next = sc.nextLine();

Scanner object behaves differently for Integer vs String inputs [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Scanner issue when using nextLine after nextInt
In the following two code snippets, I first ask for the number of inputs required and let the user input that many inputs of a particular kind. When the required inputs are String types, it takes one less input unless I use s.next() first, while for Integers it works fine. I don't understand why. Can someone please explain?. Thanks
First Code with String inputs and nextLine function:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
String[] inputs = new String[num];
for (int i = 0; i < inputs.length; i++) {
inputs[i]=s.nextLine();
}
System.out.println("end of code");
}
Second Code with Integer inputs and nextInt function:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
Integer[] inputs = new Integer[num];
for (int i = 0; i < inputs.length; i++) {
inputs[i]=s.nextInt();
}
System.out.println("end of code");
}
It is because of the following line:
int num = s.nextInt();
Your next INT only returns the INT until it gets to the \n character.
If you had a test file like this:
4
1
2
3
4
Your character code will look like this:
4'\n'
1'\n'
2'\n'
3'\n'
4'\n'
So when you grab the integer, it will grab the 4 for your "nextInt()" method on the scanner. When you tell it to grab the next line "nextLine()", it will grab the remainder of that line which is just '\n' and store nothing into the first value into your array.
On the reverse side, if you tell it to grab the next integer "nextInt()", it will search until it finds the next integer, which will cause the 1 to go into the first value into the array.

Categories