Need help modifying code for input validation and error message - java

Need some help with my code. I'm trying to modify written code to ask a user for "yes" or "no" in order for the loop to continue. I'm supposed to use a prime read and a while loop to display an error message if the user inputs anything other than "yes" or "no".
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//declare local variables
String endProgram = "no";
boolean inputValid;
while (endProgram.equals("no")) {
resetVariables();
number = getNumber();
totalScores = getScores(totalScores, number, score, counter);
averageScores = getAverage(totalScores, number, averageScores);
printAverage(averageScores);
do {
System.out.println("Do you want to end the program? Please enter yes or no: ");
input.next();
if (input.hasNext("yes") || input.hasNext("no")) {
endProgram = input.next();
} else {
System.out.println("That is an invalid input!");
}
}
while (!(input.hasNext("yes")) || !(input.hasNext("no")));
}
}

The hasNext method call doesn't take any parameters. Have a look at the docs.
Therefore you should get the value of the input first:
String response = input.next();
And then test the response:
!response.equalsIgnoreCase('yes') || !response.equalsIgnoreCase('no')
You could put this test into a method as you are checking the same thing multiple times.
It may be easier to see the logic of your program by changing endProgram to a boolean. Perhaps even rename it to running;
boolean running = true;
...
while (running) {
...
String response;
boolean validResponse = false;
while (!validResponse) {
System.out.println("Do you want to end the program? Please enter yes or no: ");
response = input.next();
running = isContinueResponse(response);
validResponse = isValidResponse(response);
if (!validResponse) System.out.println("That is an invalid input!");
}
}

Related

JAVA scanner causes if statement problems when using bag

