Issues with storing user input in txt.file [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I need help with the following code- essentially what I'm trying to do is continuously prompt user for numbers until they enter "Done" to finish, then prompts the user for a file name so that these values can be saved to that file. For example, if the user enters "output.txt", then the program should write the numbers that have been read to "output.txt".
This is what I have so far:
public static void main(String[] args) {
try{
FileWriter file= new FileWriter("filename.txt");
Scanner input= new Scanner(System.in);
boolean done= false;
do{
System.out.println("Enter a number");
String value= input.nextLine();
if (value.equalsIgnoreCase("done")){
done=true;
Scanner input1= new Scanner(System.in);
System.out.println("What is the filename?");
String filename1= input1.next();
FileWriter finalFile = new FileWriter(filename1);
} else {
try{
double number= Double.parseDouble(value);
file.write(number+ "\n");
file.flush();
}
catch (NumberFormatException fnfe) {
System.out.println("Not valid");
}
}
} while(!done);
input.close();
file.close();
System.out.println("Success");
}
catch (IOException ioe){
System.out.println(ioe.toString());
}
}
}
the code below outputs two files, one text file (filename.txt) and the other that is appropriately named by the user. How can I fix this? There should only be one output.
Any advice would be much appreciated!

You could...
Store the values been entered by the user in some kind of list. Since the number of values been entered is arbitrary, you'll probably need to use something like an ArrayList, as it provides a dynamic size
Scanner input = new Scanner(System.in);
List<Double> numbers = new ArrayList<Double>(25);
boolean done = false;
do {
System.out.println("Enter a number");
String value = input.nextLine();
done = value.equalsIgnoreCase("done");
if (!done) {
try {
double number = Double.parseDouble(value);
numbers.add(number);
} catch (NumberFormatException fnfe) {
System.out.println("Not valid");
}
}
} while (!done);
System.out.println("What is the filename?");
String filename1 = input.nextLine();
try (BufferedWriter finalFile = new BufferedWriter(new FileWriter(filename1))) {
for (double number : numbers) {
finalFile.write(Double.toString(number));
finalFile.newLine();
}
} catch (IOException ex) {
ex.printStackTrace();
}
Or you could...
If you're unable to use a List of some kind, you will need to prompt the user for the file name first and then write the values out as they entered...
Scanner input = new Scanner(System.in);
System.out.println("What is the filename?");
String filename1 = input.nextLine();
try (BufferedWriter finalFile = new BufferedWriter(new FileWriter(filename1))) {
boolean done = false;
do {
System.out.println("Enter a number");
String value = input.nextLine();
done = value.equalsIgnoreCase("done");
if (!done) {
try {
double number = Double.parseDouble(value);
finalFile.write(Double.toString(number));
finalFile.newLine();
} catch (NumberFormatException fnfe) {
System.out.println("Not valid");
}
}
} while (!done);
} catch (IOException ex) {
ex.printStackTrace();
}

What your code does: Create a FileWriter for file "filename.txt" and add the numbers entered by the user. When the user enters done in the command line ask him for the filename and create a new FileWriterfor that file, but dont write anything to it. Then close the first FileWriter.
What you want: Query the user for values, store them somehow, ask for the file location, save the values to the file location.
This should do the job:
try (Scanner input = new Scanner(System.in))
{
List<Double> numbers = new ArrayList<>();
// Query user for numbers.
boolean done = false;
do
{
System.out.println("Enter a number: ");
String value = input.nextLine();
if (value.equalsIgnoreCase("done"))
{
done = true;
}
else
{
try
{
double number = Double.parseDouble(value);
numbers.add(number);
}
catch (NumberFormatException fnfe)
{
System.out.println("Not valid");
}
}
}
while (!done);
// Prompt the user for the file name. If the user just presses enter, reprompt >:-(
String fileName;
do
{
System.out.println("Specify a filename: ");
fileName = input.nextLine();
}
while (fileName.isEmpty());
try (PrintStream ps = new PrintStream(fileName))
{
for (Double number : numbers)
{
ps.print(number);
ps.println();
}
}
System.out.println("Success");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}

Related

NoSuchElementException Problem in User Input Java

