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');
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.
I'm relatively new to coding and I've encountered a problem with switches, a loop and choosing which case to output and not output every case before that case as well.
I'm aware this problem is because of the counter, because the counter only gets to my case by counting upwards and outputting every case in the way to get the the one I want, only stopping there. But that's not even it, in this program it outputs all the case regardless of what I input! I have very little idea of what to do.
I tried using break loops, but the outcome was pretty expected. It only outputs the first case.
The point of this program is to write to a file called "foo.txt" and after a user inputs a specific letter from "COMPUTERS", a single line from the text in "foo.txt" is outputted. There are 9 letters in "COMPUTERS" and 9 sentences in "foo.txt". No hard coding allowed.
QUESTION: How can I, in a switch inside a loop, select a specific case and only output that case?
ANY help is highly appeciated.
// The "Lab_raminAmiri" class.
import java.io.*;
public class Lab_raminAmiri
{
public static void main (String[] args)
{
sendLines ();
userInputChar ();
readLines ();
} // main method
public static void sendLines ()
{
try
{
FileWriter fw = new FileWriter ("foo.txt");
PrintWriter pw = new PrintWriter (fw);
pw.println ("\nCome to the lab on time.");
pw.println ("Operate your computer properly.");
pw.println ("Make sure to listen attentively.");
pw.println ("Print only what is required.");
pw.println ("Use the Net with respect.");
pw.println ("Touch the keyboard gently.");
pw.println ("Eat or drink outside the lab.");
pw.println ("Remember to finish your assignment.");
pw.println ("Shutdown the computer at the end of class.");
pw.close ();
}
catch (IOException e)
{
}
} //sendLines method
public static void userInputChar ()
{
char input;
System.out.println ("Enter a letter from the word COMPUTERS");
input = In.getChar ();
}
public static void readLines ()
{
FileReader fr;
int counter = -1;
String line = null;
try
{
BufferedReader br = new BufferedReader (new FileReader ("foo.txt"));
System.out.print ("\nLine printed: ");
loop:
while ((line = br.readLine ()) != null)
{
counter++;
switch (counter)
{
case 1:
case 'c':
System.out.println ("1: " + line);
break loop;
case 2:
case 'o':
System.out.println ("2: " + line);
break loop;
case 3:
case 'm':
System.out.println ("3: " + line);
break loop;
case 4:
case 'p':
System.out.println ("4: " + line);
break loop;
case 5:
case 'u':
System.out.println ("5: " + line);
break loop;
case 6:
case 't':
System.out.println ("6: " + line);
break loop;
case 7:
case 'e':
System.out.println ("7: " + line);
break loop;
case 8:
case 'r':
System.out.println ("8: " + line);
break loop;
case 9:
case 's':
System.out.println ("9: " + line);
break loop;
}
}
br.close ();
}
catch (IOException e)
{
}
} //readLines method
} // Lab_raminAmiri class
Instead of reading input in different method you can take input in "readLines" method itself.
Try the below code:
public static void readLines()
{
char input;
System.out.println ("Enter a letter from the word COMPUTERS");
input = In.getChar ();
switch (input)
{
case 'C':
String line = Files.readAllLines(Paths.get("foo.txt")).get(1);
case 'O':
String line = Files.readAllLines(Paths.get("foo.txt")).get(2);
System.out.println (line);
// Like wise for other characters.
}
}
This program writes lines to file. Then it asks user to enter a letter from word computers or enter q to exit. When user types letter like s it reads from file line that starts with S. If user types q the program stops. If user types unknown letter like w it prints null. Here is code:
package com.stackoverflow.dao;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.Scanner;
public class Lab_raminAmiri {
private static char input;
private static String fileName = "foo.txt";
public static void main(String[] args) throws IOException {
sendLines();
Scanner In = new Scanner(System.in);
RandomAccessFile fileReader = new RandomAccessFile(new File(fileName), "r");
System.out.println("Enter a letter from the word computers or q to exit");
String next = null;
while ((next = In.next()) != null && next.length() > 0) {
input = next.charAt(0);
if (!String.valueOf(input).equals("q")) {
String line = readLineStartingWith(input, fileReader);
System.out.println(input + ": " + line);
// make file-pointer point to begin of file
fileReader.seek(0);
} else {
break;
}
}
In.close();
fileReader.close();
} // main method
public static void sendLines() throws IOException {
FileWriter fw = new FileWriter(fileName);
PrintWriter pw = new PrintWriter(fw);
pw.println("Come to the lab on time.");
pw.println("Operate your computer properly.");
pw.println("Make sure to listen attentively.");
pw.println("Print only what is required.");
pw.println("Use the Net with respect.");
pw.println("Touch the keyboard gently.");
pw.println("Eat or drink outside the lab.");
pw.println("Remember to finish your assignment.");
pw.println("Shutdown the computer at the end of class.");
pw.close();
} // sendLines method
private static String readLineStartingWith(char firstLatter, RandomAccessFile fileReader) throws IOException {
String line;
while ((line = fileReader.readLine()) != null && line.length() > 0) {
String upperCase = String.valueOf(firstLatter).toUpperCase();
if (line.startsWith(upperCase))
return line;
}
return null;
}
}
This code does not make sense as you are reading the value, but not returning it
public static void userInputChar ()
{
char input;
System.out.println ("Enter a letter from the word COMPUTERS");
input = In.getChar ();
}
I am guessing that you want to use this value in your switch statment, so some thing needs to be returned like:
public static char userInputChar ()
{
char input;
System.out.println ("Enter a letter from the word COMPUTERS");
input = In.getChar ();
return input;
}
now that you have returned this value, keep it like:
char input = userInputChar ();
now pass it to your switch method
readLines (input);
change your method declaration
public static void readLines (char input)
now you can use it
while ((line = br.readLine ()) != null)
{
if (line.charAt(0) == input) {
{
System.out.println (line);
break;
}
}
// close files etc
edit
To make the above safer do,
if (line.length() > 0 && line.charAt(0) == input) {
{
System.out.println (line);
break;
}
I need a java program that ask a number between 0 and 2. If the user write 0, the program ends. If the user write 1, it executes one function. If the user write 2, it executes another function. I also want to handle the error "java.lang.NumberFormatException", with a message and in this case, ask again the user for a number, until he writes a number between 0 and 2
I use
public static void main(String[] args) throws IOException {
int number = 0;
boolean numberCorrect = false;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (numberCorrect == false){
System.out.println("Choose a number between 0 and 2");
String option = br.readLine();
number = Integer.parseInt(option);
try {
switch(option) {
case "0":
System.out.println("Program ends");
numberCorrect = true;
break;
case "1":
System.out.println("You choose "+option);
functionA();
numberCorrect = true;
break;
case "2":
System.out.println("You choose "+option);
functionB();
numberCorrect = true;
break;
default:
System.out.println("Incorrect option");
System.out.println("Try with a correct number");
numberCorrect = false;
}
}catch(NumberFormatException z) {
System.out.println("Try with a correct number");
numberCorrect = false;
}
}
}
But with this code the catch(NumberFormatException z) doesn't work and the program don't ask again for a number.
You never actually catch NumberFormatException here. Your code basically does:
while (...) {
// this can throw NumberFormatException
Integer.parseInt(...)
try {
// the code in here cannot
} catch (NumberFormatException e) {
// therefore this is never reached
}
}
What you want to do here is:
while (!numberCorrect) {
line = br.readLine();
try {
number = Integer.parseInt(line);
} catch (NumberFormatException ignored) {
continue;
}
// etc
}
You could put the try/catch around the parseInt like this:
while (numberCorrect == false){
System.out.println("Choose a number between 0 and 2");
String option = br.readLine();
try {
number = Integer.parseInt(option);
}catch(NumberFormatException z) {
System.out.println("Try with a correct number");
numberCorrect = false;
option = "-1";
}
switch(option) {
case "0":
System.out.println("Program ends");
numberCorrect = true;
break;
...
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();
}
}
}
When I try to run this and call this specific method, I get the NoSuchElementException. It worked fine before I changed it to an ArrayList instead of just reading/printing from file directly with Scanner.
Here is what it says when I choose option 2 [ArrayList]:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at version4.version4.readDisplay(version4.java:79)
at version4.version4.main(version4.java:27)
My code:
public class version4
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(System.in);
boolean exit = false;
while (!exit)
{
System.out.println("1 Find an item.\n2 Display all items.\n3 Update item.\n4 Save item to disk.\n5 Quit.");
int choice = in.nextInt();
switch (choice){
case 1: System.out.println("You chose to find an item from file."); findItem(); break;
case 2: System.out.println("You chose to display all items."); readDisplay(); break;
case 3: System.out.println("You chose to update an item."); itemUpdate(); break;
case 4: System.out.println("You chose to save an item to disk."); itemAdd(); break;
case 5: exit = true; break;
default: System.out.println("That is not a valid option."); break;
}
}
System.out.println("Goodbye.");
}
public static void readDisplay() throws FileNotFoundException
{
// Open input file:
System.out.println("Reading 'read_record.txt'");
FileReader reader = new FileReader("read_record.txt");
Scanner fin = new Scanner(reader);
String str = null;
ArrayList<String> dvdfile = new ArrayList<String>();
while((str = fin.next()) != null){
dvdfile.add(str);
}
Iterator iter = dvdfile.iterator();
while (iter.hasNext())
{
String sku = (String) iter.next();
String title = (String) iter.next();
String length = (String) iter.next();
System.out.printf("%-10s %-15s %10s %n",sku,title,length);
}
// Close file:
fin.close();
}
}
Anyone know whats causing the NoSuchElementException and/or how to fix?
There could be a few things going on... I'd try this
if (fin != null && fin.hasNext()) { // do we have a scanner, is there anything to read?
while (fin.hasNext()) { // while there's something to read...
str = fin.next(); // read it.
if (str == null) { // end if it's null?
break;
}
dvdfile.add(str); // otherwise add it.
}
}