I am new to JAVA and have been using IDE, to cut it short whenever I try to check if bag contains a string thats the same as the given input JAVA counts it as FALSE, even if the if statements such as "is input equal to 1" and "is 1 inside the bag" pass as true. here is an excerpt from my code, I would appreciate any help and advice.
//user input
System.out.println("Please enter a string (to exit, enter 'exit'): ");
a=sc.next();
if (a.equals("1")) {System.out.println("adpkgnosıfbgojadnofabsndofgna");}
if (ValidAnswers1.contains("1")) {System.out.println("adpkgnosıfbgojadnofabsndofgna");}
//error detection. after I learn bag it will become if bag contains string s.
if (ValidAnswers1.contains(a)) {correct_input=1;} else {correct_input=0;}
while (correct_input==0)
{
System.out.println("you entered:"+ a+".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
a = sc.next();
if (ValidAnswers1.contains(a)) {correct_input=1;} else {correct_input=0;}
}
the console prints out both the keymashes and then diverts into the while loop. I have checked to make sure the while loop is correct by testing with fixed variables, but when scanner is used it seems to have an error.
I didn't understand, what you really want, i did the test and a yet is working fine. take a look at the class, maybe is some error in the variables or something
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String a;
String ValidAnswers1 = "1";
int correct_input = 0;
//user input
System.out.println("Please enter a string (to exit, enter 'exit'): ");
a = sc.next();
if (a.equals("1")) {
System.out.println("adpkgnosıfbgojadnofabsndofgna");
}
if (ValidAnswers1.contains("1")) {
System.out.println("adpkgnosıfbgojadnofabsndofgna");
}
//error detection. after I learn bag it will become if bag contains string s.
if (ValidAnswers1.contains(a)) {
correct_input=1;
} else {
correct_input=0;
}
while (correct_input==0) {
System.out.println("you entered:"+ a+".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
a = sc.next();
if (ValidAnswers1.contains(a)) {
correct_input=1;
} else {
correct_input=0;
}
}
}
Here is the output:
Please enter a string (to exit, enter 'exit'):
a
adpkgnos?fbgojadnofabsndofgna
you entered:a.
Please enter a valid string (to exit, enter 'exit')
1
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
//Create a new Object Scan in the memmory
Scanner scan = new Scanner(System.in);
String input;
String[] validAnswers = new String[]{"1","2","3","exit"};
boolean isCorrect = false;
//The method equalsIgnoreCase means that the text can be in uppercase too;
/*The number between the tags "[]" means the number in the array since arrays
starts with number "0" */
do{
System.out.println("Please enter a string (to exit, enter 'exit'): ");
input = scan.next();
if(input.equalsIgnoreCase(validAnswers[0])){
isCorrect = true;
System.out.println("Number 1");
}else if(input.equalsIgnoreCase(validAnswers[1])){
isCorrect = true;
System.out.println("Number 2");
}else if(input.equalsIgnoreCase(validAnswers[2])){
isCorrect = true;
System.out.println("Number 3");
}else if(input.equalsIgnoreCase(validAnswers[3])){
isCorrect = true;
System.out.println("EXIT!");
//You could use the method System.exit(0) to finish the program;
//If you put "1" in the exit value means that the prgram finished with some error;
//System.exit(0);
}else{
//If the Answers is different from all of the others;
System.out.println("you entered: " + input +".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
}
}while(isCorrect != true);
//I used the method do{}while because it's the only method that will exacute at least once;
}

java : how can i use if correctly

I recently started java programming
but I have a problem
i want to write a program. I have a password, I ask the user of the program to enter the password
I want: if the person entered a string, I tell him that please don't enter string
and if the password was right and the type of the password that he entered(int) was right, I tell him OK.
in the test of the program, my problem is that when I entered a wrong password and expect that the program tell me that the pass is wrong, the program just tell me nothing !!
here is my code :
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt() && password.nextInt()==pass)
{
System.out.println("ok");
}
else if (password.hasNextInt())
{
System.out.println("wrong pass");
}
else
{
System.out.println("wrong type");
}
You are using hasNextInt() From Java docs.
Returns true if the next token in this scanner's input can be
interpreted as an int value
So you are asking twice for the input.
Example
Input:
1234 (first Input)
1234 (Then hasNextInt() is asking for input again)
OutPut :
wrong pass
So I made this simple snippet for you can use
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
int pass = 123;
try {
int myInput = password.nextInt();
if (myInput == pass) {
System.out.println("ok");
}else{
System.out.println("wrong pass");
}
}catch (java.util.InputMismatchException e) {
System.out.println("wrong type");
}
The problem is that Scanner methods like nextInt() consume input that's then no longer available to later Scanner calls.
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt() && password.nextInt()==pass) // line A
{
System.out.println("ok");
}
else if (password.hasNextInt()) // line B
{
System.out.println("wrong pass");
}
else
{
System.out.println("wrong type");
}
So in case of entering a wrong password, e.g. 4321, what happens?
Line A checks password.hasNextInt() as the first half of your condition. The Scanner doesn't know that right now and waits for your console input. You enter 4321, and now the Scanner can check whether that's a valid number (and it does so without consuming the 4321, so that it's still available). It is, so the program continues to the next part of the condition (side remark: were it abc, that first part would be false, and Java would already know that the combined password.hasNextInt() && password.nextInt()==pass condition would be false, without a need to go into the second half, thus not consuming the entry).
Line A now checks the second half password.nextInt()==pass. This calls nextInt(), returning the integer 4321 and consuming the input. Comparing this against your number 123 gives false, so the condition doesn't match. That's what you want so far.
Now in line B you want to check for the case of a number not being 123. But your condition password.hasNextInt() no longer sees the 4321 we entered, as that has been consumed in line A. So it waits for the next input. That's the problem, you're still calling hasNextInt() after consuming the input with nextInt().
You can change your program like this:
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt()) {
if (password.nextInt()==pass) {
System.out.println("ok");
} else {
System.out.println("wrong pass");
}
} else {
pass.next(); // consume the invalid entry
System.out.println("wrong type");
}
[ I reformatted the code snippet in a more Java-typical style, doesn't change the functionality of course, but looks more familiar to me. ]
Of course, Gatusko's exception-based approach works as well, and personally I'd do it his way, but maybe you don't feel comfortable with exceptions right now, so I stayed as close to your approach as possible.
You can use the following piece of code.
public static void main(String[] args){
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt())
{
if(password.nextInt()==pass) {
System.out.println("ok");
}
else {
System.out.println("Wrong password");
}
}
else
{
System.out.println("wrong type");
}
}
What about a while?
int MAX_TRIES = 3
int currentTries = 0;
while (password.hasNextInt() && currentTries < MAX_TRIES) {
if (password.nextInt()==pass) {
// OK!
} else {
// Wrong!
}
currentTries++;
}
if (currentTries == MAX_TRIES) {
// You tried too much
} else {
// Password was a string
}
Try this code, if the input is not an integer then it will throw NumberFormatException, which is caught and displayed.
public static void main(String[] args){
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
String enteredPassword ="";
if(password.hasNext() && (enteredPassword = password.next()) !=null){
try{
if(Integer.parseInt(enteredPassword) == pass){
System.out.println("ok");
}else{
System.out.println("wrong pass");
}
}catch (NumberFormatException nfe){
System.out.println("wrong type");
}
}
}

