public static void main (String[] args) {
try{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
System.out.println ("1..case1 | 2..case2");
String ch=Integer.parseInt(bf.readLine()); //user input for switch
System.out.println (ch);
bf.close();
switch(ch) { //userinput ch variable switch in case
case 1 :
String data=bf.readLine();
bf.close();
System.out.println(data);
break;
case 2 :
System.out.print ("Enter Key ");
String key=bf.readLine();
bf.close();
System.out.println(key);
break;
default :
System.out.println ("wrong choice");
}
}
catch(IOException e){
System.out.println ("io error");
}
bf.close();
}
//every time after 1st user input it goes to partcular matching case, but at the next user input it throws an exception.
please help..
thanks in advance..
Its a good habit to close in finally block else use try with resource if you are using java7 or higher version
See this mkyongs example
Also this line is wrong String ch=Integer.parseInt(bf.readLine()); make it to int
you are converting bf.readLIne() to int and storing in string,This is wrong.
Another error is you are closing bf.close(); after the try-catch block so compiler may complain
Complete working code
public static void main (String[] args) {
BufferedReader bf=null;
try{
bf=new BufferedReader(new InputStreamReader(System.in));
System.out.println ("1..case1 | 2..case2");
int ch=Integer.parseInt(bf.readLine()); //user input for switch
System.out.println (ch);
switch(ch){ //userinput ch variable switch in case
case 1 :
String data=bf.readLine();
System.out.println(data);
break;
case 2 :
System.out.print ("Enter Key ");
String key=bf.readLine();
System.out.println(key);
break;
default :
System.out.println ("wrong choice");
}
} catch(IOException e){
System.out.println ("io error");
e.printStackTrace();
}
finally
{
try {
bf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
I got a problem with my university task.
How to start program: type 1 to create a file then write down the name of text file and fill it with words. After that press enter 2 times and you will get my problem -> NoSuchElementException.
I tried to fix this problem by creating different types of loops or changing the structure of the project, but still don`t know how to fix it. I just stuck and wasted some time on this problem. If someone more knowledgeable could help me out it would be wonderful.
My code all in one class:
import java.io.*;
import java.util.Scanner;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
showMenu();
}
static void showMenu() throws IOException {
menuOptions();
Scanner scan = new Scanner(System.in);
int userMenuInput = 0;
if (scan.hasNextLine()) {
try {
userMenuInput = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
while (true) {
switch (userMenuInput) {
case 1:
System.out.println("Create a file");
String userFileName = scan.nextLine();
createFile(userFileName + ".txt");
break;
case 2:
System.out.println("Delete a file");
String userDeleteFile = scan.nextLine();
deleteFile(userDeleteFile);
break;
case 3:
System.out.println("Write to a file");
break;
case 4:
System.out.println("Exit from program");
System.exit(0);
break;
default:
System.out.println("Please type from 1 to 4!");
}
}
}
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
in.close(); // Close reader from input
out.close(); // Close writer to file
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
private static void deleteFile(String fileNameToDelete){
try{
System.out.println("Enter file name to delete: ");
File sourceFile = new File(fileNameToDelete+".txt");
sourceFile.delete();
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static void menuOptions(){
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Create file");
System.out.println("2 - Delete file");
System.out.println("3 - Write to file");
System.out.println("4 - Quit");
System.out.println();
}
}
to add to Ryans answer, the exception comes from the fact that closing any object making use of the input/output stream doesn't really close that object, but the entire input/output stream. A dirty fix would simply be NOT to close them. so change your method createFile from:
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
in.close(); // Close reader from input
out.close(); // Close writer to file
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
to:
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
//were close used to be
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
I will stess that this is NOT ideal. You should do what Ryan said and make it so you only use use a single System.in reader. Doing that is your job, not mine. But if this is just to get something working so you can submit an assignment on time, it will work.
Another issue is that the prompt asking for a menu option is outside of the while loop. This means that it will accept only one input, then get stuck in an infinite loop. You could move that into the loop, but a cleaner alternative is to put all of the menu logic into the menuOption method, pass a reference of the Scanner to that method, and have it return an int for your switch.
for example:
menuOption():
private static int menuOptions(Scanner scan){
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Create file");
System.out.println("2 - Delete file");
System.out.println("3 - Write to file");
System.out.println("4 - Quit");
System.out.println();
if (scan.hasNextLine()) {
try {
return Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
return 0;
}
showMenu():
static void showMenu() throws IOException {
Scanner scan = new Scanner(System.in);
while (true) {
switch (menuOptions(scan)) {
case 1:
System.out.println("Create a file");
String userFileName = scan.nextLine();
createFile(userFileName + ".txt");
break;
case 2:
System.out.println("Delete a file");
String userDeleteFile = scan.nextLine();
deleteFile(userDeleteFile);
break;
case 3:
System.out.println("Write to a file");
break;
case 4:
System.out.println("Exit from program");
System.exit(0);
break;
default:
System.out.println("Please type from 1 to 4!");
}
}
}
all of those changes lead to this as the final code:
import java.io.*;
import java.util.Scanner;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
showMenu();
}
static void showMenu() throws IOException {
Scanner scan = new Scanner(System.in);
while (true) {
switch (menuOptions(scan)) {
case 1:
System.out.println("Create a file");
String userFileName = scan.nextLine();
createFile(userFileName + ".txt");
break;
case 2:
System.out.println("Delete a file");
String userDeleteFile = scan.nextLine();
deleteFile(userDeleteFile);
break;
case 3:
System.out.println("Write to a file");
break;
case 4:
System.out.println("Exit from program");
System.exit(0);
break;
default:
System.out.println("Please type from 1 to 4!");
}
}
}
private static void createFile(String fileName){
System.out.println(System.getProperty("user.dir"));
File myFile = new File(System.getProperty("user.dir") + "\\" + fileName);
try {
myFile.createNewFile();
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
// Create PrintWriter to write to file
PrintWriter out = new PrintWriter(new FileWriter(myFile));
String s;
System.out.print("Enter text: ");
while ((s = in.readLine()) != null && (s.length() != 0)) {
out.println(s);
}
//were close used to be
} catch (IOException e) {
System.out.println("File writing failed!");
}
System.out.println(myFile.getAbsolutePath());
}
private static void deleteFile(String fileNameToDelete){
try{
System.out.println("Enter file name to delete: ");
File sourceFile = new File(fileNameToDelete+".txt");
sourceFile.delete();
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static int menuOptions(Scanner scan){
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Create file");
System.out.println("2 - Delete file");
System.out.println("3 - Write to file");
System.out.println("4 - Quit");
System.out.println();
if (scan.hasNextLine()) {
try {
return Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
return 0;
}
}
Remember to close scan in your quit method.
Program execution does not loop back once I run the code to read data.
Ive tried shifting where I place the try catch statements along with the finally statement and all manners of breaks continue.
long code;
char choice;
Cars CarSales = new Cars(); //It creates a Java object and allocates memory for it on the heap.
Scanner sc = new Scanner(System.in);
System.out.println(" -----CARS SALES YARD------"); //The println is a method of java.io.PrintStream.
do {
System.out.println("1. Add item");
choice = sc.nextLine().charAt(0);
switch (choice) { //switch statement allows a variable to be tested for equality against a list of values.
case '6':
try{
CarSales.ReadData();
continue;
}
catch(IOException e){
System.out.println("Error reading file '" );
continue;
}
default:
System.out.println("Invalid Selection\n");
}
} while (choice != '6'); //while loop statement repeatedly executes a statement as long as a given condition is true
sc.close();
public void ReadData() throws IOException{//This Method is in the Cars class
String fileName = "input.txt";
String line = null;
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
System.out.println("TRY");
No error messages though program execution just stops looping.
By moving the continue; to after the catch. Like,
do {
System.out.println("1. Add item"); //<-- where are 2-6?
choice = sc.nextLine().charAt(0);
switch (choice) {
case '6': // <-- don't forget case '1' - '5'
try {
CarSales.ReadData();
} catch (IOException e) {
System.out.println("Error reading file '");
}
continue; // <-- here, or a break;
default:
System.out.println("Invalid Selection\n");
}
} while (choice != '6');
I'm at my wits end here, me and a friend have been trying to get user input and write that to a .txt file but I have no idea where I'm gone wrong...
public static void main (String [] args)
{
toTxtFile();
}
static void toTxtFile()
{
//Scanner in = new Scanner (System.in);
try
{
File records = new File("C:\\Users\\rodriscolljava\\Desktop\\IOFiles\\test3.txt");
records.createNewFile();
FileWriter fw = new FileWriter(records, true);
PrintWriter pw = new PrintWriter(fw);
String str = JOptionPane.showInputDialog(null,"Enter your text below");
str = str.toUpperCase();
pw.println(str);
if (str.length() == 3 && str.contains("END"))
{
JOptionPane.showMessageDialog(null, "You've ended the task","ERROR",JOptionPane.ERROR_MESSAGE);
pw.flush();
pw.close();
//in.close();
}
else
{
pw.println(str);
toTxtFile();
}
}
catch (IOException exc)
{
exc.printStackTrace();
}
}
}
I've tried putting the loop as a do/while with far from good results, any help would be appreciated D:
You can use a try-with-resources to close when you're done; and you might use an infinite loop with a break like
static void toTxtFile() {
File records = new File("C:\\Users\\rodriscolljava\\Desktop\\IOFiles\\test3.txt");
try (PrintWriter pw = new PrintWriter(records)) {
while (true) {
String str = JOptionPane.showInputDialog(null, "Enter your text below");
str = str.toUpperCase();
if (str.equals("END")) {
JOptionPane.showMessageDialog(null, "You've ended the task",
"ERROR", JOptionPane.ERROR_MESSAGE);
break;
}
pw.println(str);
}
} catch (IOException exc) {
exc.printStackTrace();
}
}
you have to add ,
pw.flush();
after pw.println(str);
and want to do it again and again then put it into while loop likewise,
while(true){
String str = JOptionPane.showInputDialog(null,"Enter your text below");
str = str.toUpperCase();
if (str.length() == 3 && str.contains("END"))
{
JOptionPane.showMessageDialog(null, "You've ended the task","ERROR",JOptionPane.ERROR_MESSAGE);
break;
}
pw.println(str); // else write to file...
pw.flush();
}
pw.flush();
pw.close();
import java.util.Scanner;
public class Lab4_5 {
public static void main(String[]args) {
Scanner scan= new Scanner(System.in);
int rows=0;
int rowIndex=0, colIndex=0;
boolean choice1= true;
String y="y";
String n="n";
boolean first = true;
while (choice1==true) {
if (first==true) {
first=false;
System.out.println("Do you want to start(Y/N): ");
} else if (first==false) {
System.out.println("Do you want to continue(Y/N): ");
}
String choice2=scan.next();
if (choice2.equals(y)) {
System.out.println("How many rows/columns(5-21)?");
rows=scan.nextInt();
while (rows<5 || rows>21) {
System.out.println("That is either out of range or not an integer, try again! ");
rows=scan.nextInt();
}
System.out.println("What character?");
String choice3=scan.next();
System.out.println(" ");
for (rowIndex=1; rowIndex<=rows; rowIndex++) {
for (colIndex=1; colIndex<=rows; colIndex++) {
if (rowIndex==1 || rowIndex==rows || colIndex==1 || colIndex==rows) {
System.out.print(choice3);
} else {
System.out.print(" ");
}
}
System.out.println();
}
} else if(choice2.equals(n)) {
choice1 = false;
System.out.println("Thank you. Goodbye.");
} else {
System.out.println("Please either enter Y or N.");
}
}
}//end of main
}
The code prints what I need it to print, but I also have to have something in the code when it asks how many rows/columns to catch whether or not i input something other than an integer(in the part below). need some help, we haven't done anything yet with how to catch exceptions and i don't know how to start.
String choice2=scan.next();
if (choice2.equals(y)) {
System.out.println("How many rows/columns(5-21)?");
rows=scan.nextInt();
while (rows<5 || rows>21) {
System.out.println("That is either out of range or not an integer, try again! ");
rows=scan.nextInt();
}
}
You need to understand this please look into it.
Basic understanding is
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught.
}
There is also an finally block which will always be execute even if there is an error. it is used like this
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught & the returned.
} finally {
// This will always execute if there is an exception or no exception.
}
In your particular case you can have the following exceptions (link).
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
So you would need to catch exceptions like
try {
rows=scan.nextInt();
} catch (InputMismatchException e) {
// When the InputMismatchException is caught.
System.out.println("The next token does not match the Integer regular expression, or is out of range");
} catch (NoSuchElementException e) {
// When the NoSuchElementException is caught.
System.out.println("Input is exhausted");
} catch (IllegalStateException e) {
// When the IllegalStateException is caught.
System.out.println("Scanner is close");
}
You can create a try-catch block like so:
try {
int num = scan.nextInt();
} catch (InputMismatchException ex) {
// Exception handling here
}
If you want to implement this in your code, I suggest doing this:
while (true) {
try {
rows = scan.nextInt();
if (rows<5||rows>21) {
break;
}
else {
System.out.println("That is either out of range or not an integer, try again! ");
}
} catch (InputMismatchException ex) {
System.out.println("That is either out of range or not an integer, try again! ");
}
}
See here for more details.
String choice2=scan.next();
if(choice2.equals(y)){
System.out.println("How many rows/columns(5-21)?");
try
{
rows=scan.nextInt();
}catch(Exception e)
{
rows = -1;
}
while(rows<5||rows>21){
System.out.println("That is either out of range or not an integer, try again! ");
try
{
rows=scan.nextInt();
}catch(Exception e)
{
rows = -1;
}
}
Given the following code, the first call to readLine() is not blocking, both "Enter name:" and "Enter address:" are printed at the same time, and address gets assigned to whatever is entered. Why? I've tried putting them in separate try blocks, getting rid of the loop and generally reordering things.
public class AddressReader {
public static void main(String[] args) {
Path file = Paths.get("d:/java IO/addresses.txt");
try {
Files.createDirectories(file.getParent());
} catch (IOException e) {
System.err.println("Error craeting directory: " + file.getParent());
e.printStackTrace();
System.exit(1);
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int c = 0;
try {
System.out.println("<a>dd an entry or <r>ead entries");
c = br.read();
} catch (IOException e) {
System.out.println("An error has occured, try again");
}
switch (c) {
case 'a':
String name = null;
String address = null;
while (name == null || name == "" || address == null || address == "") {
try {
System.out.println("Enter name:");
name = br.readLine();
System.out.println("Enter address:");
address = br.readLine();
} catch (IOException e) {
System.out.println("An error has occured, try again");
}
System.out.println("name = " + name);
System.out.println("address = " + address);
}
//writeEntry(file, name, address);
break;
case 'r':
//readEntries(file);
break;
default:
System.out.println("Invalid entry, try again.");
}
}
}
This is because of this line:
c = br.read();
This does not consume the new-line character that is produced by pressing ENTER.
To solve this issue, use this instead:
c = br.readLine().charAt(0);
Over and above whats already been said, for what you're trying to do I suggest using the Console instead:
Console console = System.console();
String name = console.readLine("Create a name.");
char[] password = console.readPassword("Create a password.");
System.out.println(name + ":" + new String(password));