How to fix java.util.InputMismatchException for my scanner file reader? - java

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);

Related

how to get the final output without pressing enter?

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.

How do I fix my error with scanner? java.util.InputMismatchException

I am using Java (VSC is my compiler).
I try to read through a document that is in the same folder. However, just scanning causes this error:
An error has occured.
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.nextDouble(Scanner.java:2564)
at Project1.results(Project1.java:66)
at Project1.main(Project1.java:87)
This is my whole code:
public class Project1() {
public void results(String fileName){
double x, y, xc, yc, rad, radius;
int number_of_circles = 0;
try {
Scanner scanner = new Scanner(new BufferedReader(new FileReader(fileName)));
while(scanner.hasNext()) {
x = scanner.nextDouble();
y = scanner.nextDouble();
rad = scanner.nextDouble();
if(rad > 0) {
number_of_circles++;
}
}
}
catch(Exception exception) {
System.err.println("An error has occured.");
exception.printStackTrace();
}
}
public static void main(String args[]){
Project1 P = new Project1();
P.results("Project1.data");
}
}
I tried different files with different values but it does not seem to help. Thanks. I looked at other threads, but they seem to not cover the exact same problem.
It looks like if I put only integer values inside Project1.data, then it works, but obviously I want to allow for other values
Project1.data values:
9.50 2.40 3.20
2.20 3.40 5.60
2.50 2.40 3.20
3.20 4.40 5.60
Is it possible that your locale expects , as separator, while your file contains . ?
Related question: Best way to parseDouble with comma as decimal separator?
Here is another related question with tips for Scanner: Java - Scanning comma delimited double and int values

Java arrays formatting

I am nearly done with my project (technically it's finished), but I am having a big problem with little detail such as output formatting. I am fairly new to JAVA and would apreciatte any help you can provide.
I need to output 2 arrays (String and Int) in some sort of table format.
Example:
England 4.6
USA 2.6
Japan 7.8
etc
I need exact spacing between the characters. I'll give you one part of my code: (I can apply the logic to the rest of the program)
double beerStrenghts [] = new double [10];
for(int x = 0; x < beerStrenghts.length; x++){
beerStrenghts[x] = beerStrenghts()[x];
}
String beerName [] = new String [10];
for(int x = 0; x < beerName.length; x++){
beerName[x] = (beerName()[x]);
}
String lookup;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter search criteria. Min 3 characters.");
lookup = keyboard.nextLine();
while(lookup.length() < 3){
System.out.println("Please enter at least 3 characters");
lookup = keyboard.nextLine();
}
Formatter fmt = new Formatter();
int indexInt;
boolean found;
for(int x = 0; x< beerName.length; x++){
found = beerName[x].toUpperCase().contains(lookup.toUpperCase());
if(found){
fmt.format("%12s%3d",beerName[x], beerStrenghts[x]);
System.out.println(fmt);
}
}
}
public static String [] beerName(){
String[] beerName = new String[10];
beerName[0] = "Heineken";
beerName[1] = "Bud Light";
beerName[2] = "Coors Light";
beerName[3] = "Leffe Blonde";
beerName[4] = "Budweiser";
beerName[5] = "Erdinger Non-Alcoholic";
beerName[6] = "Bud Premier Select";
beerName[7] = "Corona";
beerName[8] = "Barefoot Bohemian";
beerName[9] = "3 Monts";
return beerName;
}
public static double [] beerStrenghts(){
double beerStrenghts [] = new double [10];
beerStrenghts[0] = 4.0;
beerStrenghts[1] = 4.2;
beerStrenghts[2] = 4.3;
beerStrenghts[3] = 6.6;
beerStrenghts[4] = 5.0;
beerStrenghts[5] = 0.0;
beerStrenghts[6] = 7.4;
beerStrenghts[7] = 4.6;
beerStrenghts[8] = 4.0;
beerStrenghts[9] = 8.5;
return beerStrenghts;
You need to (re)read the javadoc for java.util.Formatter. In particular, it says that the formatting code d is for decimal integers. You are dealing with doubles, so the f code is probably more your style. (I'm just guessing though since you've been very light on details.)
Try something like
fmt.format("%-12s%3.1f",beerName[x], beerStrenghts[x]);
just change %3d to %.03for %.3f
like :
fmt.format("%-12s %.03f", beerName[x], beerStrenghts[x]);
%d is used for formatting integers.
also have a look at StringBuilder if you want different locales i.e different ways of formatting for different regions.
More about formatters with string builders here:https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
Big thanks for all help guys. And apologies for not providing enough details... I am also new in stack overflow.
This is my college project indeed (small part of it). Unfortunately majority of solutions-problems haven't being covered during classes - but I am doing my own researches(going very very well - almost done, formatting is the last part) and though I'll give my shoot here :)
Thanks for java.until.formatter reference dcsohl - I'll definitely go through it.
The solution given is almost working but I cant figure out what is the problem this time. Current output while searching for "bud":
Bud Light 4.2
Bud Light 4.2Budweiser 5.0
Bud Light 4.2Budweiser 5.0Bud Premier Select 7.4

