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;
}
Related
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.
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();
}
I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
Thanks for your time!
Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue.
Try this:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
Shorter solution. Just take input in sc.next()
public int getInt(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
while (!sc.hasNextInt()) {
System.out.println("Enter a whole number");
sc.next();
}
return sc.nextInt();
}
Working on Juned's code, I was able to make it shorter.
int getInt(String prompt) {
System.out.print(prompt);
while(true){
try {
return Integer.parseInt(new Scanner(System.in).next());
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n"+prompt);
}
}
}
Keep gently scanning while you still have input, and check if it's indeed integer, as you need:
String s = "This is not yet number 10";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
while (scanner.hasNext()) {
// if the next is a Int,
// print found and the Int
if (scanner.hasNextInt()) {
System.out.println("Found Int value :"
+ scanner.nextInt());
}
// if no Int is found,
// print "Not Found:" and the token
else {
System.out.println("Not found Int value :"
+ scanner.next());
}
}
scanner.close();
As an alternative, if it is just a single digit integer [0-9], then you can check its ASCII code. It should be between 48-57 to be an integer.
Building up on Juned's code, you can replace try block with an if condition:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
System.out.println("Correct input, exit");
break;
}
System.out.println("Input is not a number, continue");
}
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.
public class Main {
public static void main(String[] args)
{
int ch = 0;
do
{
Scanner in = new Scanner(System.in);
String s;
System.out.println("Enter the part number");
s=in.nextLine();
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Ankit\\Documents\\NetBeansProjects\\tcs_1\\number.txt"));
BufferedReader Br = new BufferedReader(new FileReader("C:\\Users\\Ankit\\Documents\\NetBeansProjects\\tcs_1\\number1.txt"));
String strLine;
int flag=0;
while ((strLine = br.readLine()) != null)
{
if(strLine.equals(s))
{
flag=1;
System.out.println ("Part Number exists in 1");
break;
}
else
{
flag=0;
System.out.println ("Part Number doesnot exist in 1");
break;
}
}
if(flag==0)
{
while ((strLine = Br.readLine()) != null)
{
if(strLine.equals(s))
{
System.out.println ("Part Number exists in 2");
break;
}
else
{
System.out.println("File does not exist in 2");
break;
}
}
}
System.out.println ("Do you want to continue-Press1 for yes and 2 for no");
ch= in.nextInt();
br.close();
Br.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
while(ch==1);
}
}
this is the program that I made to search a user given string from 2 diff text files. Its working fine but only searching the first line.
eg.: If a file has
1000
1001
1002
it wll only search 1000. How do I go to next line and keep on using the .equals() method?
You should use Scanner not BufferedReader as it's a more recent class
and I feel does a nicer job with this task. Especially since you have
already used Scanner elsewhere in your code and thus imported it.
Below is a scanner that will read all the lines in a file while there
is a next one to read.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class JavaApplication32
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Scanner scanner1 = null;
Scanner scanner2 = null;
String partCheck;
String repeatLoop;
boolean isInOne;
boolean isInTwo;
File file1 = new File("data1.txt");
File file2 = new File("data2.txt");
try
{
scanner1 = new Scanner(file1);
scanner2 = new Scanner(file2);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
do
{
isInOne = false;
isInTwo = false;
System.out.println("Enter the part number");
partCheck = keyboard.nextLine();
while (scanner1.hasNextLine() && !isInOne)
{
String line = scanner1.nextLine();
if(line.equals(partCheck))
{
System.out.println("Part Number exists in 1");
isInOne = true;
}
}
if(!isInOne)
{
System.out.println("Part Number does not exist in 1");
}
while(scanner2.hasNextLine() && !isInOne && !isInTwo)
{
String line = scanner2.nextLine();
if(line.equals(partCheck))
{
System.out.println("Part Number exists in 2");
isInTwo = true;
}
}
if(!isInTwo)
{
System.out.println("Part Number does not exist in 2");
}
System.out.println("Do you want to continue? (Y/N)");
repeatLoop = keyboard.nextLine();
} while(repeatLoop.equalsIgnoreCase("y"));
scanner1.close();
scanner2.close();
}
}
Example Text File data1.txt:
Test1
Test2
Test3
Test4
Example Test File data2.txt
Check1
Check2
Check3
Check4
Example stdout when code is run with these datafiles:
run:
Enter the part number
Test1
Part Number exists in 1
Part Number does not exist in 2
Do you want to continue? (Y/N)
y
Enter the part number
Check1
Part Number does not exist in 1
Part Number exists in 2
Do you want to continue? (Y/N)
n
BUILD SUCCESSFUL (total time: 19 seconds)
You also shouldn't put all of your read in information in a loop. By
putting do at the top you effectively keep creating a new set of
BufferedReaders and naming them the same thing and telling to do the
same thing and then telling them to break after the first hit. If you
did actually get rid of the break you'd have even more problems since
all of this other stuff is in the loop where it shouldn't be.
Since you have used
break;
in while loop it will exit from the loop after check first line. Try removing break; if you want to read all lines.