I'm confused while using an Java program I created.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
System.out.println("Your first input is " + input1);
}
Initially, when a user Ctrl+D during the input, it will promptly end the program and display an error in the form of this,
Your first input integer? ^D
Class transformation time: 0.0073103s for 244 classes or 2.9960245901639343E-5s per class
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651);
at Playground.Test1.main(Test1.java:13)
Doing a bit of research I note that Ctrl+D terminates the input of sort. Therefore, I tried add few more lines to my codes to prevent the error from appearing again and instead printing a simple "Console has been terminated successfully!" and as far as my skills can go.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
catch (NoSuchElementException e) {
System.out.println("Console has been terminated successfully!");
}
}
System.out.println("Your first input is " + input1);
}
In the end, I still got the same error.
Got it!, the code hasNext() will ensure that the error will not appear. This method is to check whether there is another line in the input of the scanner and to check if its filled or empty. I am also using null to check my statement after passing the loop so the program stops if the input value is still null while keeping the function of Ctrl+D.
public static void main(String[] args) {
Integer input1 = null;
System.out.println("Your first input integer? ");
Scanner scanner1 = new Scanner(System.in);
while(scanner1.hasNextLine()) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
break;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.println("Your first input integer? ");
}
}
if (input1 == null) {
System.out.println("Console has been terminated successfully!");
System.exit(0);
}
System.out.println(input1);
}
This solution is not prefect of course but I would appreciate if there were much simpler options.

Java problem with Scanner input and try {/// } finally {input.close();}

Java newbie here... I want to scan some user input after a button is pressed. The first thing that I scan from keyboard works fine but in the second input the programm crashes. I believe the problem is with the second use of try{//blocks of code}finally{input. close();} (same code though). I used it so I can get out of the scanning process. I need your sights. Thx for the help. Here is my code:
#Override
public void action Performed(Action Event e) {
if(e.getSource()==button1){
System.out.println("Sth");
label1.setVisible(true);
Scanner input = new Scanner(System.in);
try {
String userInput = "";
System.out.println("Asking the user a q, (yes/no)");
userInput = input.nextLine();
if(userInput.equalsIgnoreCase("yes")) {
System.out.println("Okay");
int Temp = input.nextInt();
System.out.println("Print the scanned value");
input.close();
}else if(userInput.equalsIgnoreCase("no")) {
System.out.println("Default answer to q");
}
}finally{
input.close();
}
} else if(e.getSource()==button2){
System.out.println("Sth");
label2.setVisible(true);
Scanner input = new Scanner(System.in);
try {
String userInput = "";
System.out.println("Q for user, (yes/no)");
userInput = input.nextLine();
if(userInput.equalsIgnoreCase("yes")) {
System.out.println("Sth");
int Time = input.nextInt();
System.out.println("" + Time + "");
input.close();
}else if(userInput.equalsIgnoreCase("no")) {
System.out.println("Okay");
}
}finally{
input.close();
}
}
}

Java, while infinite loop when using scanner

I want to ask the user to enter a String, and four integer values, and i want the program to keep asking the user for integer value if the user input a type mismatch, why the code keep looping forever and never wait for the user input if the user inserted a wrong type ?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sessionName;
int pomoInterv, breakInterv, terminalBreakInterv;
System.out.println("Please, Enter the session name: ");
sessionName = scanner.nextLine();
while (true) {
try {
System.out.println("Please, Enter the Pomodoro interval: ");
pomoInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
}
}
while (true) {
try {
System.out.println("Please, Enter the break interval: ");
breakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
}
}
while (true){
try {
System.out.println("Please, Enter the terminal break interval ");
terminalBreakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
}
}
System.out.println("Done!");
System.out.println(sessionName);
System.out.println(pomoInterv);
System.out.println(breakInterv);
System.out.println(terminalBreakInterv);
}
}
According to scanner oracle docs :
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
So when you entered anything other than an integer, the scanner.nextInt() will not parse it to integer and throw InputMismatchException and the scanner will not move to the next token and tried to read again and again the same token.
To solve this, you can either change the loop or use hasNextInt() method or use scanner.next() in the catch block so that the scanner can move to the next token.
I always use do-while loop when checking for correct Input from the user.
See if the following works:
Scanner scanner = new Scanner(System.in);
String sessionName;
int pomoInterv = -1, breakInterv = -1, terminalBreakInterv = -1;
System.out.println("Please, Enter the session name: ");
sessionName = scanner.nextLine();
boolean isPomoInterv = false;
do {
System.out.println("Please, Enter the Pomodoro interval: ");
String temp = scanner.nextLine();
try {
if (Integer.parseInt(temp) > 0) {
pomoInterv = Integer.parseInt(temp);
isPomoInterv = true;
}
} catch (NumberFormatException e) {
System.out.println("Try again");
}
} while (!isPomoInterv);
boolean isBreakInterv = false;
do {
System.out.println("Please, Enter the break interval: ");
String temp = scanner.nextLine();
try {
if (Integer.parseInt(temp) > 0) {
breakInterv = Integer.parseInt(temp);
isBreakInterv = true;
}
} catch (NumberFormatException e) {
System.out.println("Try again");
}
} while (!isBreakInterv);
boolean isTerminalBreakInterv = false;
do {
System.out.println("Please, Enter the terminal break interval ");
String temp = scanner.nextLine();
try {
if (Integer.parseInt(temp) > 0) {
terminalBreakInterv = Integer.parseInt(temp);
isTerminalBreakInterv = true;
}
} catch (NumberFormatException e) {
System.out.println("Try again");
}
} while (!isTerminalBreakInterv);
System.out.println("Done!");
System.out.println(sessionName);
System.out.println(pomoInterv);
System.out.println(breakInterv);
System.out.println(terminalBreakInterv);
The comment on your question by scary-wombat is correct. i have used his comment to code the above.
I actually solved it, i just had to add a (scanner.next();) in the catch statement as below, it's because how the Scanner class works, see the code below,
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sessionName;
int pomoInterv, breakInterv, terminalBreakInterv;
System.out.println("Please, Enter the session name: ");
sessionName = scanner.nextLine();
while (true) {
try {
System.out.println("Please, Enter the Pomodoro interval: ");
pomoInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
scanner.next();
System.out.println(ex.getMessage());
}
}
while (true) {
try {
System.out.println("Please, Enter the break interval: ");
breakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
scanner.next();
System.out.println(ex.getMessage());
}
}
while (true){
try {
System.out.println("Please, Enter the terminal break interval ");
terminalBreakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
scanner.next();
System.out.println(ex.getMessage());
}
}
System.out.println("Done!");
System.out.println(sessionName);
System.out.println(pomoInterv);
System.out.println(breakInterv);
System.out.println(terminalBreakInterv);
}
}
check this answer
https://stackoverflow.com/a/47852703/12565862
Because you don't have a break; in catch block. When there is exception, you print the message. But once it comes out of catch block, while loop still satisfies its condition and execute again. Try adding break; inside catch block too.

