This question already has answers here:
Error message "unreported exception java.io.IOException; must be caught or declared to be thrown" [duplicate]
(5 answers)
Closed 4 years ago.
My code for reading an input stream of numbers and sorts them into an array, returns
error:
unreported exception IOException; must be caught or declared to be thrown
on String lines = br.readLine();
public int[] inputArr() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
int [] a = new int [strs.length];
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
return a ;
}
Any help please on this?
BufferedReader.readLine() throws an IOException:
public String readLine() throws IOException {
So any call to it must handle it by either:
Surrounding with try/catch block
Declaring that your method also throws that exception.
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:
Why does a Try/Catch block create new variable scope?
(5 answers)
Closed 7 years ago.
I am trying to output the split contents of a .txt file.
Here is my code so far:
import java.io.FileReader;
import java.io.BufferedReader;
public class PassFail {
public static void main(String[] args) {
String path = "C:\\new_java\\Final_Project\\src\\student.txt";
try {
FileReader file = new FileReader(path);
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
reader.close();
String[] values = line.split(" ");
int nums[] = new int[values.length];
for (int x = 0; x < values.length; x++) {
nums[x] = Integer.parseInt(values[x]);
}
} catch (Exception e) {
System.out.println("Error:" + e);
}
System.out.println(nums[1]);
}
}
Question: Why am I getting the error "nums cannot be resolved to a variable" when trying to output num[2]? Furthermore, how can I fix this? To my knowledge I have already declared nums[] as a an int data type just before the for loop.
Because nums is defined in the try block, and you try to access it outside the try.
Also, it's nicer if you use an IDE like IntelliJ or Eclipse. This will help you format the code, and more easily spot errors like this.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
My code compiles, but I get this error at runtime:
Exception in thread "main" java.lang.ExceptionInInitializerError
at GUI.<init>(GUI.java:46)
at GUI.main(GUI.java:252)
Caused by: java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at java.util.Arrays$ArrayList.<init>(Arrays.java:3813)
at java.util.Arrays.asList(Arrays.java:3800)
at db.<clinit>(db.java:23)
... 2 more
This is the code causing the error:
public static String strLine;
public static String[] filearray;
public static List<String> list = Arrays.asList(filearray);
public static void load() throws IOException{
FileInputStream in = new FileInputStream("slist.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
filearray = new String[4];
while ((strLine = br.readLine()) != null) {
for (int j = 0; j < filearray.length; j++){
filearray[j] = br.readLine();
}
}
in.close();
Line 46 referenced in the error:
JList stafflist = new JList(db.list.toArray());
I am trying to load a text file as an Array and add it to the JList stafflist, but I get a runtime error.
It's in your declaration:
public static String[] filearray;
public static List<String> list = Arrays.asList(filearray);
fileArray is null, and you're trying to create a List around it.
You can either initialize fileArray right here:
public static String[] filearray = new String[4];
Or call Arrays.asList(filearray) after putting the values into filearray.
The problem that I see in your code is here:
public static String[] filearray;
public static List<String> list = Arrays.asList(filearray);
You are trying to convert filearray that is null at the time to list using Arrays.asList() method.
You should initialize filearray first.
I am getting an unreported exception; must be caught or declared to be thrown error in the fill method below. From similar posts I read I am assuming that the error originates since the read method has throws Exception but I cannot fix it.
public void read(int fileName) throws Exception
{
FileInputStream in = null;
try
{
Scanner in = new Scanner("dataset.txt");
File inFile = new File(in.nextLine());
in = new FileInputStream(inFile);
}
catch ( Exception e)
{
System.out.println(e);
}
BufferedReader buf = new BufferedReader(new InputStreamReader(in) );
String input;
input = buf.readLine();
fill(input,buf);
}
where fill is defined as:
public void fill(String in,BufferedReader buf)
{
StringTokenizer token = new StringTokenizer(input);
no = token.countTokens();
constraints = new Vector[noOfAttributes];
for (int i=0; i < no; i++)
{
c[i] = new Vector();
names = new String[noOfAttributes];
}
for (int i=0; i < no; i++)
{
names[i] = token.nextToken();
}
while((in = buf.readLine()) != null) //<----error given here
{
token = new StringTokenizer(input);
Train example = new Train(no);
}
buffer.close();
}
Your fillData calls buffer.readLine(), which is declared to throw IOException - but you neither catch the exception witin fillData, nor declare that it might be thrown.
The simplest fix is to change the signature of fillData to:
public void fillData(String input, BufferedReader buffer) throws IOException
I would also strongly recommend not closing the reader within fillData. Usually, the same code that acquires a resource should be responsible for closing it. A try-with-resources statement is most appropriate here, so in read:
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(in))) {
String input = buffer.readLine();
fillData(input,buffer);
}
Even this isn't ideal, however - because you're opening the input stream earlier on. I'd also recommend always passing an encoding to the InputStreamReader constructor, otherwise it will use the platform default encoding. In Java 7+ you can use Files.newBufferedReader which defaults to UTF-8.
Additionally:
read declaring that it throws Exception is generally a bad idea; only throw specific exceptions
Catching Exception in read is a bad idea; only catch specific exceptions
Continuing in read after a failure is a bad idea - in will be null, causing a failure immediately afterwards
It's very bizarre to have a parameter called fileName of type int. As it happens, you're not using that anyway - what's the point of it?
Basically all of your exception handling and resource management needs a fair amount of work.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why do I get the “Unhandled exception type IOException”?
I'm trying to solve Euler #8 using the following algorithm. Problem is, whenver I modify the line I have the giant comment on, the error Unhandled Exception Type IOException appears on each line that I've marked with the comment //###.
private static void euler8()
{
int c =0;
int b;
ArrayList<Integer> bar = new ArrayList<Integer>(0);
File infile = new File("euler8.txt");
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(infile), //###
Charset.forName("UTF-8")));
while((c = reader.read()) != -1) { //###
char character = (char) c;
b = (int)character;
bar.add(b); /*When I add this line*/
}
reader.close(); //###
}
Yes, IOException is a checked exception, which means you either need to catch it, or declare that your method will throw it too. What do you want to happen if the exception is thrown?
Note that you should generally be closing the reader in a finally block anyway, so that it gets closed even in the face of another exception.
See the Java Tutorial lesson on exceptions for more details about checked and unchecked exceptions.
One solution: change to
private static void euler8() throws IOException {
But then the calling method has to catch the IOException.
or catch the Exception:
private static void euler8()
{
int c =0;
int b;
ArrayList<Integer> bar = new ArrayList<Integer>(0);
BufferedReader reader;
try {
File inFile = new File("euler8.txt");
reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(infile), //###
Charset.forName("UTF-8")));
while((c = reader.read()) != -1) { //###
char character = (char) c;
b = (int)character;
bar.add(b); /*When I add this line*/
}
} catch (IOException ex) {
// LOG or output exception
System.out.println(ex);
} finally {
try {
reader.close(); //###
} catch (IOException ignored) {}
}
}
Wrap in a try/catch block to catch the Exceptions.
If you do not do that it will go unhandled.
What happens if you can't read the nominated file ? The FileInputStream will throw an exception and Java mandates that you'll have to check for this and handle it.
This type of exception is called a checked exception. Unchecked exceptions exist and Java doesn't require you to handle these (largely because they're unhandable - e.g. OutOfMemoryException)
Note that your handling may include catching it and ignoring it. This isn't a good idea, but Java can't really determine that :-)