+ 2
Scanner - input limitation - preventing errors.
Hello I ran into a problem in JAVA... I wrote a program, that lets me choose a value from array of strings... Inputting a number between 1-6 calls and prints the value from array on the screen I would like to prevent errors when user enters a wrong symbol, string or a number that exceeds 1-6... How to do that?? I tried various ways found on the web, but can't implement this myself... I don't want to copy paste - I am trying to understand handling of Scanner and conditional loops. I managed to prevent from entering a wrong data type like letters, but fail to add a condition lets say (value > 1 && value < 0) inside a loop. Here is the link to my working code: https://code.sololearn.com/cDRAx2IOxM2H/#java
35 Antworten
+ 1
Second try:
https://code.sololearn.com/cOFVVEPtrdBS/#java
In this case because of the do/while loop everything would be an error here... so i used all exception catch to prevent this.
+ 4
Mr. Wells, I modified your code a little, added a do..while loop in attempt to help @Bartlomiej Bugala, but I couldn't verify the code validity because input request in loop is prohibited/unsupported in Code Playground, and I don't have local Java IDE, could you test the loop in IDE, if you happen to have one?
Here's the modified code:
https://code.sololearn.com/c4UKqynBFaaD/?ref=app
+ 3
There are two ways to do this: exceptions or string line read. I tend to use exceptions because the code is simpler.
public static int inputSecrets() {
try {
System.out.println("Choose secret from 1 to 6");
input = new Scanner(System.in);
x = input.nextInt();
if (x < 1 || x > 6)
x = 0;
} catch(Exception e)
x = 0;
return x;
}
You would test for 0 in the caller and display an error message.
+ 3
@Bartlomiej Bugala, well I'm glad you finally sort things out, anyway, on curiosity, what error did Eclipse give on the modified code? I'd like to know, just for a lesson, future reference :)
+ 3
Okay mate, c u later...
+ 3
BLB, calm down... look, just make a small list summarizing what needs to be solved, make priorities on the list, and include steps you have taken to try to solve, and grab a drink, fluids will cool your overheating processor ;)
Post the list here later, so others can see it too, maybe someone with better knowledgeable have something to say too, okay?
Cheers!
+ 3
@BLB woah, glad you finally made it! that's great mate, I'm keeping your code for reference in my code storage, don't worry, I keep it private, credits all yours 8-)
+ 3
@BLB thanks mate, well we're all learning here, it may not be perfect now, but I guess it's a good start, and you can still enhance it as you go :D
+ 2
Sorry I forgot the {} are required. Still learning Java and used C++ syntax. I updated your code here (left private so hopefully you can access it)
https://code.sololearn.com/cQdVXpGvYME7/?ref=app
+ 2
https://code.sololearn.com/cpgSHCNQE68L/#java
Here is the best solution I could come up with:
/*
* @author BLB - Bartek
*
* Here is the perfected code for Scanner input verification
*
* The required input is an integer from 1 to 6
*
* TO CHECK IF IT WORKS INPUT some values like f (enter) 23 (enter) etc. between 1-6
* LAST input must be an integer between 1-6
*
*/
import java.util.Scanner;
public class Secrets {
static int x;
private static Scanner input;
public static void main(String[] args) {
Secrets secret = new Secrets();
inputSecrets();
secret.chooseSecrets();
}
public static int inputSecrets() {
boolean checkTrue = false;
System.out.println("Choose a secret word between 1-6");
input = new Scanner(System.in);
int check = 0;
while(!checkTrue) {
if(input.hasNextInt()) {
check = input.nextInt();
if(check >= 1 && check <= 6) {
checkTrue = true;
x = check;
break;
}
else {
System.out.println("Choose a valid integer between 1-6");
input.nextLine();
}
}
else {
System.out.println("Wrong input, please choose a number between 1-6");
input.nextLine();
}
}
return x;
}
public void chooseSecrets() {
String[] secretsArr;
secretsArr = new String[6];
secretsArr[0] = "1 ALPHA";
secretsArr[1] = "2 BETA";
secretsArr[2] = "3 GAMMA";
secretsArr[3] = "4 DELTA";
secretsArr[4] = "5 EPSILON";
secretsArr[5] = "6 OMEGA";
String actualSecret = secretsArr[x-1];
System.out.println(actualSecret);
}
}
+ 2
@Bartlomiej Bugala, okay, glad to know, well maybe we should just seek more info about Scanner object then. I'll look into cooperating your method with my idea later, maybe we can work something out..
+ 2
What's with input.hasNextInt? I thought it would be the filter for invalid input? I mean, it returns true if the input is an integer right?
+ 1
try something like this:
your inputFunction
get input
create a variable to store a match and set it to false.
check with a for loop equality with every element of the array.
if equality is found set the match variable to true.
if match is true go on with your program
else call inputFuncion again(recursion until a valid input is typed)
+ 1
@John Wells thanks for your time and efford.
I guess, this might work when applied correctly, but
I am not sure if it is what I am looking for, because I can't get it to work...
But I am still working on it....
@seamiki thanks, but - I am not trying to check the outcome (value) I am checking the scanner input... array is beeing checked after the valid scanner input was entered... and actually it is the index of the array... that is adressed and later on the value should pop up.
+ 1
@Ipang I checked it on eclipse - does not work... However I managed to find a solution.... Still not perfect because I can't fix empty enters now :) But it does not go into errors, just in my ide if i press multiple enters and then a wrong input it prints as many wrong input messages as I put in enters... But on Sololearn it worked fine putting multiple inputs at once. However - I would like to go with the try + loop - I just found a simpler (for me) workaround. The main issue was not checking < or > with the variable... but directly with the "scan" - that was my biggest problem. :) But do not give up... I would like to finaly get this done with try / catch in a loop.... I will post my solution when I make the code cleaner....
+ 1
I will try to do that tomorrow. But don't give up on that idea I think it can be corrected.
+ 1
Ipang I am affraid it is not perfect (because John made a great point) it was designed in eclipse, and I don't have input problems there... But The main problem I had was solved...
+ 1
@Ipang you can use it!! You can upgrade it or do whatever you wish with it. :) It's not a commercial banking app ;) Just a fragment of code.
0
@John Wells. Thank you John! This was not the full solution to my problem, but it solves the main problem - I was trying to check the condition on the Scanner input directly, where it needs to be set to a variable obviously!!! Now I still need to figure out a loop which does not terminate the program until the user gets the right input.
0
@Ipang - Hello I checked the code in eclipse again... And no errors where showing!
Just the functionality is not exactly what I was hoping for
after input of a string or char... it stops, where it should continue... and wait for input... I achieved that... Now I am working on achieving empty input message if you press enter without anything - that seems the hardest part now.