Scanner/Token error java - 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.

Related

Getting java.util.InputMismatchException

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.

Use delimiter to separate a pattern

I have a text file where I am trying to read string and integer input using a Scanner. I need to separate the data using a comma and there is also the issue of newline character. Here is the text file contents:
John T Smith, 90
Eric K Jones, 85
My code:
public class ReadData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
Scanner input = new Scanner(file);
input.useDelimiter(",");
while (input.hasNext()) {
String name1 = input.next();
int score1 = input.nextInt();
System.out.println(name1+" "+score1);
}
input.close();
}
}
Exception:
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 ReadData.main(ReadData.java:10)
Setting the delimiter for class java.util.Scanner to comma (,) means that each call to method next() will read all the data up to the next comma, including newlines. Hence the call to nextInt reads the score plus the name on the next line and that isn't an int. Hence the InputMismatchException.
Just read the entire line and split it on the comma (,).
(Note: Below code uses try-with-resources)
public class ReadData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
try (Scanner input = new Scanner(file)) {
// input.useDelimiter(","); <- not required
while (input.hasNextLine()) {
String line = input.nextLine();
String[] parts = line.split(",");
String name1 = parts[0];
int score1 = Integer.parseInt(parts[1].trim());
System.out.println(name1+" "+score1);
}
}
}
}
Use ",|\\n" RegExp delimiter:
public class ReadData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
Scanner input = new Scanner(file);
input.useDelimiter(",|\\n");
while (input.hasNext()) {
String name1 = input.next();
int score1 = Integer.parseInt(input.next().trim());
System.out.println(name1+" "+score1);
}
input.close();
}
}
Try this.
String text = "John T Smith, 90\r\n"
+ "Eric K Jones, 85";
Scanner input = new Scanner(text);
input.useDelimiter(",\\s*|\\R");
while (input.hasNext()) {
String name1 = input.next();
int score1 = input.nextInt();
System.out.println(name1+" "+score1);
}
input.close();
output:
John T Smith 90
Eric K Jones 85

Scanning in contents of a file

I have a file that has the following content:
5
Derrick Rose
1 15 19 26 33 46
Kobe Bryant
17 19 33 34 46 47
Pau Gasol
1 4 9 16 25 36
Kevin Durant
17 19 34 46 47 48
LeBron James
5 10 17 19 34 47
With the a blank line between each of the names and numbers. However when I scan the file using the the nextLine(); method I get the following:
NAME:
NAME:
NAME: Derrick Rose
NAME:
NAME: 1 15 19 26 33 46
NAME:
NAME: Kobe Bryant
NAME:
NAME: 17 19 33 34 46 47
NAME:
Can someone tell me where in my code the problem is occurring and why it is scanning in blank lines.
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); i++)
{
String name = scan.nextLine();
System.out.println("NAME: " + name);
}
It seems you want to ignore the empty lines, you could just check the length of the line you're about to write to the console. It's not possible to not scan empty lines, you need to at least skip them to dive further into your stream.
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); i++) {
String name = scan.nextLine();
if (name.trim().length() > 0)
System.out.println("NAME: " + name);
}
If you have a newline in your input, then that will consume one call to scan.NextLine(), since that function delimits on newlines. If you want it to ignore blank lines then you should explicitly check for them and then explicitly increment your counter if the lines are not blank.
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); )
{
String name = scan.nextLine();
if (!name.trim().equals("")) i++;
System.out.println("NAME: " + name);
}
You could check for blank lines and ignore them. The code below should do this.
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); i++)
{
String name = scan.nextLine();
if (!name.equals("")){
System.out.println("NAME: " + name);
}
}
The below class ExcludeEmptyLines.java worked
package com.stackoverflow.java.scannertest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Created by fixworld.net on 03-September-2015.
*/
public class ExcludeEmptyLines {
public static void main(final String[] args)
throws FileNotFoundException {
String dataFileFullPath = "<replace with full path to input file>";
File inputFile = new File(dataFileFullPath);
Scanner scan = new Scanner(inputFile);
int numEntries = scan.nextInt();
System.out.println("NumEntries = " + numEntries);
for(int i = 0; i <= (numEntries * 4); i++)
{
String inputLine = scan.nextLine();
if(!inputLine.trim().equalsIgnoreCase("")) {
System.out.println("inputLine = " + inputLine);
}
}
}
}
Output from running it is
NumEntries = 5
inputLine = Derrick Rose
inputLine = 1 15 19 26 33 46
inputLine = Kobe Bryant
inputLine = 17 19 33 34 46 47
inputLine = Pau Gasol
inputLine = 1 4 9 16 25 36
inputLine = Kevin Durant
inputLine = 17 19 34 46 47 48
inputLine = LeBron James
inputLine = 5 10 17 19 34 47

How to solve java.util.InputMismatchException

