i currently have this code
My problem is that when i give a number 1 or 2, it doesn't give it and just says 'Not valid input'.
It would be nice if anyone could explain me why is it happening.
Thanks for any answer.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Screen {
private static BufferedReader stdin;
private static PrintStream os;
public static void main(String[] args) throws IOException{
try {
stdin = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
System.exit(1);
}
try {
switch (Integer.parseInt(selectAction())) {
case 1:
os.println("1");
System.err.print("Hello World ");
break;
case 2:
os.println("2");
System.err.print("Another Word ");
break;
}
} catch (Exception e) {
System.err.println("not valid input");
}
}
public static String selectAction() throws IOException {
System.out.println("1. Hello World.");
System.out.println("2. Another Word.");
System.out.print("\nMake selection: ");
return stdin.readLine();
}
}
Provide an initialization for os to prevent the NullPointerException. Your code works if I change the os declaration like
private static PrintStream os = System.out;
Also, please don't swallow the Exception
} catch (Exception e) {
System.err.println("not valid input: " + e.getMessage());
e.printStackTrace(System.err);
}
Related
In the following piece of code :
import java.io.*;
import java.io.FileReader;
public class ExceptionPropagationDemo {
public static void main(String[] args){
ExceptionPropagationDemo testObject =new ExceptionPropagationDemo();
testObject.throwException1();
}
public void throwCheckedException(){
try{ //try - catch error block
BufferedReader br;
br = new BufferedReader(new FileReader("/Project1/src/employee.txt"));
} catch(FileNotFoundException e){
System.out.println("An IO exception happened and has been handled");
}
finally {
System.out.println("This block always executes.");
}
}
public void throwException2() {
throwCheckedException();
}
public void throwException1(){
throwException2();
}
}
I'm trying to catch a checked exception and handle it. In my case it would be FileNotFoundException, but I don't know for what reason it never runs the catch block which I'm trying to print a message or any other functionality, but it seems it jumps over.Thank you
I want to convert my IO Class from java on Eclipse to the Android API. For some reason it's not working on android!It is giving me a NullPointerException on my Println method. This class is used to create, write, read and open textfiles. My goal is to make all these methods readable on android.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
public class IO {
private static PrintWriter fileOut;
private static BufferedReader fileIn;
public static void createOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
} catch (IOException e) {
System.out.println("*** Cannot create file: " + fileName + " ***");
}
}
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void openOutputFile2(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void print(String text) {
fileOut.print(text);
}
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
public static void closeOutputFile() {
fileOut.close();
}
public static void openInputFile(String fileName) {
try {
fileIn = new BufferedReader(new FileReader(fileName));
//System.out.println("opening " + fileName);
} catch (FileNotFoundException e) {
System.out.println("***Cannot open " + fileName + "***");
}
}
public static String readLine()
// throws IOException
// Note: if there's an error in this method it will return IOException
{
try {
return fileIn.readLine();
} catch (IOException e) {
e.printStackTrace();
return "errors";
}
}
public static void closeInputFile() {// throws IOException
// Note: if there's an error in this method it will return IOException
try {
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you're getting a NullPointerException in println then that would be because 'fileOut' is null.
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
You're actually reacting on your second error because you've ignored the first one. In all cases where you set fileOut you're swallowing (effectively hiding) the error. E.g.
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
//Don't do this, it makes debugging much more difficult.
//Because the root problem is hidden.
//So now you have 2 problems to solve.
//And you've thrown away the information that might have
//helped to solve the problem in the first place.
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
Stop hiding errors, if something goes wrong you need to find out about it. Because invariably, ignoring errors results in more complex errors later down the line.
Fix you bad exception handling, and you'll be able to track down the root problem (probably file not found or a permission error).
course.txt file is not read by my code. It allows me to enter the file name, but doesn't open the file.
package javaexam;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.BufferedReader;
import java.util.Scanner;
public class BufferReader {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
BufferedReader bf = null; // shows warning that assigned but never used
String line;
System.out.println("Please enter the file name");
try {
bf = new BufferedReader(new FileReader("C:\\Users\\MohammedArfa\\Desktop\\New folder\\" + scanner.next()));
} catch(FileNotFoundException fnfex) {
//shows warning that the buffer assignment is declared but never used
System.out.println(fnfex.getMessage()+"The file was not found");
}
System.exit(0);
try {
while((line=bf.readLine()) != null) {
System.out.println(line);
}
} catch(IOException ex) {
System.out.println(ex.getMessage()+"Error reading file");
} finally {
System.out.println(0);
}
}
}
Move the system.exit(0) into the catch statement above...
try {
bf = new BufferedReader(new FileReader("C:\\Users\\MohammedArfa\\Desktop\\New folder\\" + scanner.next()));
} catch(FileNotFoundException fnfex) {
//shows warning that the buffer assignment is declared but never used
System.out.println(fnfex.getMessage()+"The file was not found");
System.exit(0);
}
If the system.exit(0) is not inside the catch then it is always being executed which terminates your program before you reach the print out loop.
I created three text files, inputt.txt, outputt.txt, & errorr.txt. Inputt.txt is for input, outputt.txt is supposed to print all numbers from inputt.txt that are valid integers, and errorr.txt prints all the errors from the input text file. I am having trouble with iteration. The System.out.println prints all the numbers from inputt.txt just fine; however, when i try to print all the numbers into outputt.txt, it only prints the first line of numbers. Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Lab5_Exceptions_Redo extends Exception {
public static void main(String[] args) throws FileNotFoundException {
String file = "inputt.txt";
String file1 = "outputt.txt";
String file2 = "errorr.txt";
PrintWriter errorr = new PrintWriter(file2);
PrintStream ps = new PrintStream(file2);
PrintWriter outputt = new PrintWriter(file1);
Scanner scan = new Scanner(new File(file));
while (scan.hasNext()) {
try {
String number = scan.nextLine();
int num = Integer.parseInt(number);
System.out.println(num);
outputt.println(num);
} catch (InputMismatchException e) {
errorr.println("There was an input mismatch error.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (NoSuchElementException e) {
errorr.println("There is no such element.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (UnsupportedOperationException e) {
errorr.println("An unsupported operation occured.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (NumberFormatException e) {
errorr.println("Number Format Exception.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
}
errorr.close();
outputt.close();
}
scan.close();
}
}
The PrintWriter stream variable errorr should move outside the for loop. Try the following version of code.
public class Lab5_Exceptions_Redo extends Exception {
public static void main(String[] args) throws FileNotFoundException {
String file = "inputt.txt";
String file1 = "outputt.txt";
String file2 = "errorr.txt";
PrintWriter errorr = new PrintWriter(file2);
PrintStream ps = new PrintStream(file2);
PrintWriter outputt = new PrintWriter(file1);
Scanner scan = new Scanner(new File(file));
while (scan.hasNext()) {
try {
String number = scan.nextLine();
int num = Integer.parseInt(number);
System.out.println(num);
outputt.println(num);
} catch (InputMismatchException e) {
errorr.println("There was an input mismatch error.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (NoSuchElementException e) {
errorr.println("There is no such element.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (UnsupportedOperationException e) {
errorr.println("An unsupported operation occured.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
} catch (NumberFormatException e) {
errorr.println("Number Format Exception.");
errorr.println(e.getMessage());
e.printStackTrace(ps);
}
}
errorr.close();
outputt.close();
scan.close();
}
}
I'm successfully able to read from and write to a sample text file in Java. However, when I try to read from the file, it always throws a NoSuchElementException when it reaches the end of the file. I've modified the code to catch this exception by printing "Reached end of file," but I was wondering if that was normal; I don't feel like it is and I feel like I'm missing something.
Any help is appreciated. Here is my code:
MyFileWriter.java
import java.io.*;
public class MyFileWriter {
public static void main(String[] args) {
File file = new File("MyFile.txt");
PrintWriter out = null;
try {
out = new PrintWriter(file);
out.write("This is a text file.");
} catch(IOException e) {
e.printStackTrace();
System.out.println("IOException: " + e.getMessage());
} finally {
out.flush();
out.close();
}
}
}
MyFileReader.java
import java.io.*;
import java.util.*;
public class MyFileReader {
public static void main(String[] args) {
File file = new File("MyFile.txt");
Scanner scan = null;
try {
scan = new Scanner(file);
while(true) {
String next = scan.nextLine();
if(next != null) {
System.out.println(next);
}
else {
break;
}
}
} catch(IOException e) {
e.printStackTrace();
System.out.println("IOException: " + e.getMessage());
} catch(NoSuchElementException e) {
System.out.println("***Reached end of file***");
} finally {
scan.close();
}
}
}
Instead of while(true) in the reader, use while( scan.hasNextLine() )