Exception in java "java.util.InputMismatchException" - java

So, I am working on a code for class and can't figure what is wrong. The code compiles and when I enter the file I'm searching for, I get this message:
Enter the name of the file: FanData.txt
Exception in 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 FanDriver.fillArray(FanDriver.java:76)
at FanDriver.main(FanDriver.java:35)
Press any key to continue . . .
I'm using TextPad as my compiler and the text file is in the project. The following is the code that I have written (ignore the methods being called in the quotes as they are something I need to do afterwards):
import java.io.*;
import java.util.Scanner;
public class FanDriver
{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String args[]) throws IOException
{
// Constant for the amount of elements of the array
final int MAXSIZE = 100;
// Declaring variables
int amountFans = 0;
// Declaring and initializing our array of fans
Fan[] fans = new Fan[MAXSIZE];
// Calling all of our methods
amountFans = fillArray(fans, MAXSIZE);
/**
listFanData(fans, amountFans);
bubbleSortByAge(fans, amountFans);
listFanData(fans, amountFans);
bubbleSortByFan(fans, amountFans);
listFanData(fans, amountFans);
searchByAge(fans, amountFans);
searchByFan(fans, amountFans);
*/
}
public static int fillArray(Fan[] array, int MAXSIZE) throws IOException
{
// Declaring variables
int counter = 0;
int age;
String name;
// Getting the file name
System.out.print("\nEnter the name of the file: ");
String fileName = keyboard.nextLine();
// Opening the file
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
// Making sure the file was successfully opened
if (!file.exists())
{
System.out.println("\nERROR: FILE DOESN'T EXIST. CLOSING PROGRAM NOW.");
// Exiting the program
System.exit(0);
}
// Reading all of the amounts from the file
while (inputFile.hasNext() && counter < MAXSIZE)
{
name = inputFile.nextLine();
age = inputFile.nextInt();
array[counter] = new Fan(name, age);
// Adding to our counter
counter = counter + 1;
}
//Closing file
inputFile.close();
return counter;
}
}
I do not have the code for the Fan class, just the class itself.
The file we are retrieving is the file FanData.txt, which looks like this:
Chris P. Cream
5
Scott Free
9
Lou Tenant
3
Trish Fish
12
Ella Mentry
4
Holly Day
3
Robyn DeCradle
12
Annette Funicello
4
Elmo
7
Grover
3
Big Bird
9
Bert
7
Ernie
3
Grover
9
The text file is line-by-line. One line is a name and the next is a number. I don't know how to format it correctly on here.
Any help would be greatly appreciated.

I am not sure about the delimiter in your input file.
The way you had instantiated your "Scanner"(without specifying any explicit delimiter) shall use default delimiter i.e. a whitespace character.
It seems that the "nextLine()" method in your case is not returning a "line".
It is rather returning a number or string(may be, you need check your file for that) which is not matching with the pattern followed by your Scanner.

The error is because of the type mismatch. After your first read scanner will be pointing to a non Integer value.
try to print your name before doing
age = inputFile.nextInt();
you will get to know the issue.
Above mentioned are means to understand the mistake.
Solution for your problem
Try :
age = Integer.parseInt(inputFile.nextLine()); // instead of age = inputFile.nextInt();

Exception is because of type mismatch as you are reading a text value from textfile and directly assigning to an int type.
Exception will be resolved if you parse the value as an integer as below
Integer.valueOf(inputFile.nextLine());

Related

Item Counter program that will display the number of names that are stored on a file