I'm working on a java lab and the first step is reading data from the input text file. I've been trying to fix the code but it doesn't help at all. Could you guys please take a look and let me know what I can do about it?
The error I get is:
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.nextDouble(Scanner.java:2456)
at Restaurant.<init>(Restaurant.java:35)
at RestaurantTester.main(RestaurantTester.java:11)
For the tester class with main method
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class RestaurantTester {
private static Scanner buffer = new Scanner(System.in);
private static int inputInt;
private static Restaurant restaurant;
public static void main(String[] args) throws FileNotFoundException {
restaurant = new Restaurant();
System.out.print("\n Welcome to Java Restaurant\n");
System.out.print("\n\n*************************************\n");
System.out.print("1. Display Menu\n");
System.out.print("2. Display Server List\n");
System.out.print("3. Restaurant Activities\n");
System.out.print("4. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
while (inputInt != 4) {
switch (inputInt) {
case 1: {
restaurant.displayMenu();
break;
} // end case 1
case 2: {
restaurant.displayServerList();
break;
} //end case 2
case 3:{
System.out.print("\n\n*************************************\n");
System.out.print("1. Restaurant Activity\n");
System.out.print("2. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
while (inputInt != 2) {
restaurant.restaurantActivity();
System.out.print("\n\n*************************************\n");
System.out.print("1. Restaurant Activity\n");
System.out.print("2. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
} // end inner while
break;
} // end case 3
} // end switch
System.out.print("\n\n*************************************\n");
System.out.print("1. Display Menu\n");
System.out.print("2. Display Server List\n");
System.out.print("3. Restaurant Activities\n");
System.out.print("4. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
} // end outer while
System.out.print("\nThank you. The Java restaurant is now closed.\n");
} // end main
}
For my Restaurant class
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Restaurant {
...
private Menu menu;
public ArrayList<Server> servers;
private Activity activity;
public Restaurant() throws FileNotFoundException {
input = new Scanner(new File("menu.txt"));
menu = new Menu();
servers = new ArrayList<Server>();
temp = input.nextLine(); // skip 1st line
for (int index = 0; index < 3; index++) {
servers.add(new Server(input.next(), (input.nextLine()).split(",",6)));
} // assume only 6 tables for each server
temp = input.nextLine(); // skip instruction line
while (input.hasNext()) {
str1 = input.next();
str2 = input.next();
value = input.nextDouble();
menu.setMenuItem(str1,str2, value);
}
} // end constructor
....
}
And heres my text file:
Waiters: first name followed by table list
John 1,2,5,9,11,15
Maria 3,4,6,7,17,18
Mike 8,10,12,13,14,26
Menu: listing of the full menu: item code, name, price
A1 Bruschetta 5.29
A2 Caprese_Flatbread 6.10
A3 Artichoke-Spinach_Dip 3.99
A4 Lasagna_Fritta 4.99
A5 Mozzarella_Fonduta 5.99
E1 Lasagna_Classico 6.99
E2 Capellini_Pomodoro 7.99
E3 Eggplant_Parmigiana 8.99
E4 Fettuccine_Alfredo 7.49
E5 Tour_of_Italy 14.99
D1 Tiramisu 2.99
D2 Zeppoli 2.49
D3 Dolcini 3.49
S1 Soda 1.99
S2 Bella_Limonata 0.99
S3 Berry_Acqua_Fresca 2.88
You need to skip one more line.
Skip one
read three
skip blank line?
skip instructions
loop till the end
From http://www.java-made-easy.com/java-scanner-help.html:
Q: What happens if I scan a blank line with Java's Scanner?
A: It depends. If you're using nextLine(), a blank line will be read in as an empty String. This means that if you were to store the blank line in a String variable, the variable would hold "". It will NOT store " " or however many spaces were placed. If you're using next(), then it will not read blank lines at all. They are completely skipped.
My guess is that nextLine() will still trigger on a blank line, since technically the Scanner will have the empty String "". So, you could check if s.nextLine().equals("")
I may be wrong, but it seems you need to skip two lines after finishing the first portion of the file. You skip one line, but that may just be the line space. So you need to skip again to get to your desired content. Try adding another nextLine()
input.nextline();
temp = input.nextLine();
Also, it's possible you may have a problem with the scanner not going to next line after nextDouble(). If the above didn't work, Try adding a nextLine() after it and see if that works?
value = input.nextDouble();
input.nextLine();
Consider even using a split to avoid this problem
while (input.hasNextLine()) {
String line = input.nextLine();
String[] token = line.split("\\s+");
str1 = tokens[0].trim();
str2 = tokens[1].trim();
value = Double.parseDouble(tokens[2].trim());
menu.setMenuItem(str1,str2, value);
}
The above code will read each line, line by line, then split the three into an array of Strings. The last value will need to be parsed into a double.
Edit: Here's another
servers.add(new Server(input.next(), (input.nextLine()).split(",",6)));
You're reading the next, then the nextLine. You need to read all in one line
Edit: try this code
public Restaurant() throws FileNotFoundException {
input = new Scanner(new File("menu.txt"));
menu = new Menu();
servers = new ArrayList<Server>();
temp = input.nextLine(); // skip 1st line
for (int index = 0; index < 3; index++) {
String line = input.nextLine();
String[] tokens = line.split("[\\s,]+");
String name = tokens[0];
String[] nums = new String[6];
for (int i = 1; i < tokens.length; i++) {
nums[i - 1] = tokens[i].trim();
}
servers.add(new Server(name, nums));
} // assume only 6 tables for each server
input.nextLine();
temp = input.nextLine(); // skip instruction line
while (input.hasNextLine()) {
String line = input.nextLine();
String[] tokens = line.split("\\s+");
str1 = tokens[0].trim();
str2 = tokens[1].trim();
value = Double.parseDouble(tokens[2].trim());
menu.setMenuItem(str1,str2, value);
}
}

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