Why is my PrintWriter class not working as expected?

I have this application which prompts the user for a text file for input, from this text file, it contains strings of integers and text. And from there, it supposed to write to another text file, result.txt. Right now, as I'm still new to IO I am having problems with writing to the file although the file successfully created. The application stops right at the part after the user inputs the text file's name. So could you guys give me some help on that please? Thanks in advance!
import java.util.*;
import java.io.*;
class FileReadingExercise3 {
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do
{
try
{
System.out.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if(a.equals("QUIT"))
{
System.exit(0);
}
fileInput = new Scanner(new File(a));
}
catch(FileNotFoundException e)
{
System.out.println("Error " + a + " does not exist.");
}
}while(fileInput == null);
PrintWriter output = null;
try
{
output = new PrintWriter(new File("result.txt"));
}
catch(IOException g)
{
System.out.println("Error");
System.exit(0);
}
while(fileInput.hasNext())
{
if(fileInput.hasNextInt())
{
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
}
}
fileInput.close();
output.close();
}
}
It is stuck because you have to call the next() method after calling hasNext()so the pointer goes to next line of your input file.
Also you are not using sum so check if you need this variable.
Here is the code that works:
public static void main(String[] args) throws FileNotFoundException {
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do {
try {
System.out
.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if (a.equals("QUIT")) {
System.exit(0);
}
fileInput = new Scanner(new File(a));
} catch (FileNotFoundException e) {
System.out.println("Error " + a + " does not exist.");
}
} while (fileInput == null);
PrintWriter output = null;
try {
output = new PrintWriter(new File("result.txt"));
} catch (IOException g) {
System.out.println("Error");
System.exit(0);
}
while (fileInput.hasNext()) {
if (fileInput.hasNextInt()) {
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
} else {
fileInput.next();
}
}
fileInput.close();
output.close();
}
}
Update:
As per java doc for Scanner.hasNext() method:
Returns true if this scanner has another token in its input. This
method may block while waiting for input to scan. The scanner does not
advance past any input.
So to go to the next position, you need to call the next() method, otherwise the Scanner will be at same position and the program gets stuck in infinite loop.

Using exception handling to get a correct file input

I'm trying to use a try{} catch{} to get a correct file input from the user, however I don't know how to keep asking for input until I get a valid file. I can't use an if statement, this is what I have so far. The file is filled with integers, and it applies to another method. I have FileReader to make sure the file exists, if it doesn't it should throw an exception.
public static int readFilename() {
Scanner scan = new Scanner(System.in);
String input;
int average = 0;
try{
System.out.print("Enter a filename: ");
input = scan.next();
FileReader read = new FileReader(input);
average = AverageFile.average(input);
}
catch(FileNotFoundException e){
System.out.println("Incorrect file input");
}
return average;
}
try this
public static int readFilename() {
Scanner scan = new Scanner(System.in);
String input;
int average = 0;
boolean flag= true;
while(flag)
{
try{
System.out.print("Enter a filename: ");
input = scan.next();
FileReader read = new FileReader(input);
average = AverageFile.average(input);
flag= false;
}
catch(FileNotFoundException e){
System.out.println("Incorrect file input");
}
}
return average;
}

Categories

Resources