How to avoid Scanner from eof and keep him alive - java

could you tell me is there any solution to keep Scanner alive after ctrl+d (eof)?
I have this
static public int getInt(String errorText){
Scanner scan = new Scanner(System.in);
while (!scan.hasNextInt()){
scan.next();
System.out.println(errorText);
}
return scan.nextInt();
}
And after ctrl+d i get NoSuchElementException
Then i try to section try-catch
static public int getInt(String errorText){
Scanner scan = new Scanner(System.in);
while (!scan.hasNextInt() ){
try{
scan.next();
}catch(NoSuchElementException e){
System.out.println("PrechwyciƂem!");
}
System.out.println(errorText);
}
return scan.nextInt();
}
and after that i get infinity loop

Related

Sanitizing user input in Java, correcting mistakes [duplicate]

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");
}

Scanner throws InputMismatchException with null

import java.io.*;
import java.util.*;
public class Main{
public static void main(String [] args) throws InputMismatchException{
double width;
int period;
double Ppp;
Scanner in0 = new Scanner(System.in);
Scanner in1 = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
System.out.println("Give width\n");
while(in0.hasNextDouble()){
width = in0.nextDouble();
}
in0.close();
System.out.println("\n");
System.out.println("Give period");
while(in1.hasNextInt()){
period = in1.nextInt();
}
in1.close();
System.out.println("\n");
System.out.println("Insert width peak to peak");
while(in2.hasNextDouble()){
Ppp = in2.nextDouble();
}
in2.close();
}
I run this code block
I insert the first input but it displays null for each input
and then it crash
May someone run it and tell if he has the same problem
I use BlueJ compiler
The cause of the problem is this
Scanner in0 = new Scanner(System.in);
Scanner in1 = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
and this
in0.close();
...
in1.close();
...
in2.close();
When you create the Scanner, you work on System.in, then you close it. This cause that next Scanner operate on closed stream.
The solution is to create a single Scanner for InputStream.
Scanner scanner = new Scanner(System.in);
System.out.println("Give width\n");
double width = scanner.nextDouble();
System.out.println("Give period");
int period = scanner.nextInt();
System.out.println("\nInsert width peak to peak:");
double p2p = scanner.nextDouble();
This is only example that do not validate the user input.
public static void main(String [] args) throws InputMismatchException{
double width;
int period;
double Ppp;
Scanner in0 = new Scanner(System.in);
System.out.println("Give width\n");
// This will read the line, and parse the result as a double, this way you can insert a number and press enter
width = Double.parseDouble(in0.nextLine());
System.out.println("Give period");
period = Integer.parseInt(in0.nextLine());
System.out.println("\n");
System.out.println("Insert width peak to peak:");
ppp = Double.parseDouble(in0.nextLine());
in0.close();
}

Error while returning integer instead of Scanner.NextInt()

I'm writing a menu-driven Java program to implement a Vigenere Cipher.
For the menu function, I wrote the following code:
public static int printmenu(){
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to the Vigenere Cipher!");
System.out.println("What would you like to do?");
System.out.println("1.Encrypt a message");
System.out.println("2.Decrypt a message");
System.out.println("Enter your choice:");
return scan.nextInt();
}
Now this does the job correctly, but I was criticized by my professor for not closing my scanner class object "scan".
So, I made the following edit to my code:
public static int printmenu(){
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to the Vigenere Cipher!");
System.out.println("What would you like to do?");
System.out.println("1.Encrypt a message");
System.out.println("2.Decrypt a message");
System.out.println("Enter your choice:");
a = scan.nextInt();
scan.close();
return a;
}
This, however, returns the following error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at vigenere.Ciphermain.main(Ciphermain.java:30)
I don't understand what I'm doing wrong. Can anyone help me?
Edit: Here is the source code for the Ciphermain class:
public class Ciphermain extends JFrame{
public static int printmenu(){
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to the Vigenere Cipher!");
System.out.println("What would you like to do?");
System.out.println("1.Encrypt a message");
System.out.println("2.Decrypt a message");
System.out.println("Enter your choice:");
a = scan.nextInt();
scan.close();
return a;
}
public static void main(String[] args) {
String message, key;
int choice;
choice = printmenu();
Scanner scan = new Scanner(System.in);
if(choice == 1){
System.out.println("Enter the message to be encrypted:");
message = scan.nextLine();
System.out.println("Enter the secret key:");
key = scan.next();
Cipher ciph = new Cipher(key);
System.out.println("Encrypted message is: " + ciph.encrypt(message));
}
else{
System.out.println("Enter the message to be decrypted:");
message = scan.nextLine();
System.out.println("Enter the secret key:");
key = scan.next();
Cipher ciph = new Cipher(key);
System.out.println("Decrypted message is: " + ciph.decrypt(message));
}
scan.close();
}
}
Closing scanner will close underlying stream (System.in). So next time you create scanner on System.in which is closed, you will get such exception.
Create scanner at start of program, use it everywhere and close it at end of program.
Like:
static Scanner scan;
static int displayMenu(){
// display menu.
return scan.nextInt();
}
public static void main(String [] args){
scan = new Scanner(System.in);
// start work.
// end of work.
scan.close();
}
Check this: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()

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;
}

Prevent input error

import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int x = keyboard.nextInt();
}
}
How do I loop a piece of code like the one above until an int is entered instead of giving an error when a non-int is entered?
The Scanner class has a lot of stuff built in so that you don't need to do try-catches unless you are explicitly looking to catch the errors.
public static int test(){
int number = 0;
Scanner input = new Scanner(System.in);
boolean valid = false;
do{
System.out.print("Please enter an integer: ");
if(input.hasNextInt()){ // This checks to see if the next input is a valid **int**
number = input.nextInt();
valid = true;
}
else{
System.out.print("Not a valid integer!\n");
input.next();
}
}while(valid == false);
return number;
}
This tries to run the scanner, if a input is one that is not expected it will simply restart. You can add a message to it, my code was for brevity.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
try {
int x = keyboard.nextInt();
}
catch (java.util.InputMismatchException e) {
main(null);
}
}
}

Categories

Resources