For my team's programming project, we have a board game, where the user has various inputs at different stages.
When the user wants to quit in the middle of the game, we want the user to press Control+D (which throws the NoSuchElementException) which I want to propagate back to the main menu to allow the user to begin a new game without re-running the program.
I run into problems when I try to access any Scanner .next* methods - it throws the same exception with "No line found". As I read somewhere, the EOF makes hasNext* return false.
The EOF completely stops the Scanner, and any new Scanner from working, as I get the same problem. So, the EOF works exactly as I want it to, until we ask for more input from the user.
(I have done this in C successfully)
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
boolean run = true;
String str;
Scanner scan1 = new Scanner(System.in);
while (run)
{
try
{
System.out.println(scan1.hasNextLine());
str = scan1.nextLine();
System.out.println(str);
}
catch (Exception e)
{
System.out.println("Error");
//scan1.nextLine(); // this throws the "No line found"
run = false;
}
}
Scanner scan2 = new Scanner(System.in);
System.out.println(scan2.next()); // without scan1, this throws the "NoSuchElementException"
}
}
Any ideas on how to continue Scanning after we EOF?
Related
I'm trying to write a getInt() method, which abstracts the extraction of an integer from the console, to the rest of my program.
Inside, is a try using resource -- the resource being a scanner; with a catch block for the inevitable InputMismatchException.
It captures valid inputs, fine; and catches false inputs.
However, after -- recursively -- trying to again capture the input, my scanner instantly throws a NoSuchElementException, which is obviously linked to the last mismatch error.
Do I need to clear something in the second scanner, perhaps left from the first?
private static int getInt(String name) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.printf("Enter %s: ", name);
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid");
return getInt(name);
}
}
I already tried to instantiate the scanner out of the function, like so:
Scanner scanner = new Scanner(System.in);
getInt(scanner, name);
...
private static int getInt(Scanner scanner, String name) {
try {
System.out.printf("Enter %s: ", name);
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid");
return getInt(scanner, name);
}
}
Here, I simply get a stack over flow error, because the mismatch error recurs.
I have a java console application which checks for password. If the password is correct then and only then the application window should close. Otherwise if it is incorrect password , the application window should not close until and unless the correct password is entered. I am not able to find any right java keywords which would close application window if the correct password is entered.
Use System.exit():
public static void main(String[] args) {
while(true) {
// get password
if(passwordCorrect) {
System.exit(0);
}
}
}
Try this code:
import java.util.*;
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
String input = null;
do{
input = scn.nextLine();
if(input == "password"){
system.exit(0);
}
}
}
I have a java class where a user provides a file path and if the path doesn't exist I ask them to try again. My professor says we should use an exception to handle this.
Here is a snippet of how I'm currently doing it:
public class SalesUtil {
public static void processSales() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sales file name: ");
String salesFile = keyboard.nextLine();
try {
Scanner scanFile = new Scanner(new File(salesFile));
//do stuff
}
} catch(FileNotFoundException fnfe) {
System.out.println("Invalid file name supplied, please try again.");
processSales();
}
}
}
Well in the do stuff section, I'm calculating values and printing data to the console. If I enter the correct file name correctly on the first try all the data is correct. If it is incorrect one or more times the data is not correct.
I imagine this is because of adding function calls on top of my initial stack and never 'getting out' of the initial stack while supplying subsequent stack calls until the correct file is supplied?
I'm still new to java and would appreciate some tips in understanding how to solve this using an exception.
The FileNotFoundException is the correct one to catch, however I gather that you're worried about the stacks building up? I tested reading back the file after multiple failed attempts and it was fine. The recursive call is at the end of the method so it is the last line of code and therefore the stacks shouldn't have any effect.
However, if you want, you could use a while loop instead of recursion to avoid stack buildup:
public static void processSales() {
Scanner scanFile = null;
Scanner keyboard = new Scanner(System.in);
while (scanFile == null) {
System.out.println("Enter sales file name: ");
String salesFile = keyboard.nextLine();
try {
scanFile = new Scanner(new File(salesFile));
while (scanFile.hasNextLine()) {
System.out.println(scanFile.nextLine());
}
} catch(FileNotFoundException fnfe) {
System.out.println("Invalid file name supplied, please try again.");
}
}
}
use the file.exist() method to check, if that what you want to do is to make sure it exist then this is the codes:
File sfile = new File(salesFile);
if (sfile.exists()) {
// ok, file exist do something.
...
}
On the other hand, when you say "invalid file" could be anything, if it is bad filename, then it is another animal (well, different exeception)...
To use try/catch for a readonly file then:
try {
FileInputStream sfile = new FileInputStream(salesFile);
...
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
Original Question
For the following small code I'm getting the error...
import java.io.*;
class test
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i;
System.out.println("Enter no of processes ");
int no_of_process=Integer.parseInt(br.readLine());
int process[]=new int[no_of_process];
System.out.println("Enter the values");
for(i=0;i<no_of_process;i++)
process[i]=Integer.parseInt(br.readLine());
for(i=0;i<no_of_process;i++)
System.out.println(process[i]);
}
}
Input:
Enter no of processes
5
Enter the values
1
2
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at test.main(test.java:17)
Process completed.
I think I have written the code properly and proper integer input is also given. How do I get rid of the above error without using any explicit exception handling statements?
Further Question:
Thanks guys for your answers...it is working. But there is one new question in my mind.
I tried the following modification in the code and executed it. To my surprise, input was accepted properly without any run time error.
for(i=0;i<no_of_process;i++)
{
System.out.println(Write anything or even keep it blank);
process[i]=Integer.parseInt(br.readLine());
}
By adding just one Print statement before (or even after) the input statement in the for loop, my program worked correctly and no exception was thrown while giving input.
Can you guys explain the reason behind this?
Again if I remove the Print statement from there, the same error gets repeated. I am really confused about the reason behind this. Please help.
Without any error handling statements? check to see if br.readLine() is returning "" before you attempt to parse it, like so:
String line = br.readLine();
if(!String.isEmpty(line))
{
//Do stuff
}
else
{
//Do other stuff
}
How to get rid of above error without using any explicit exception handling statements?
for (i = 0; i < no_of_process; i++) {
String input;
do {
input = br.readLine();
if (isInteger(input)) {
process[i]=Integer.parseInt(input);
} else {
//error handling here
System.err.println("you entered an invalid input");
}
} while(isInteger(input));
}
And isIntegerlooks like this:
public static boolean isInteger(String s)
{
try {
Integer.parseInt(s);
}
catch (Exception e) {
return false;
}
return true;
}
I think I have written properly and proper integer input is also given.
I think not ;) i think you pressed the return with out typing anything
Try this:
import java.io.*;
public class test
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i;
System.out.println("Enter no of processes ");
try{
int no_of_process=Integer.parseInt(br.readLine());
int process[]=new int[no_of_process];
System.out.println("Enter the values");
for(i=0;i<no_of_process;i++)
process[i]=Integer.parseInt(br.readLine());
for(i=0;i<no_of_process;i++)
System.out.println(process[i]);
}
catch(NumberFormatException n)
{
System.out.println(n.getMessage());
}
}
}
I'm writing Java on Windows 7, and I want to be able to work with the input from the keyboard, which I can only presume is the standard input.
I've tried to use BufferedInput, System.in, and Scanner, but all of them require the program to pause and wait for an end of line or return! Is there anyway to just collect and record the data as it is used, and not have to wait for a return?
Here is a quick solution:
public static void main(String[] args) {
Thread inputThread = new Thread(new Runnable() {
#Override
public void run() {
Scanner scan = new Scanner(System.in);
String input = "";
while (true) {
System.out.println("Type something: ");
input = scan.nextLine();
System.out.println("Input: "+input);
}
}
});
inputThread.start();
while (true) {
System.out.println("");
System.out.println("test");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
The main thread prints "test" every second. And the inputThread asks the user to type something then prints what he wrote. It's just a "visual" solution, you certainly don't want to print something while the user is typing.