Java File IO scan into variables

this is basically my first true Java assignment and I've hit a brick wall. I basically wrote my entire project as if the user were to input the information into the program. upon rereading the assignment I saw that we are to input the info from a .txt file in the following format:
1.17 12 15( and then sort them)
7 54 9873 1867 4425 878 365 783 (where the first number n indicates how many n will folow)
4 (flyods triangle problem)
20 (fizz buzz problem)
I have all of the code written to solve these parts of the project but am completely stuck on how to implement the numbers from the .txt file. I am not asking for code merely some advice on how you guys might go about doing so/
import java.util.Arrays;
import java.util.Scanner;
public class FunTime {
public static void main(String args[])
{
int n, num = 1, c, d;
Scanner in = new Scanner(System.in);
n = in.nextInt();
for ( c = 1 ; c <= n ; c++ )
{
for ( d = 1 ; d <= c ; d++ )
{
System.out.print(num+" ");
num++;
}
System.out.println();
}
Fortunately, reading from a file is exactly like reading from the terminal. Instead of reading from System.in, read from a file that you open with something like FileInputStream.

SPOJ ADDREV Problem

I did go through the other threads on this SPOJ problem, ADDREV (Adding Reversed Numbers), but sadly, I was not able to get an answer by any of the three programs that I have written (in C, Python and Java). I am attaching the code snippets of all three.
Python:
def find_rev(a):
d=0
while(a>=1):
d=d*10+a%10
a=a/10
return d
n=input('enter a number')
for i in range(int(n)):
num1=input('enter the first number')
num2=input('enter the second number')
num=0
num1=find_rev(int(num1))
num2=find_rev(int(num2))
num=num1+num2
num=find_rev(num)
print num
With Python, I get a runtime error.
With C, I get a wrong answer.
#include<stdio.h>
long rev(long);
int main()
{
long int n;
long int n1;
long int n2;
long int i=0;
scanf("%ld",&n);
//printf("%d",n);
for (i=0;i<n;i++)
{
//printf("\n%d",i);
//printf("\nenter the two numbers");
scanf("%ld%ld",&n1,&n2);
n = rev(rev(n1)+rev(n2));
printf("%ld\n",n);
}
return 0;
}
long rev(long a)
{
long d=0;
while(a>=1)
{
d = d*10+a%10;
a = a/10;
}
return d;
}
With Java, I get a compilation error.
import java.util.*;
//import java.io.*;
public class spoj_prob {
public static void main(String args[])
{
long n=0;
System.out.println("enter a number \n");
Scanner in=new Scanner(System.in);
n=in.nextLong();
long n1=0;
long n2=0;
long sum=0;
for (int i=0; i<n; i++)
{
System.out.println("enter two numbers \n ");
n1=in.nextLong();
n2=in.nextLong();
n1=rev(n1);
n2=rev(n2);
System.out.println(n1);
System.out.println(n2);
sum=rev(n1+n2);
System.out.println(sum);
}
}
static long rev(long a)
{
long d=0;
while (a>=1)
{
d=d*10+a%10;
a=a/10;
}
return d;
}
}
}
Of course, those errors are reported by the SPOJ Judge. The programs work fine on my system. Test cases I use are:
2
999999999 11
999 11
Answer
101
101
Also
3
34 54
123 091
00034 00054
Update: Guys, I got the answer in C. Thank you for all the help.
Before you start using any service, it's generally a good thing to read its FAQ. It explains how exactly the program should receive data.
In particular, please notice that printing enter a number and other junk to the console will always lead to a wrong answer. Because a correct program would output something like
34
1998
1
and yours
enter a number
enter two numbers
34
enter two numbers
1998
enter two numbers
1
I can't tell why Java fails to compile, though. You probably should find some information on how to submit in Java with the reference solution.
Also, the problem definition gives no limit for input numbers, so they can possibly be too big for standard integer types in Java and C++.
With Python I think you're getting Runtime Error because you're calling a restricted function input, nothing else comes to mind.
In C you're getting WA because the input integers can be very large, and you're overflowing.
For JAVA there are 2 potential problems that you may have. One is that you're using Scanner class which may not be supported by SPOJ (due to security or other considerations). Second, is that your class name needs to be Main I think. Please search SPOJ forum for more details on this.
Try this solution in Python 3:
import sys
t = int(input())
i=0
while i<t:
a,b = map(int,sys.stdin.readline().split()) #to take both inputs in single line
c=str(a) #converting the number into string
d=str(b)
e=int(c[::-1]) #converting reverse of the string c to int
f=int(d[::-1]) #converting reverse of the string d to int
s=e+f #adding the two reverse numbers
s1=str(s)
s2=int(s1[::-1]) #reverse s and display it
print(s2)
i+=1

Categories

Resources