Creating and validating a reference number

So basically, I need to get the user to enter a reference number; it cannot be automatically generated.
It needs to be 2 Numbers, a Letter and a Number again.
Here's my code, but I cannot for the life me get it working, I had it working via a way that automatically generates a reference number, but now we need to change it so it gets the user to manually generate one and I'm just sat staring at NetBeans like "Oh errmmmm..."
static String getReferenceNumber() {
Scanner refScanner = new Scanner(System.in);
String referNumber = null;
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers and a Number");
String input = refScanner.nextLine().toUpperCase();
while (!Policy.refCheck(input)) {
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers a Nuber");
if (input.length() !=5) {
referNumber = false;
} else if ((!Character.isLetter(input.charAt(0)))
||!Character.isLetter(input.charAt(1))
||!Character.isDigit(input.charAt(2))
||!Character.isDigit(input.charAt(3))
||!Character.isDigit(input.charAt(4))){
referNumber = false;
}
System.out.println("");
System.out.println(referNumber);
return referNumber;
}
You never assign the actual input to the referNumber, instead you just assign Booleans?
Therefore at the end you are returning a Boolean or null when the return value needs to be a string.
static String getReferenceNumber() {
Scanner refScanner = new Scanner(System.in);
String referNumber = "";
boolean test = false;
while (!test) {
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers:");
String input = refScanner.nextLine().toUpperCase();
if (input.length() !=5) {
test = false;
System.out.println("Invalid reference");
} else if ((!Character.isLetter(input.charAt(0)))
||!Character.isLetter(input.charAt(1))
||!Character.isDigit(input.charAt(2))
||!Character.isDigit(input.charAt(3))
||!Character.isDigit(input.charAt(4))){
test = false;
System.out.println("Invalid reference");
} else {
referNumber = input;
test = true;
}
}
System.out.println(referNumber);
return referNumber;
}
I have changed the condition for the while loop and altered your if statements. I hope this helps.

Having an incedibly tough time with a loop

I've copied part of the instructions below, and I can code pretty much every part on its own, but getting the control flow together is giving me massive doubts about my ability.
One of my biggest problems is the int gameChanger. Im supposed to immediately verify if it is a integer or not, and loop back if its not. But then Im also supposed to check to see if thebuser ever types "exit". But the input variable for my scanner instance is an integer... So Im stumped. I can use a try catch to check the missmatchexception once the input is being read in, but that doesnt solve the exit issue nor am I able to come up with solid logic to get the try catch to loop back if it indeed isnt an integer. Im thinking a do while loop but I havent gotten it to work.
Instructions:
You can whether the input is a number before attempting to consume it.
int num;
while (true) {
if (scanner.hasNextInt()) {
num = scanner.nextInt();
break;
} else {
// read whatever is there instead.
String line = scanner.nextLine();
if (line.equals("exit"))
System.exit(0);
System.out.println("Please enter a number");
}
}
System.out.println("Number entered " + num);
This gets the job done. Try it out.
import java.util.Scanner;
public class MyCode
{
public static void main(String[] args)
{
String gameInput = ".";
int gameNumber = 0;
boolean inputLoop = true;
Scanner input = new Scanner(System.in);
while(inputLoop == true)
{
try
{
System.out.print("Please enter a valid game number: ");
gameInput = input.next();
if(gameInput.equals("exit"))
{
System.out.println("Program will now end. Goodbye.");
inputLoop = false;
input.close();
}
gameNumber = Integer.parseInt(gameInput);
if(gameNumber >= 20001 && gameNumber <= 21230)
{
System.out.println("You have inputted a valid game number.");
inputLoop = false;
input.close();
}
}
catch(NumberFormatException e)
{
if(!gameInput.equals("exit"))
{
System.err.println("Invalid game number. Please try again.");
}
}
}
}
}

Scanner loop doesn't cycle when hitting enter twice

boolean loop = false;
double numberOfStudents;
System.out.print("Enter a number: ");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
while (loop) {
System.out.println("Enter a number");
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
I'm trying to get the program to say "Enter a number" until the user has entered an actual number (no white spaces or letters or signs). When the user has entered a number, it sets numberOfStudents equal to that number and breaks out of the loop.
But if you hit enter twice, it doesn't iterate. It only displays "Enter a number" once.
What is wrong with the loop logic? Why isn't it looping until valid input is taken?
For the actual answer to your question of "Why doesn't 'Enter a number' display more than once?" see Tom's comment (update: Tom's answer).
I've rewritten your loop in a way which preserves your code, but also makes it a little easier to handle format exceptions (though at the risk of silently swallowing an exception -- should be acceptable for this use case).
Can be up to you to use this design, here is an SO post on why empty catch blocks can be a bad practice.
public static void main(String args[])
{
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(loop){
System.out.print("Enter a number: ");
String input = scnr.nextLine();
try{
numberOfStudents = Double.parseDouble(input);
loop = false;
}catch(NumberFormatException e){
}
}
System.out.println("You're outside the loop!");
}
Output:
Enter a number:
Enter a number:
Enter a number:
Enter a number: 50
You're outside the loop!
First of all: Since you're reading from System.in a call to the input stream will block until the user entered a valid token.
So let's check first scan using your scnr variable:
scnr.nextLine()
nextLine() reads everything til the next line delimiter. So if you just press return, then it will successfully read it and will perform the next stuff.
The next call is:
scnr.hasNextDouble()
This call expects a "real" token and ignores white spaces, except as a delimiter between tokens. So if you just press return again it doesn't actually read that input. So it still waits for more (for the first token). That is why it stucks in your loop and you won't get another "Enter a number" output.
You can fix that by either enter a real token, like a number, or by changing the loop like trobbins said.
I hope you now understand your program flow a bit more :).
While trobbins code basically solves your problem, it's bad practice to use exceptions for flow control.
I used a small regexp to check if the value is a number. But this example is not complete, it will still crash it the user enters for example two decimal points. So you would need to create a proper number check or just use integers where the check is much easier.
Someone in the comments pointed out that people may want to enter scientific notation like 5e10, so this would also be another case to check for. If this is just some code you need as a proof of concept or something quick and dirty, you can go with the exception handling method but in production code you should avoid using exceptions this way.
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(true) {
System.out.print("Enter a number: ");
String input = scnr.nextLine().trim();
if(input.matches("^[0-9\\.]{1,}$")) {
System.out.println("Loop has stopped");
numberOfStudents = Double.parseDouble(input);
break;
}
}
System.out.println("You're outside the loop!");
The following code should help you:
double numberOfStudents = 0;
Scanner scnr = new Scanner(System.in);
boolean readValue = false; //Check if the valid input is received
boolean shouldAskForNumber = true; //Need to ask for number again? Case for Enter
do {
if (shouldAskForNumber) {
System.out.print("Enter a number:");
shouldAskForNumber = false;
}
if (scnr.hasNextDouble()) {
numberOfStudents = scnr.nextDouble();
readValue = true;
} else {
String token = scnr.next();
if (!"".equals(token.trim())) { //Check for Enter or space
shouldAskForNumber = true;
}
}
} while (!readValue);
System.out.printf("Value read is %.0f\n", numberOfStudents);
System.out.println("You're outside the loop!");
Update
Understood the following statement in question different way:
But if you hit enter twice, it doesn't loop back. It only displays
"Enter a number" once.
The code is set to print "Enter a number" only once if the user hits RETURN/ENTER or enters space character. You may remove the special check and use the code if needed.
import java.util.Scanner;
public class Testing {
public static boolean checkInt(String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}
public static void main(String[] args) {
boolean loop = false;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
String input = "";
while (!(checkInt(input))) {
System.out.println("Enter a number");
input = scnr.nextLine();
}
numberOfStudents = Integer.parseInt(input);
System.out.println("Number of students: " + numberOfStudents );
}
}
//this code is working fine, if you want you check it out.
//In your code your taking another input if the first is an int/double; if the first input is not a number then you have mentioned to take input again..
Use a debugger to see what the code is actually doing. Here's a guide on debugging in Eclipse. After you have finished debugging your code, you will probably know what the problem is.
Below code will help you
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scnr.nextLine();
while(!scnr.hasNextDouble()){
System.out.print("Enter a number: ");
try{
numberOfStudents = Double.parseDouble(input);
break;
}catch(NumberFormatException e){
}
input = scnr.nextLine();
}
System.out.println("You're outside the loop!");
The following code is working,
boolean loop = true;
double numberOfStudents;
Scanner scnr=new Scanner(System.in);
while(loop) {
System.out.println("Enter a number");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
The output is,
run:
Enter a number
hj
po
Enter a number
lhf
Enter a number
o
Enter a number
p
Enter a number
a
Enter a number
34
Loop has stopped
You're outside the loop!
You have to scan the next line if you want to get more values form the scanner again. The code should be like:
while (loop) {
System.out.println("Enter a number");
if(!(scnr.nextLine().trim().isEmpty())){
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
}

Categories

Resources