Getting java.util.InputMismatchException - java

The program I'm trying to do:
"Use the file ("Eleven.txt") and delete the records with the marks in English and Science below 80 and marks under 90 in Computer Science"
I have tried adding 'sc.next()' and 'sc.nextLine()' between eng, sci, comp... But still no success.
The value in the "Eleven.txt" file is
a
A
10
20
30
b
B
20
30
40
c
C
40
50
60
d
D
60
70
80
e
E
70
8
90
"Science.txt" file is a blank file
import java.io.*;
import java.util.*;
public class filePg501Ex21{
public static void main() throws IOException{
String name1;
String name2;
int eng;
int sci;
int comp;
int ch;
int p = 0;
FileReader fr = new FileReader("Eleven.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("Science.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
Scanner sc = new Scanner(new File("Eleven.txt"));
while(sc.hasNext()){
name1 = sc.nextLine();
name2 = sc.nextLine();
eng = sc.nextInt();
sci = sc.nextInt();
comp = sc.nextInt();
if((eng >= 80) && (sci >= 80) && (comp >= 90)){
pw.println(name1);
pw.println(name2);
pw.println(eng);
pw.println(sci);
pw.println(comp);
}
}
fr.close();
br.close();
fw.close();
bw.close();
pw.close();
sc.close();
File f1 = new File("Eleven.txt");
f1.delete();
File f2 = new File("Science.txt");
boolean Rename = f2.renameTo(f1);
if(!Rename){
System.out.println("Renaming of the file not done");
}
else{
System.out.println("Renaming done sucesfully");
}
}
}

It looks to me like the error occurs in the second data set. The sc.nextInt() is not reading the carriage return after the final grade. So when the loop comes back for the second iteration, the first name1 field is blank, and the name2 field is b. That means when you read the eng value as an int, you get a value of B. That is the mismatch.
You should consider adding debug code to show you what the loop is doing to help you find this sort of problem.
There are almost certainly many ways to solve this.
Read another line after the last grade for instance.
Read the scores as lines and parse them to ints.

Related

java parsing text file and handling each line differently

I'm trying to read integers from a text file, but I want to handle the first line differently from the rest, and take the following lines and loop some calculations. Below is my file reader, my question is about the next part, however this may provide some context.
public class main
{
BufferedReader in;
public main() throws FileNotFoundException
{
System.out.println("please enter the name of the text file you wish you import. Choose either inputs or lotsainputs. Nothing else");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
System.out.println("You have loaded file: \t\t"+filename);
in = new BufferedReader(new FileReader(file));
Scanner inputFile = new Scanner(file);
String element1 = inputFile.nextLine().toUpperCase();
try
{
while ((element1 = in.readLine()) != null)
{
System.out.println("Line to process:\t\t"+element1);
myCalculations(element1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
The first text file look like this:
200 345
36
The second text file look like this:
200 345
36
45
36
21
Here is the method called:
public static void myCalculations(String s)
{
String[] items = s.split(" ");
int[] results = new int[100];
String errorMessage = "that's a wrap!";
for (int i = 0; i < items.length; i++)
{
try {
int stuff = Integer.parseInt(items[i]);
results[i] = stuff;
}
catch (NumberFormatException nfe) {
System.out.println(results);
System.out.println(errorMessage);
}
}
int health = result[0];
int power = result[1];
int days = result[2];
some calculations....
returns new health and power of the car.
same calculations but results[3] as the time period
returns new health and power of car
etc....
}
The method parses the integers, puts them into the results[] array.
Lets say the first two numbers of the text file are health and power of a car. Each proceeding number are days between races. Each race there is deterioration of the of the car and engine, the amount of deterioration is a factor of days in between each race.
I have used results[3][4]&[5] and hard code the deterioration and print the results and it works, but its pretty crap. How would I improve this method? I'm copy and pasting the 'calculations'. How do I take the first line, then put the following lines in a separate loop?
ideally, the number of days in the text file could vary. ie, there could be 5 races, or there could be 3 and the program will handle both cases.
try something like
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(
"please enter the name of the text file you wish you import. Choose either inputs or lotsainputs. Nothing else");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
System.out.println("You have loaded file: \t\t" + filename);
BufferedReader in = new BufferedReader(new FileReader(file));
String element1 = null;
try {
element1 = in.readLine();
}catch (Exception e) {
// TODO: handle exception
}
String[] firstLine = element1.split(" ");
Arrays.stream(firstLine).forEach(fl -> {
System.out.println("First line element: " + fl);
});
//Do the staff
String otherElement = null;
try {
while ((otherElement = in.readLine()) != null) {
System.out.println("Line to process:\t\t" + otherElement);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
result for file:
1 2
3
5
7
is
You have loaded file:
First line element: 1
First line element: 2
Line to process: 3
Line to process: 5
Line to process: 7

Read columns from .txt file

I have a text file (archive.txt) which has 9 columns of data separated by a tab. I want to read the columns and perform simple math.
In the example below, I want to find the average cost(iCost) by adding all policies with high (3) or unlimited (4) in column cData then dividing by the total of high and unlimited. High and unlimited are represented by a 3 and 4, respectively, in the archive file.
There are two System.out.println() numbered 1 and 2. They are used to see where the program gets to. It doesn't make it past the first System.out.println.
public int highUnlimited() {
Scanner input = new Scanner(System.in);
input = new Scanner("archive.txt");
int iLargeBundle = 0;
int iCost = 0;
System.out.println("1");
String cDate = input.next();
int cMinutes = input.nextInt();
int cData = input.nextInt();
int cLength = input.nextInt();
boolean cIntCalls = input.nextBoolean();
String cReference = input.next();
int cCostPerMonth = input.nextInt();
String cFirstName = input.next();
String cSecondName = input.next();
System.out.println("2");
if (cData == 3 || cData == 4) {
iLargeBundle = iLargeBundle++;
iCost = iCost + cCostPerMonth;
}
int iTotal = iLargeBundle / iCost;
return iTotal;
}
These are the first two lines of the Archive file. They don't have headings normally
15-Sep-2016 2 1 12 N MT230N 617 C Clark
25-Oct-2016 1 1 12 N ED641N 475 Z Clark
input = new Scanner("archive.txt");
This opens up a scanner on the string "archive.txt", not a file with that name.
If you wish to scan a file, you will need to do the following:
input = new Scanner(new File("archive.txt"));
Here you have your code rewritten with comments showing you how to do it, i've added a loop in case you want to read all the lines of the file you are able to do it (in that loop i added the methods hasNextLine(), returns true if there is a line next and nextLine(), it jumps to the next line). It is important that you import java.io.; to import the class file and import java.util.; to import that class Scanner. I hope i could help you.
public int highUnlimited(){
try{ //you all ways need to try catch the Exceptions when you use Scanner and File.
File f = new File("path"); //We need to create first the file object this is
//done with the constructor File(String path)
Scanner input = new Scanner(f); //You dont need the Scanner.in, the Scanner.in
//scanns input data from the terminal and we want
//to scann it from a File. Th constructor
//Scanner(String path) that you used doesn't exist
//on java.
int iLargeBundle = 0;
int iCost = 0;
String cDate, cReference, cFirstName, cSecondName; // I declare the variables outside so there
int cMinutes, cData, cLength, cCostPerMonth; //is no problem with the while
boolean cIntCalls;
int iTotal = 0; //I've used 0 as default value for iTotal
System.out.println("q");
while(input.hasNextLine()){ //I use hasNextLine in case you have various lines of data in your file
cDate = input.next();
cMinutes = input.nextInt();
cData = input.nextInt();
cLength = input.nextInt();
cIntCalls = input.nextBoolean();
cReference = input.next();
cCostPerMonth = input.nextInt();
cFirstName = input.next();
cSecondName = input.next();
input.nextLine(); //To jump a line so it doesn't block on the while
if (cData == 3 || cData ==4){
iLargeBundle++; //if you only want to add 1 to the variable with this is enough
iCost = iCost + cCostPerMonth;
}
}
iTotal = iLargeBundle/iCost; //as iCost is = if it hasn't been modified here is going
//to show an error because you can't divide by 0 so you have
//to change this in cas iCost is 0
}
catch(Exception e){
System.out.println(e.getMessage());
}
return iTotal;
}

Scanner/Token error java

I'm writing a program that reads sports data from a text file. Each line has strings and ints mixed together, and I'm trying to read just the scores of the teams. However, even though the lines have ints, the program immediately goes to the else statement without printing out the scores. I have the two input2.nextLine() statements so that it skips two header lines that have no scores. How can I fix this?
Here's the code:
public static void numGamesHTWon(String fileName)throws FileNotFoundException{
System.out.print("Number of games the home team won: ");
File statsFile = new File(fileName);
Scanner input2 = new Scanner(statsFile);
input2.nextLine();
input2.nextLine();
while (input2.hasNextLine()) {
String line = input2.nextLine();
Scanner lineScan = new Scanner(line);
if(lineScan.hasNextInt()){
System.out.println(lineScan.nextInt());
line = input2.nextLine();
}else{
line = input2.nextLine();
}
}
}
Here is the top of the text file:
NCAA Women's Basketball
2011 - 2012
2007-11-11 Rice 63 #Winthrop 54 O1
2007-11-11 #S Dakota St 93 UC Riverside 90 O2
2007-11-11 #Texas 92 Missouri St 55
2007-11-11 Tennessee 76 Chattanooga 56
2007-11-11 Mississippi St 76 Centenary 57
2007-11-11 ETSU 75 Delaware St 72 O1 Preseason NIT
Method hasNextInt() try to check immediate string is int ? . So that condition is not working.
public static void numGamesHTWon(String fileName) throws FileNotFoundException {
System.out.print("Number of games the home team won: ");
File statsFile = new File(fileName);
Scanner input2 = new Scanner(statsFile);
input2.nextLine();
input2.nextLine();
while (input2.hasNextLine()) {
String line = input2.nextLine();
Scanner lineScan = new Scanner(line);
while (lineScan.hasNext()) {
if(lineScan.hasNextInt()) {
System.out.println(lineScan.nextInt());
break;
}
lineScan.next();
}
line = input2.nextLine();
}
}
Please try this code.

FileInputStream not reading first value

The file I need to read from looks like this:
30 15
6 3
12 20
3 4
(without the bullet points)
The inputStream isn't reading 30 and 15 but it's reading all the other ones.
How do I get the inputStream to read the first line?
import java.io.*;
import java.util.*;
public class Program6 {
// private static Fraction [] fractionArray;
public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println("Please enter the name of the input file: ");
Scanner inputFile = new Scanner(System.in);
Scanner outputFile = new Scanner(System.in);
String inputFileName = inputFile.nextLine();
System.out.println("Please enter the name of the output file: ");
String outputFileName = outputFile.nextLine();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
FileWriter fileWriter = new FileWriter(outputFileName, true);
//Declaring an inputstream to get file
Scanner inputStream = new Scanner(new FileInputStream(inputFileName));
//while the file still has a line
while (inputStream.hasNextLine()) {
String theLine = inputStream.nextLine();
if (theLine.length() >= 0) {
//declares a numerator and denominator from the file
int num = inputStream.nextInt();
int denom = inputStream.nextInt();
//new fraction from file
Fraction fract = new Fraction(num, denom);
fract.reduce();
System.out.println(fract);
fileWriter.write("" + fract + "\r\n");
}
}
//closes streams and flushes the file writer
fileWriter.flush();
fileWriter.close();
inputStream.close();
}
}
The issue here is Scanner.nextLine() consumes the line of input from the InputStream. Then, using Scanner.nextInt() goes back to consume from that same InputStream - it does not consume from the value returned by nextLine().
So, use one or the other.
If using the nextLine() approach, then the String containing the line will need to be parsed to extract the values. Using scanner.nextInt(), the integer value from the file is immediately available. The only loss is that then you lose knowledge of whether values were on the same line or different lines.

Printing the last number only from a loop

If I have a while loop that goes through a file and prints the numbers, how would I make it to where it only prints the very last number.
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
This is the output I'm currently getting. How would I make get it to where it would just print out 19
And how would I get it to work to where the numbers start at 1 instead of 0?
Currently my loop looks like this:
if (math == last){
System.out.println(Score++);
}
math is another method which computes equations, and last is the answer inputed from a file, and the loop currently just checked if the math matches the inputed answer in order to "grade" the problems.
I can't use arrays, try/catch, or regex.
Just read through the file normally and store each line in a temporary variable. Once the reader finishes reading, print out the temporary variable.
public class ReaderExample {
public static void main(String[] args) throws IOException {
File file = new File("input.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
String copy = "";
while((line = br.readLine() )!= null){
copy = line;
}
System.out.println(copy);
}
}
Using a Scanner
The same principle applies with a Scanner:
public class ReaderExample {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("input.txt"));
String line = "";
while(in.hasNext()){
line = in.nextLine();
}
System.out.println(line);
}
}
Without Invoking Scanner
public String getLast(Scanner scanner){
String line = "";
while(in.hasNext()){
line = in.nextLine();
}
return line;
}

Categories