My code is designed to read the contents of a text file and check if the contents are entered in a format that is as follows:
john : martin : 2 : 1
and if that format is followed then it will output it in the format:
john [2] | martin [1]
or else it will be counted as an invalid result and the total numbers will not be added to it whereas if the results are in the format then they will get added to the total so with the example it would display the number of vaild results as 1, invalid as 0 and total number as 3.
My question is that my code doesn't work properly as I get this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at reader.main(reader.java:33)
So how would I go about fixing this and reading and displaying the data in thee way that I want? Thanks in advance.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;
import java.util.Scanner;
public class reader {
/**
* #param args
* #throws FileNotFoundException
* #throws FileNotFoundException
* #throws FileNotFoundException when the file cannot be loaded
*/
public static void main(String[] args) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
Scanner s = new Scanner(new BufferedReader(new FileReader("results2.txt"))).useDelimiter(":");
// create a scanner which scans from a file and splits at each colon
while ( s.hasNext() ) {
hteam = s.next(); // read the home team from the file
ateam = s.next(); // read the away team from the file
hscore = s.nextInt(); //read the home team score from the file
ascore = s.nextInt(); //read the away team score from the file
System.out.print(hteam); // output the line of text to the console
System.out.print(hscore);
System.out.print(ateam);
System.out.println(ascore);
}
System.out.println("\nEOF"); // Output and End Of File message.
}
}
You're looking for s.next() instead of s.nextLine().
hteam = s.nextLine() reads the entire line "john : martin : 2 : 1", leaving nothing left for ateam.
Edit:
As you've said this still isn't working, I'd guess that you have an extra newline at the end of your input file, which is causing s.hasNext() to evaluate to true. This would cause the Scanner to trip up when it's getting the next input line.
Try Scanner s = new Scanner(System.in).useDelimiter("\\s*:\\s*|\\s*\\n\\s*"); to read multiple lines.
See implementation: http://ideone.com/yfiR2S
To verify that a line is in the correct format, I'd (with inspiration from osoblanco's answer) check that there are 4 words and that the last two are integers:
public static boolean verifyFormat(String[] words) {
// see endnote for isInteger()
return words.length == 4 && /*isInteger(words[2]) && isInteger(words[3])*/;
}
public static void main(String[] args) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
Scanner s = new Scanner(new BufferedReader(
new FileReader("results2.txt"))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
ascore = Integer.parseInt(words[3]); //read the away team score
System.out.print(hteam); // output the line of text to the console
System.out.print(hscore);
System.out.print(ateam);
System.out.println(ascore);
}
}
System.out.println("EOF");
}
isInteger() can be found here.
I think scanning isn't quite what you want here. I would just use a BufferedReader and do ReadLine to handle 1 line each time through the for loop.
Then verify each line by the following:
1) String.split(":") and verify 4 pieces.
String [] linePieces = nextLine.split(":");
if(linePieces.length!=4)
{
//mark invalid, continue loop
}
2) Trim each piece
for(int i =0; i<4; i++)
linePieces[i] = linePieces[i].trim();
3) Verify piece 3 and piece 4 are numbers, Integer.parseInt with try/catch. In the catch block, count that the line is invalid.
try
{
name1=linePieces[0];
name2=linePieces[1];
score1=Integer.parseInt(linePieces[2]);
score2=Integer.parseInt(linePieces[3]);
//count as success and do logic
}catch(NumberFormatException e){
//invalid line
}
Related
I've fixed many other issues but after fixing one that I thought was the last error, I came a Null pointer exception.
package com.Text.Scanner.java;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class TextScanner {
public static void main(String ...args) throws IOException{
Scanner sc = new Scanner(System.in);
System.out.println("Enter names for parsing");
String input = sc.nextLine();
ArrayList<String> names = new ArrayList<String>();
for (int i = 0;i<=input.length();i++) {
names.add(input.substring(0, input.indexOf(",")));
input = input.substring(input.indexOf(",")+1);
}
System.out.println(names);
// handles the string import to arraylist
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("sample.txt"));
//finds file
String line = reader.readLine();
//reads line
while (line != null) {
for (int i = 0; i <= line.length(); i++) {
if (line.contains(names.get(i))) {
//gets name from array to scan line for
System.out.println(line.substring(4, line.indexOf(names.get(i)) + names.get(i).length()));
//controls length
line = reader.readLine();
}
}
}
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
The goal here is to scan each line for a name (first and last) then print the number aside their name on the text file.
first line: 1234 Billy Smith
second line: 5678 John Smith
what you input: Billy Smith,John Smith,
The point of it is to scan the file for the list of first and last names in an arraylist and then output the numbers and name. The program works if I go in order in the whole list, but if I don't then it gives me this. I have tried to put reader.reset() if the if statement finds a match and then if it doesn't it reads another line, but that doesn't work
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.get(ArrayList.java:426)
at com.Text.Scanner.java.TextScanner.main(TextScanner.java:32)
for (int i = 0; i <= line.length(); i++) {
if (line.contains(names.get(i))) {
So basically i goes from O to line.length() (number of char in the line) and you use it to accces your names with name.get(i) that absolutely no reason to be the same size (it is more the number of lines on the first line)
But why don't you debug your code ? The error you got says the error is in TestScanner line 32 calling the method get. It already say where the error !
You could even rerun that program with the debugger, and ask it to stop when an exception is raised so it would stop exactly at the right place and you be able to look at the various variables.
I keep getting an error and I am unsure why. This is my code
public class test {
public static void main(String[] args) throws FileNotFoundException {
Scanner inscan = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputfilename = inscan.nextLine();
File inputfile = new File(inputfilename);
Scanner in = new Scanner(inputfile);
String inputline = in.nextLine();
ArrayList<String> Names = new ArrayList<String>();
in.nextLine();
in.nextLine();
int total = 0;
while(in.hasNextLine()){
in.nextInt();
String Mname = in.next();
int Number = in.nextInt();
Names.add(Mname);
total += Number;
}
in.close();
for (String Mname : Names) {
System.out.println(Mname);
}
System.out.println("total number is " + total);
}
}
Prints:
hi
total number is 38
This is what the text file looks like.
test
test
1 mike 34
2 hi 38
I am first skipping the first two lines. Then getting all the names. Then printing the total number of all those names. It is now working with no errors but only prints one thing.
You're not pointing to the file properly. In order for your program to read names.txt, names.txt must be in the program's root directory. If you're running this from eclipse, that's the project's main folder. If you're running this from something like Dr. Java, this would be wherever your .java file is. Depending on what ide you're using to compile and run this, you can Google where the root directory of your project should be.
When you export this as a .jar file, the root directory becomes the directory from which the .jar is being run.
Edit: nevermind, disregard that, I see that the error is occurring on a different line of code. My bad :/
Edit 2: actually, do NOT disregard that, I just realized I was looking at the right line of code - the txt file's location is likely the problem (I think)
Part of your input routine is done in a loop. I'm guessing it is that way to facilitate the lines which (probably) all follow the same pattern (after the first two lines).
The problem is that your loop reads one line an "bits" of the second line. It is the "bits" of the second line being read that is problematic. Those bits prevent the beginning of the loop from reading where you probably want it to start reading.
I would recommend the loop reading just one line, or doing away with the loop and reading both lines before processing (depending on if the file has many or 2 lines of input).
Your code has three calls to in.nextLine() before it starts scanning line for tokens (ie int ID, name and number). This means it skips the two header lines, but also the first line of data.
I also noticed that you are not advancing to the next line once you have finished scanning tokens. So at the end of your while loop another call to in.nextLine() should get you in the right position for the next iteration.
This seems to work with my local testing:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class test {
public static void main(String[] args) throws FileNotFoundException {
Scanner inscan = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputfilename = inscan.nextLine();
File inputfile = new File(inputfilename);
Scanner in = new Scanner(inputfile);
String inputline = in.nextLine();
ArrayList<String> Names = new ArrayList<String>();
in.nextLine();
int total = 0;
while(in.hasNextLine()){
in.nextInt();
String Mname = in.next();
int Number = in.nextInt();
Names.add(Mname);
total += Number;
in.nextLine();
}
in.close();
for (String Mname : Names) {
System.out.println(Mname);
}
System.out.println("total number is " + total);
}
}
I am currently testing out a program who's purpose is to import a file and find the number of characters in that file using string manipulation.
I am currently using System.out.println(fileone.length()); to do so. However each time I try and run the program it reads the number of characters wrong, in fact it gives the same wrong number every time. Down below is the output of the program.
My name is Sam Tyler 54
As you can see the words in the file are displayed and next to that is the character number which is obviously wrong, as I counted myself, it should be 19, including spaces.
Here is the code that is reading the file and giving the character number.
Can you see any problems?
Any help is much appreciated.
Scanner ourScanner = new Scanner(new File(fileone));
System.out.println();
while(ourScanner.hasNextLine())
{
System.out.print (ourScanner.nextLine() + "\t");
count++;
if (count%4 == 0)
System.out.println();
}
}
//System.out.println ("\n\n" + count + " \ntotal strings found.");
System.out.println(fileone.length());
You are checking the length of the String representing the file path (fileone), not the actual file scanned, so it will be invariant given the context.
If you're counting the number of lines, just print your count variable.
You also have a number of ways to check for file length from a File object , or for specific character length (since the file system may allocate more space than actually used for the file), you can count them through iteration with a FileReader, etc.
fileone.length() gives you the length of the path of file.
But new File(fileone).length() will give you the file size in number of bytes (assuming one character is one byte)
Try this example:
1: read all the lines of the file
2: convert to a string
3: remove the white spaces
4: display the length in byte for the resulting string
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("C:\\Users\\xxx\\test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuffer fileContents = new StringBuffer();
String line = br.readLine();
while (line != null) {
fileContents.append(line);
line = br.readLine();
}
String sValue = fileContents.toString();
//remove all whitespace
sValue = sValue.replaceAll("\\s+","");
System.out.println(sValue.length());
}
}
Test:
test.txt content: My name is Sam Tyler 54 --> 18 characters
result:
18
I have got a question about a code I have written
package salescities;
import java.io.File;
import java.util.Scanner;
public class SalesCities {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double totalSales = 0;
int count = 0;
int missingCount = 0;
String line;
File file;
Scanner input;
try {
file = new File("sales.txt");
input = new Scanner(file);
input.useDelimiter(":");
while (input.hasNextLine()) {
input.next();
line = input.nextLine();
try{
totalSales += Double.parseDouble(line);
count++;
}
catch(IllegalArgumentException e){
missingCount++;
}
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(totalSales + " " +missingCount);
}
}
And the file im trying to read is like this
New York: 23.5678
New Jersey: no reports
Rio de Janeiro: 12.3654
When i run the program however it prints out 0.0 3 like all is missing.
The problem is when i run the debugger to see whats happening to line so parseDouble isn't functioning and i saw that line is a string that has this
: 23.5678
and I don't understand why if I'm using ":" as delimeter. I expected only the number without the colon. Can someone answer me?
ps: this is an exercise from a book that's quite simple but the book uses a class TextIO that is implemented by them. just wanted to try scanner instead of their code.
Scanner#nextLine grabs the rest of the line, regardless of the delimiter.
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. — Scanner#nextLine
In this program I am just getting input from a file and trying to get the boys name and the girls name out of it, and also put them in separate files. I have done everything just as the book has stated. And I've also searched everywhere online for help with this but cant seem to find anyone with the same problem. Ive seen problems where its not -1 but a positive number because they went to far out of the string calling a substring over the strings length. But cant seem to figure out this giving me -1 since i's value is 1.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
public class Homework_11_1 {
public static void main(String[] args)throws FileNotFoundException
{
File inputFile = new File("babynames.txt");
Scanner in = new Scanner(inputFile);
PrintWriter outBoys = new PrintWriter("boys.txt");
PrintWriter outGirls = new PrintWriter("girls.txt");
while (in.hasNextLine()){
String line = in.nextLine();
int i = 0;
int b = 0;
int g = 0;
while(!Character.isWhitespace(line.charAt(i))){ i++; }
while(Character.isLetter(line.charAt(b))){ b++; }
while(Character.isLetter(line.charAt(g))){ g++; }
String rank = line.substring(i);
String boysNames = line.substring(i, b);
String girlsNames = line.substring(b, g);
outBoys.println(boysNames);
outGirls.println(girlsNames);
}
in.close();
outBoys.close();
outGirls.close();
System.out.println("Done");
}
}
Here is the txt file
1 Jacob Sophia
2 Mason Emma
3 Ethan Isabella
4 Noah Olivia
5 William Ava
6 Liam Emily
7 Jayden Abigail
8 Michael Mia
9 Alexander Madison
10 Aiden Elizabeth
I would have written it an other way, using split.
public static void main(String[] args)throws FileNotFoundException
{
File inputFile = new File("babynames.txt");
Scanner in = new Scanner(inputFile);
PrintWriter outBoys = new PrintWriter("boys.txt");
PrintWriter outGirls = new PrintWriter("girls.txt");
while (in.hasNextLine()){
String line = in.nextLine();
String[] names = line.split(" "); // wile give you [nbr][boyName][GirlName]
String boysNames = names[1];
String girlsNames = names[2];
outBoys.println(boysNames);
outGirls.println(girlsNames);
}
in.close();
outBoys.close();
outGirls.close();
System.out.println("Done");
}
Rather than fuss with loops and substring(), I'd just use String.split(" "). Of course, the assignment may not permit you to do this.
But anyway, without giving you the answer to the assignment, I can tell you that your logic is wrong. Walk through it and find out why. If you try running this code on just the first line of the input file, you'll get these values: i=1, b=0, and g=0. Calling line.substring(1,0) is obviously not going to work.