Can someone help me with this java program that I've been puzzled on for a while. I'll post the question alone with the code but its a Files in java that I've recently started and I'm having trouble adding a loop counter variable to hold and display the number of names stored in the file.
For better understanding here the question I'm working on:
Assume that a file containing a series of names (as strings) is named names.dat and exists on the computers disk. Design a program that displays the number of names that are stored in the file. (Hint: Open the file and read every string stored in it. Each time you read a string, increment a counter variable. When you've read all the strings from the file, the counter variable will contain the number of names stored in the file.)
I don't know how much trouble it will be to aid assist being that this question is file related in java.
Here is my java code so far for better understanding:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Item_Counter {
public static void main(String[] args) throws FileNotFoundException {
int numLines = 0;
int sum = 0;
File namesFile = new File("C:\\Users\\Tyrese\\JAVA 2\\Chapter 10\\names.dat");
Scanner bot = new Scanner(namesFile);
System.out.println(bot.nextLine());
while (bot.hasNext()) {
numLines = numLines + 1;
numLines = bot.nextInt();
}
System.out.println("The file has" + numLines);
}
}
Feel free to replace my file path and name that is a simple notepad document containing a few names, with your own if necessary.
You have some errors in your code, the way Scanner works for file reading is simple, you open the file the way you did like this : Scanner bot = new Scanner(namesFile); but in order to go to the next line you need to do bot.nextLine() so if you do it before you are in the while or do it twice it will go on 2 lines, so you just need to do like this :
public static void main(String[] args) throws FileNotFoundException {
int numLines = 0; // initialise variable
File namesFile = new File("C:\\Users\\Tyrese\\JAVA 2\\Chapter 10\\names.dat"); // fetch the file
Scanner bot = new Scanner(namesFile); // open the file
while (bot.hasNextLine()) { // while the file has a next line -> go on
numLines++; // add +1 to the variable numLines
numLines = bot.nextLine(); // go to the next line (if it has one)
}
System.out.println("The file has" + numLines); // print the result
}
You can ask me if you have any further questions
This is the problematic part of your code:
System.out.println(bot.nextLine());
while (bot.hasNext()) {
numLines = numLines + 1;
numLines = bot.nextInt();
}
Your println types a line being read and therefore that line will be ignored later. You need hasNextLine in the while loop and nextLine instead of nextInt.
Fix:
while (bot.hasNextLine()) {
numLines = numLines + 1;
bot.nextLine();
}
You can compute the sum of integers inside a file similarly. However, the actual solution depends on the structure of the file. If the file contains the integers as lines, without white characters beside the newline, such as
1
5
4
7
2
7
then the solution is:
int sum = 0;
while (bot.hasNextLine()) {
sum += 1;
bot.nextLine();
}
however, if the file is a list of numbers, separated by space, such as
3 7 8 2 8 3 6 9
then you read the content of the file via
String content = bot.nextLine();
String[] splited = str.split("\\s+");
int sum = 0;
for (int index = 0; index < splited.length; index++) {
sum += Integer.parseInt(splited[index])
}

Why won't my method read in every value from a file?

public static int getBoys(ArrayList<String> boysNames, Scanner s) throws IOException {
// Getting boys file location
System.out.println("Please enter the file name containing the the boys names.");
String boyFileLocation = s.nextLine();
// Opening the file containing the names of boys
File boyFile = new File(boyFileLocation);
Scanner BF = new Scanner(boyFile);
int initialBoyCount = 0;
int i = 0;
boysNames.add(BF.nextLine());
while (BF.hasNextLine()) {
if (BF.nextLine().equals(boysNames.get(i))) {
} else {
boysNames.add(BF.nextLine());
initialBoyCount++;
i++;
System.out.println(boysNames.get(i));
}
}
return (initialBoyCount);
}
I am trying to read in from a file a list of names and add them to an array list. However there are duplicates of certain names and i am only suppoused to keep the unique ones (If if already exists don't add it again). However, I figured out that it is only giving me every other name. Starting with 2, and giving me the following errors.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at namesList.namesList.getBoys(namesList.java:53)
at namesList.namesList.main(namesList.java:27)
The reason of the exception in this line
if (BF.nextLine().equals(boysNames.get(i)))
you read a line and if equation isn't true in else branch you call BF.nextLine() again. So sometimes you read line twice but you call hasNextLine() only once .
Solution: read line only one time before if statement.

Reading a multi datatype file into an ArrayList in Java

I am trying to read a file, which the user inputs, and the file has numbers and characters. I only want to store the numbers in an Arraylist but I keep getting stuck, help would be greatly appreciated. This is what I have. Sorry if this has been answered, I am new to the site.
import java.util.*;
import java.io.*;
public class ArrayListClient {
public static final int SIZE = 100;
public static void main(String[] args) throws FileNotFoundException {
String fileName, fileName2;
UnorderedArrayList list1 = new UnorderedArrayList(SIZE);
Scanner input = new Scanner(System.in);
System.out.print("Please input the name of the file to be opened for the first list: ");
fileName = input.nextLine();
System.out.println();
Scanner inputFile = new Scanner(new File(fileName));
int num = inputFile.nextInt();
while(inputFile.hasNextInt()) {
int num2 = inputFile.nextInt();
list1.insertEnd(num);
num = num2;
}
list1.print();
}
}
the input file is 13 c v b 25 34 x x 67 56 10 a a 20 27 2 a s 5 1 45 59
The loop you provided is correct, although you don't need this line outside of the while loop:
int num = inputFile.nextInt();
If the file you provided didn't have a Integer then this would crash your program.
I think you can simply write this and it should work:
while (inputFile.hasNextInt()) {
int num = inputFile.nextInt();
list1.insertEnd(num);
}
The loop checks to see if there is another Integer left in the file (inputFile.hasNextInt()) and then gets it to add to the list (inputFile.nextInt()).
This sounds like it could be a homework question, so I'm hesitant to just give the answer, but if I were you, I would consider writing a filter function (make it a lazy filter if you have to consider files that are very large/won't fit in memory). Your filter function can try Integer.parseInt(yourString); and catch any NumberFormatExceptions that occur because it tried to parse a letter. This approach has the obvious danger of using exceptions to control program flow (normally considered bad practice), but you won't have to traverse the list twice.
Your other obvious option is to write a filter that filters the characters out so that you are only left with number strings, and then just run parseInt over those number strings to turn them into integer values. If performance is a concern, you can avoid double-traversing the list by writing functions that validate a single string value (reject if it's not a number), and then parse it into an int if it is a number, and then add the parsed integers into your array as you go within a foreach loop.
You are most of the way there already since integer detection is built into the Scanner class and the Integer class contains the parseInt() method. Just mutate an array which you define outside of a for each loop and you're good to go.

InputMismatchException while reading two lines correctly?

I'm reading in two lines of a .txt file (ui.UIAuxiliaryMethods; is used for this) to calculate the BodyMassIndex(BMI) of patients, but I get a inputmismatchexception when the patientLenght is reached. These are my two lines of input, seperated by a \t:
Daan Jansen M 1.78 83
Sophie Mulder V 1.69 60
It's sorted in Name - Sex - Length - Weight. This is my code to save all elements in strings, doubles and integers:
package practicum5;
import java.util.Scanner;
import java.io.PrintStream;
import ui.UIAuxiliaryMethods;
public class BodyMassIndex {
PrintStream out;
BodyMassIndex() {
out = new PrintStream(System.out);
UIAuxiliaryMethods.askUserForInput();
}
void start() {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
String lineDevider = in.nextLine(); //Saves each line in a string
Scanner lineScanner = new Scanner(lineDevider);
lineScanner.useDelimiter("\t");
while(lineScanner.hasNext()) {
String patientNames = lineScanner.next();
String patientSex = lineScanner.next();
double patientLength = lineScanner.nextDouble();
int patientWeight = lineScanner.nextInt();
}
}
in.close();
}
public static void main(String[] args) {
new BodyMassIndex().start();
}
}
Somebody got a solution for this?
Your name has two tokens not one, so lineScanner.next() will only get the token for the first name.
Since a name can have more than 2 tokens theoretically, consider using String.split(...) instead and then parsing the last two tokens as numbers, double and int respectively, the third from last token for sex, and the remaining tokens for the name.
One other problem is that you're not closing your lineScanner object when you're done using it, and so if you continue to use this object, don't forget to release its resource when done.
Your name field has two token. and you are trying to treat them as one. that;s creating the problem.
You may use a " (double quote) to separate the name value from others. String tokenizer may do your work.
I changed the dots to commas in the input file. Hooray.

why's this program giving a runtime error on jcreator but not on netbeans?

This is my solution for sphere's online judge palin problem. It runs fine on Netbeans, but the judge is rejecting my answer saying it gives a RuntimeError. I tried it on JCreator and it says:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
at java.lang.Integer.parseInt(Integer.java:497)
at Main.main(Main.java:73)
I'm not passing an empty string for it to parse, why is this?
The code:
import java.io.*;
import java.util.*;
class Main {
public static int firstPalinLargerThanNum(int num){
int foundPalin =0;
int evalThisNum = ++num;
while (true){
if (isPalin(evalThisNum))
break;
evalThisNum++;
}
foundPalin = evalThisNum;
return foundPalin;
}
public static boolean isPalin(int evalThisNum){
boolean isItPalin = false;
int dig=0;
int rev=0;
int n = evalThisNum;
while (evalThisNum > 0)
{
dig = evalThisNum % 10;
rev = rev * 10 + dig;
evalThisNum = evalThisNum / 10;
}
if (n == rev) {
isItPalin=true;
}
return isItPalin;
}
public static void main(String args[]) throws java.lang.Exception{
BufferedReader r1 = new BufferedReader(new InputStreamReader(System.in));
/*BufferedReader r1 = new BufferedReader (new FileReader(new File ("C:\\Documents and Settings\\Administrator\\My Documents\\NetBeansProjects\\Sphere\\src\\sphere\\sphere\\PALIN_INPUT.txt")));*/
String read = r1.readLine();
int numberOfTestCases = Integer.parseInt(read);
for (int i=0; i<numberOfTestCases;i++){
read = r1.readLine();
if (read!=null){
int num = Integer.parseInt(read);
System.out.println(firstPalinLargerThanNum(num));
}
}
}
}
Input:
2
808
2133
line 73 is: int num = Integer.parseInt(read);
You will get that error if you hit <Enter> when the program is expecting a number.
Suppose your input is
2
3
<Enter>
You will receive the error you have indicated after processing the number 3, as you have told your routine to iterate twice.
As an aside, on top of error handling around the number parsing, you might also want to introduce a trim() to the readLine() method calls:
String read = r1.readLine().trim();
This will allow you to handle gracefully the input in the event that the user to put in whitespace around the numbers.
Just a wild guess: Could there be a problem with different end-of-line separators.
E.g. your program actually gets 2<CR><LF>808<CR><LF>2133<CR><LF>, thinks that the line ends at the <CR> and processes the line.
Now when it tries to process the next line it finds <LF> which makes it think it read an empty String.
You cannot assume that the user knows how to use your program and will give you correct input. The judge probably hit enter, without typing any number. How is he/she supposed to know the input that your program requires? A program should fail gracefully, not blow up in the user's face with cryptic errors.
You should be doing something like the following, so that the user knows what to do:
private static function readInt(BufferedReader reader) throws IOException
{
boolean done = false;
int result = -1;
while ( ! done ){
System.out.print("Please enter an integer: ");
String str = reader.readLine();
try{
result = Integer.parseInt(str);
done = true;
}catch(NumberFormatException cantconvert){
System.out.println("That isn't an integer. Try again.");
}
}
return result;
}
Additionally, you shouldn't use an exception specifier with the main function (that is, don't use "throws" in the signature of "main"). You should handle those IOExceptions and print a pretty and intelligible message to the user, even if there is nothing you can do about the exception to fix it or make it go away.
I just ran your example code under Eclipse 3.4 without error. I was only able to induce a similar error when I did not provide the specified number of test cases, i.e.:
6
56
87
[Enter]
So I am inclined to agree with akf that there must be an extra Enter happening somewhere, because this error will only be generated when there are insufficient lines of input.

Categories

Resources