My input is in this format:
1 2 3 4 5 6
Alice
The array length is not known.
I coded it this way:
import java.util.*;
public class Main
{
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int i=0;
while(sc.hasNext()){
arr.add(sc.nextInt());
}
String player = sc.nextLine();
}
}
But I am getting this 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 Main.main(Main.java:17)
Thanks in advance.
The reason you are seeing java.util.InputMismatchException is because you provided input "Alice" to the statement sc.nextInt(), and the scanner is telling you that it doesn't know how to convert a java.lang.String input to an int (which is the return type of nextInt()).
Here's a very simple example that reproduces the same behavior:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
If you run those two lines and enter a non-integer, like "d", it will throw an exception:
d
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 a91.main(a91.java:6)
To fix it, you need to replace nextInt() with something that is tolerant of non-numeric input, possibly nextLine(). Here is a (very) simple example showing how that could work. Note this is just highlighting the behavior you're asking about, namely: how to address InputMismatchException. As with your original program, there is no loop termination – it will run forever (until you quit the program).
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
while (sc.hasNext()) {
String s = sc.nextLine();
System.out.println("got this: " + s);
}
1 2 3 4 5 6
got this: 2 3 4 5 6
Alice
got this: Alice
You should use hasNextInt to check for integer input. Once no more integers, then just use next() to read the player.
List<Integer> arr = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
arr.add(sc.nextInt());
}
String player = sc.next();
arr.forEach(System.out::println);
System.out.println(player);
Example input's supported
10 20 30 40 50 60 70
Alice
10 20 30 40
50 60 70 Alice
10 20 30
40
50
60 70 Alice
10 20 30
40 50
60 70
Alice
output
10
20
30
40
50
60
70
Alice
Related
In the below code when i enter the input as***(i just don't enter the input one by one instead i copy and paste the entire input)***
4
101
1111
00110
111111
i am supposed to get
5
15
6
63
instead i get
5
15
6
and after i press enter here
i get the 63
import java.util.Scanner;
public class VonNeumanLovesBinary {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int no = scn.nextInt();
while (no > 0)
{
int binary = scn.nextInt();
int i = 0 ;
int sum = 0;
while(binary > 0 )
{
int digit = binary % 10;
sum += Math.pow(2,i) * digit ;
binary /= 10;
i++;
}
System.out.println(sum);
no--;
}
}
}
This code is written Intellij IDE.
Please help me out . this is the problem of the ide ?
Its not the fault of the IDE. It is how it deals with copy-pasting text into the console.
The text is handed over to the Java code as you paste it, line by line. Input is only handed over once you finish the line. The previous lines are all terminated already with a newline symbol but the last line is not.
So you have to either add a newline to the end of your copy-pasta or hit enter to produce one yourself. So before you terminate the last line, the last line is never handed over to Java but is still only in the console.
For example, if you copy pasta this instead:
4
101
1111
00110
111111
(note the last, empty line)
it will work as expected, since you finished the 111111 line, i.e. it is 111111\n and not just 111111.
I'm having some problems with my file reader that uses scanner, and I'm at a bit of a loss at this point. Trying to read the file with scanner but atm I keep getting a java.util.InputMismatchException message which suggests that my scanner.next is putting the wrong files in the wrong arrays? I don't know why this is happening, if someone could point out in my code where I'm screwing up, I'd appreciate it.
Note: Unless it is relevant, ignore the useless variables and the excessively long arrays. I was getting ready to make this into a class and some variables are not used yet.
public static void main(String[] args) throws IOException
{
int playersTotal = 0;
int entries = 0;
int namesIndex = 0;
int attackIndex = 0;
int blockIndex = 0;
String[] playersName = new String[60];
double[] attackScores = new double[60];
double[] blockScores = new double[60];
String file = "roster1.txt";
Scanner scanner = new Scanner(new File(file));
scanner.useDelimiter(" ");
while(scanner.hasNextLine())
{
playersName[namesIndex] = scanner.next();
System.out.println(playersName[namesIndex]);
namesIndex ++;
playersName[namesIndex] = scanner.next();
System.out.println(playersName[namesIndex]);
namesIndex ++;
entries ++;
attackScores[attackIndex] = scanner.nextDouble();
System.out.println(attackScores[attackIndex]);
attackIndex ++;
entries ++;
//problem occurs here:
blockScores[blockIndex] = scanner.nextDouble();
System.out.println(blockScores[blockIndex]);
blockIndex ++;
entries ++;
playersTotal ++;
}
}
This should take every entry separated by a space from a list with both Strings and doubles on every line and save it to their proper arrays. However it only ever reaches the first double on the first line. Attempting to read the next double prompts an exception in thread.
Program output:
Rachael
Adams
3.36
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at VerdeVolleyball.main(VerdeVolleyball.java:37)
list I'm using:
1. Rachael Adams 3.36 1.93
2. Kim Hill 1.53 1.76
3. Tori Dixon 0.92 1.62
4. Alisha Glass 1.96 1.55
5. Cursty Jackson 0.69 1.44
6. Michelle Bartsch 0.28 1.42
7. Alexis Crimes 3.89 1.34
8. Foluke Akinradewo 4.81 1.14
9. Courtney Thompson 0.59 0.93
10. Krista Vansant 2.78 0.86
11. Nicole Fawcett 4.01 0.61
12. Kelly Murphy 1.15 0.58
13. Natalie Hagglund 2.49 0.52
14. Kayla Banwarth 2.98 0.5
15. Lauren Gibbemeyer 2.25 0.5
Try to comment out the line where you specify the delimiter for Scanner instance
scanner.useDelimiter(" ");
and be sure that your Scanner instance uses proper locale when resolving double (. separator instead of ,).
Scanner scanner = new Scanner(new File(file).useLocale(Locale.US);
the part of my code:
public static String[] getNames(int players) {
System.out.println("What are the names of the players?");
String[] playerNames = new String[players + 1];
playerNames[0] = "Dealer";
for (int i = 1; i < players + 1; i++) {
playerNames[i] = input.next();
}
return playerNames;
}
It compiles fine but the problem is when you run it:
How many people are playing?
1
What are the names of the players?
Johny
Bob
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextBoolean(Scanner.java:1782)
at BlackJack.playTurn(BlackJack.java:17)
at BlackJack.everyoneGo(BlackJack.java:36)
at BlackJack.main(BlackJack.java:112)
another part of the code asks the how many people are playing thing and stores the number entered (1 in this case) as the integer players. Therefore [players +1] in the for loop should equal 2 so the for loop should only run once if you have 1 player, first time the check executes 1 < 2 and second time 2 !< 2 so it shouldn't run but it does for some reason, I shouldn't have been able to enter a second name. Anyways immediately after you enter the second name (or third if you said 2 people etc.) you get the exception and error thing.
I also tried putting system.out.println("test1"); right before and test2 right after the line playerNames[i] = input.next(); to see what happens.
this is the result:
How many people are playing?
1
What are the names of the players?
test1
johnny
test2
bob
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextBoolean(Scanner.java:1782)
at BlackJack.playTurn(BlackJack.java:17)
at BlackJack.everyoneGo(BlackJack.java:36)
at BlackJack.main(BlackJack.java:112)
as you can see it also didn't print test1 a second time which was at the beginning of the for loop (before it should have asked for the second name) which is really weird.
Any ideas/solutions?
Thanks
This is some work which I'd much rather figure out myself so could you please not give the answer right out if possible but maybe point me into the right direction to why I am receiving the error from the loop output and why the IF statement is not producing the output.
I have to allow a user input for the 'Recommended maximum staff wage' and then read text from a file of different shop units to work out the staff wages and total staff cost per shop units.
Here is the text I have to read
Unit One
4
32 8
38 6
38 6
16 7
Unit Two
0
Unit Three
2
36 7
36 7
Unit Four
6
32 6.5
32 6.5
36 6.5
36 6.5
38 6.5
38 6.5
...continued up to 9 shop units.
This is my code:
public class Recursion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count =0;
int n = 1;
int t=0;
int triangularNumber =0;
while (n<Integer.MAX_VALUE)
{
t = isTriangularNumber(n,count,triangularNumber);
triangularNumber=0;
int starNumber= ((6*n)*(n-1)) + 1;
if (starNumber ==t)
{
System.out.println(t);
}
n++;
}
if (n==Integer.MAX_VALUE)
{
System.exit(0);
}
}
public static int isTriangularNumber(int n, int count, int triangularNumber)
{
triangularNumber =triangularNumber + (n-(n-count));
if (count<=n)
{
return isTriangularNumber(n,(count++), triangularNumber);
}
else return triangularNumber;
}
}
The printouts for the shop units are fine, but it produces an error after the output, and the output from the if-statement isn't coming out, as displayed below:
Please enter the recommended maximum staff cost:
900
You entered: 900.0
256.0
484.0
712.0
824.0
The total staff cost of Unit One is £824.0
The total staff cost of Unit Two is £0.0
252.0
504.0
The total staff cost of Unit Three is £504.0
208.0
416.0
650.0
884.0
1131.0
1378.0
The total staff cost of Unit Four is £1378.0
208.0
464.0
688.0
944.0
The total staff cost of Unit Five is £944.0
266.0
461.0
653.0
845.0
1037.0
The total staff cost of Unit Six is £1037.0
The total staff cost of Unit Seven is £0.0
480.0
The total staff cost of Unit Eight is £480.0
192.0
348.0
543.0
711.0
935.0
The total staff cost of Unit Nine is £935.0
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at TEST.main(TEST.java:48)
Any ideas what could be causing this?
The following lines are giving you an error:
Unitnum = inFile.nextLine();
Unitnum = inFile.nextLine();
You could wrap them in:
if (b < shopunits - 1) {
...
}
You have reached the end of the file and the Scanner tries to read the nextLine when at the end of the file which is causing this issue.
What Adarsh said is most likely correct, what you should do is wrap it in a while loop.
while(infile.hasNextLine()){
...
}
This way when it gets to the end it wont fail on you.
I went through and edited your code for formatting, it was hard to follow at first. I think the problem with your if block was there were no brackets on it.
Try this:
if(total > recommended_max){
System.out.println("Higher");
}else{
System.out.println("Lower");
}
I know it works without brackets sometimes but sometimes depending on how or where it is written it might not. so its always good to put them on.
The reason why the output of the if statement isn't coming is that the statement is outside the loop. Formatting your code properly should help you identify such errors earlier.
The curly brace ending the for (int b = 0; b <shopunits; b++) loop is located on the same line with total = 0; i.e. before the if statement. That is why the conditional is not reached during the loop.
Another problem is that your code consumes the new lines between the shops after processing the current shop. This works as long as there is a next shop; however, this breaks as soon as you reach the last shop.
To fix this problem, add checks before consuming new lines, like this:
if (!inFile.hasNextLine()) break;
Unitnum = inFile.nextLine();
if (!inFile.hasNextLine()) break;
Unitnum = inFile.nextLine();
Alternatively, you could protect the current block of nextLine() reads with a single if, like this:
if (b != shopunits-1) {
// Skip lines only if we haven't reached the last block
Unitnum = inFile.nextLine();
Unitnum = inFile.nextLine();
}
Once you move your if statement inside the loop and fix this problem, your program should run correctly.
For the error at the end, it seems that below at end of for loop tries to read lines after each iteration:
Unitnum = inFile.nextLine();
Unitnum = inFile.nextLine();
So either you should have 2 blank lines at the end of your file, or you should read a line at the beginning of the loop:
while(inFile.hasNextLine()) {
Unitnum = inFile.nextLine();
saleassist = inFile.nextInt();
.......
}
Second problem about the "if" block is related to the value of total being set to 0 at end of each iteration:
hour= 0;
rate = 0;
total = 0;
you need additional variable declared outside the outer loop, to hold the sum of totals across loops.
double sumOfTotal=0;
......
System.out.println("The total staff cost of " + Unitnum +" is £"+ total);
//this holds the sum of totals across loops
sumOfTotal += total;
......
total=0;
}
if (sumOfTotal > reccomended_max)
System.out.println("Higher");
else
System.out.println("Lower");
This is what I have so far....
/**
* #param args
*/
public static void main(String[] args) {
final String DATA_FILE = "payroll_problem.txt";
Scanner scan = null;
try
{
scan = new Scanner(new File(DATA_FILE));
}
catch (FileNotFoundException e)
{
System.err.printf("Could not open file \"%s\".\n", DATA_FILE);
}
int [] arr = new int[scan.nextInt()];
for(int i = 0; i < arr.length; i++)
{
arr[i] = scan.nextInt();
System.out.print(arr[i]);
}
scan.close();
}
I keep getting error code
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at fvse.main(fvse.java:22)
The five ints stand for how many hours the person has worked from Monday-Friday. Here is the data file.
Mohnan Maria 8 8 8 9 8 10.01
Blue Shelly 8 10 8 8 6 10.00
Black 8 8 8 8 8 23.0
Fortuna Jorge 5 5 5 5 5 10.10
Jones Mitchel 10 5.5 10 10 10 15.05
Olafson Sven 10 10 10 10 10 10.00
Cruz Astrid 1 1 1 1 1 20.50.3
Adler Irene 10 12 8 8 8 22.50
The problem happen because you call scan.nextInt() but your input file actually contains string/characters.
Either add the integer indicating the number of lines on the top of your input file, or change your code read by line (eg: using BufferredReader.readLine())
If you choose the former, make sure you also read the first and last name using two invocation of scan.next()
You are reading your file for integers, but more than likely that file is filled with strings or characters.
Edit: Try scanning for lines or characters, or just using a FileInputStream, and then parsing the data once it's been loaded in.
Edit: Now that i've seen your data file, I would read in the file using standard file input practices (check out http://www.javapractices.com/topic/TopicAction.do?Id=42 if you need a tutorial on that). Then split the string based on spaces, and go through each string in your new string array and handle the data. The first 2 strings being names, and then integers until you get another name, or the end of the string.