Exception in thread "main" java.util.InputMismatchException in Java - 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.

Related

Unable to take input from console in 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.

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.

How do input characters into an array through user input?

This is essentially what i have, everything works fine, but for some reason I'm not able to input the characters into the array.
If you could explain to me why it isn't working it would be greatly appreciated.
The purpose of this is to input a series of characters into an array, and to count the number of ' ' (gaps) present within it.
The part in bold is where I'm currently having my issue.
import java.util.*;
public class Test4c{
public static void main(String[] args){
Scanner x = new Scanner(System.in);
Scanner a = new Scanner(System.in);
int size;
System.out.println("Please input the size of the array.");
size = x.nextInt();
char[] test = new char[size];
System.out.println("Please input " + size + " characters.");
//ask user to input number of characters
for(int i = 0; i<size; i++){
**test[i] = a.next().toCharArray();**
}
int s;
int e;
System.out.println("Please input the starting value of the search.");
s = x.nextInt();
System.out.println("Please input the ending value of the search.");
e = x.nextInt();
}
public static int spaceCount(char[]arr, int s, int e){
int count = 0;
if (s<= e) {
count = spaceCount(arr,s+1, e);
/*counter set up to cause an increase of "s" so
* the array is traversed until point "e"*/
if (arr[s] == ' ' ) {
count++;
}
}
return count;// return the number of spaces found
}
}
when you force to run your code, you get such error stack
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - incompatible types: char[] cannot be converted to char
at test4c.Test4c.main(Test4c.java:26) Java Result: 1
It is obviously clear why you get such a message?
you try to insert a char array inside an index of char[] test which accept a char not a char array
This is what you have:
for(int i = 0; i<size; i++){
test[i] = a.next().toCharArray();
}
From what you have, I think you want just to convert to a.next() to char array which is test which you have already defined
char[] test = new char[size];
you can change what you have to
test = a.next().toCharArray();
The issue is that the toCharArray returns an array, and you can't put an array into an array. Try this:
Char[] test = a.next().toCharArray();

Take a single line input of numbers, and storing it into an array

import java.util.Scanner;
class HistogramChart
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the population of data: ");
int populationOfData = scan.nextInt();
System.out.println("Please enter data separated by spaces: ");
String data = scan.next();
int indexWhiteSpace = data.indexOf(" ");
int[] dataArray = new int[populationOfData];
int tempInt = 0;
for(int index = 0; index < populationOfData; index++)
{
String tempString = data.substring(0, indexWhiteSpace);
data = data.substring(indexWhiteSpace+1, data.length());
tempInt = Integer.parseInt(tempString);
dataArray[index] = tempInt;
indexWhiteSpace = data.indexOf(" ");
}
System.out.println(dataArray[0]);
}
}
I realize there's nothing yet to print out the entire array, as i'm just trying to get it to print anything, but this is continually printing the following errors:
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1954)
at HistogramChart.main(HistogramChart.java:22)
"
I cannot figure out why this is saying this.
Please help!
Why not using split ?
class HistogramChart {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter data separated by spaces: ");
String data = scan.nextLine();
String tmpDataArray[] = data.split(" ");
int dataArray[] = new int[tmpDataArray.length];
for (int i = 0; i < dataArray.length; ++i) {
dataArray[i] = Integer.parseInt(tmpDataArray[i]);
}
}
If I remember correctly, using
String data = scan.next();
Like you're doing, you will just scan a single element. Try using scan.nextLine() so that it takes the whole line, and then split by spaces so you get an array of your data. And the problen it is actually giving you is because you look for indexOf(" ") but since you're not reading a full line, that nevers happens and you get a -1. When you try to look for a substring with the index -1, then you get that error.

"exception in thread main java.lang.arrayindexoutofboundsexception" when using an array + for loop

when I wrote this code to prompt the user for how many numbers are going to be entered, I got an error saying: "exception in thread main java.lang.arrayindexoutofboundsexception"
PS: note that I used an array of int + for loop to write it.
import java.util.*;
public class Pr8{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
//Prompt the user for how many numbers are going to be entered.
System.out.print("*Please write how many numbers are going to be entered: ");
int a = scan.nextInt();
int[] n = new int[a];
for (int i = 0; i < a; i++){
System.out.print("*Please enter an enteger: ");
n[a] = scan.nextInt();
}//for
}//main
}//Pr8
Change
n[a] = scan.nextInt();
to
n[i] = scan.nextInt();
a is not a valid index in an array that only has a elements. The valid indices are 0 to a-1.

Categories