This question already has answers here:
How can I use hasNextInt() to catch an exception? I need Int but if input is character, that is bad
(3 answers)
Closed 9 years ago.
Basically I am taking a string input that represents a file. That file can contain integers, doubles or random strings. I am trying to iterate through the file adding all the integers and then taking the average of all of them. The issue I'm stuck on is when I get something other than an integer. I don't know how I am supposed to catch and deal with the error and then iterate onto the next part of the file. I can't use if statements and I'm thoroughly stuck.
String storeVariables = null;
FileReader fileReader;
BufferedReader bufferedReader;
Scanner scanner = null;
int total = 0;
int itterate = 0;
try{
fileReader = new FileReader(filename);
bufferedReader = new BufferedReader(fileReader);
scanner = new Scanner(bufferedReader);
while(scanner.hasNextInt()){
total += scanner.nextInt();
itterate++;
}
}
catch(Exception e){
}
return total/itterate;
}
Scanner#nextInt may throws
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
Try this -
while(scanner.hasNextInt()){
try{
total += scanner.nextInt();
itterate++;
}catach(RuntimeException nfe){...}
}
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm trying to read in a text file which looks similar to this:
0000000000
0000100000
0001001000
0000100000
0000000000
Here is my code:
public static int[][] readBoard(String fileName) throws FileNotFoundException {
File life = new File(fileName);
Scanner s = new Scanner(life);
int row = s.nextInt();
int columns = s.nextInt();
int [][] size = new int [row][columns];
for (int i=0; i <= row; i++) {
String [] state = new String [columns];
String line = s.nextLine();
state = line.split("");
for (int j=0; i <= columns; i++) {
size[i][j] = Integer.parseInt(state[j]);
}
}
return size;
}
It keeps giving me this error. I think it's the Integer.parseInt(state[j]) that is giving me trouble, but I don't know why.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Project5.readBoard(Project5.java:33)
at Project5.main(Project5.java:9)
I've executed your code with the example input, and you have logical issues in the code. With the exmaple input the code doesn't even reach the parseInt() line where the asked NumberFormatException could be thwrown. I assume you have tried your code in a different input. The Exception message is staithforward, you tried to parse an empty string to number. It's a typical NumberFormatException. The parseInt() function can throw Exception, so your code must be prepared for it.
The other problem is a basic logical issue in your algorithm. Your row and column variables will be populated with the first to integer token from the text. Based on the exampe input the first integer token will be the first row 0000000000 which integer value is 0, and the second token is 0000100000 which will parsed as 100000. So you are trying to initialize an array with these dimensions which is imposible.
To calculate the row count, you have to read the file line by line. And to get the column counts you have the check the length of the lines. (It can open a new question, how do you want to handle the not properly formatted input file, because in the file the line length can be various.)
That means you can only be sure with the dimensions of the board if you have already iterated though the file content. To prevent the multiple iteration you should use dinamic collection instead of a standard array, like ArrayList.
That means while you are read the file line by line, you can process the the characters one after another in a line. In this step you should be concidered about the invalid characters and the potential empty characters in the end of the file. And during this iteration the final collection can be built.
This example shows a potention solution:
private static int processCharacter(char c) {
try {
return Integer.parseInt((Character.toString(c)));
} catch (NumberFormatException e) {
return 0;
}
}
public static List<List<Integer>> readBoard(String fileName) throws FileNotFoundException {
List<List<Integer>> board = new ArrayList<>();
File file = new File(fileName);
FileReader fr = new FileReader(file);
try (BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim(); // removes empty character from the line
List<Integer> lineList = new ArrayList<>();
if(line.length() > 0) {
for (int i = 0; i < line.length(); i++) {
lineList.add(Main.processCharacter(line.charAt(i)));
}
board.add(lineList);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return board;
}
This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 4 years ago.
i would like to build a text data-cleaner in Java, which
cleans the text from Smileys and other special charakter. I wrote a text reader,
but he stops after 3/4 of Line 97 and i just don't know why he does it? Normally he should read the complete text file (ca. 110.000 Lines) and then stop. It would be really nice if could show me where my mistake is.
public class FileReader {
public static void main(String[] args) {
String[] data = null;
int i = 0;
try {
Scanner input = new Scanner("C://Users//Alex//workspace//Cleaner//src//Basis.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
data[i] = line;
i++;
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(data[97]);
}
}
Your mistake is here:
String[] data = null;
I would expect this code to throw null pointer exception...
You can use ArrayList instead of plain array if you want to have dynamic re-sizing
This question already has answers here:
using hasNextLine() but still getting java.util.NoSuchElementException: No line found
(5 answers)
Closed 5 years ago.
When I try to use java scanner it works and in my list I get all the text file content as a list.
But when I try to print within the while loop, it throws
java.util.NoSuchElementException: No line found
exception at the last line. Why would that be the case, wouldn't mylist also thrown had it been out of bound?
try {
Scanner myscanner = new Scanner(new FileReader(myfilepath));
while(myscanner.hasNextLine()){
//System.out.println(myscanner.nextLine() );
mylist.add(myscanner.nextLine());
numline += 1;
}
myscanner.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
You check that you have next line and then when you print you read 2 lines.
You should change it to:
String line = myscanner.nextLine();
// print and add to list using line variable
To avoid that you should create variable to store the result fo myscanner.nextLine() then print it and add it to the list. e.g
while(myscanner.hasNextLine()){
String temp = myscanner.nextLine();
System.out.println(temp);
mylist.add(temp);
numline += 1;
}
I am a beginner. Reading from text file in Java using a scanner. This code just to read the first 3 tokens isn't working:
try{
Scanner scFile = new Scanner (new File ("readhere.txt")).useDelimiter("#");
String first = scFile.next();
String second = scFile.next();
int third = scFile.nextInt(); // error here. Why cant I store the integer?
}
catch(FileNotFoundException e){
System.out.println("Error");
}
I am trying to read just the first 3 tokens:
Andrew#Smith#21
John#Morris#55
the problem occurs when reading 21. java.util.InputMismatchException
The scanner is including the carriage return character(s) as part of the next readable token which produces an invalid integer. You could do
Scanner scanner = new Scanner(new File("readhere.txt")).useDelimiter("#|\r\n");
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 8 years ago.
My System.out.println(info); line gives back "Model_X_Sale_2014.txt" instead of the information in the file. The first line being: "Jan 3128 1.59 3421 1.79" I'm new to splitting a string, but this problem is occuring before the string is even splitting.
Any idea what may be causing this? Thanks for the time either way. Also, is there a particular reason Eclipse wont let me use a try catch around the file stuff?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What year would you like to review?");
int year = Integer.parseInt(keyboard.nextLine());
String fileName= "Model_X_Sale_" + year + ".txt";
Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();//read one line at a time
MonthlySale_Baumbach input = new MonthlySale_Baumbach(line);
System.out.printf("\n%s %15.2f %s15.2f", input.getMonth(), input.getProfitX310(), input.getProfitX410());
}
scanner.close();
}
public class MonthlySale_Baumbach {
//variables
String month;
int X310_Units, X410_Units;
double X310_uPrice, X410_uPrice;
public MonthlySale_Baumbach(){}
public MonthlySale_Baumbach(String info){
System.out.println(info);
String[] st = info.split("\\s");
month = st[0];
X310_Units = Integer.parseInt(st[1]);
X310_uPrice = Double.parseDouble(st[2]);
X410_Units = Integer.parseInt(st[3]);
X410_uPrice = Double.parseDouble(st[4]);
}//end of constructor
}
Start by reading the documention for Scanner(String)
public Scanner(String source)Constructs a new Scanner that
produces values scanned from the specified string.
Parameters: source - A string to scan
What you probably want is Scanner(File)
public Scanner(File source) throws FileNotFoundException
Constructs a new Scanner that produces values scanned from the
specified file. Bytes from the file are converted into characters
using the underlying platform's default charset.
Parameters: source - A file to be scanned
Throws: FileNotFoundException - if source is not found