package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("What is the password?");
Scanner new2 = new Scanner(System.in);
int input = 0;
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
}
}
}
basically, once I hit the 5 loops, it just says "incorrect password" and breaks. not the "maximum attempts" message.
Allow me to annotate:
This if statement will always be evaluated:
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
This if statement will only be evaluated if the password is "bluesky123". In this case, it will always evaluate to true.
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
There is no case when this if statement will ever be evaluated. Once if-else finds a statement that is true, it will skip all others in that section.
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
In your case, you should consider a nested if (i.e. an if inside another if).
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else {
System.out.println("You got it right!");
break;
}
if((input == 5) && (!password.equals("bluesky123"))) {
System.out.println("maximum number of attempts reached");
break;
}
}
Your logic has some flaws. You have to pay attention to how JAVA processes if / else if
https://www.tutorialspoint.com/java/if_else_statement_in_java.htm
I tested your code it is working! The only thing that you need to do is to move the follow line to inside the while loop
System.out.println("What is the password?");
Doing this it will print "Incorrect password" and then it will print again
"What is the password?"
Because in the way that it is working now seems that the software is not waiting the password to be retyped when in fact it is.
Related
A little confused on where to put another if-else statement after one. like do I put it under the if statement ("have you registered to vote yet?" ) or do i put it under the else statement?
I wanted it to answer if yes then it would print out "you can vote" and if no then it would print out "You must register before you can vote"
here's the code
import java.util.Scanner;
public class voting {
public static void main(String[] args) {
int yourage, votersage;
votersage = 18;
Scanner input = new Scanner(System.in);
System.out.println("How old are you? ");
yourage = input.nextInt();
if (yourage >= votersage) {
System.out.println("Have you registered to vote?");
}
else {
System.out.println("You are too young to vote");
}
}
}
I think this works to how you want it. You may need to change around the input'Registered as I am a bit rusty with inputs but I think this should work?
if (yourage >= votersage) {
Scanner input = new Scanner(System.in)
System.out.println("Have you registered to vote?");
Registered = input.next();
if Registered = ("Yes") {
System.out.println("You can vote");
}
else if Registered = ("No"){
System.out.println("You need to register to vote");
}
else:
System.out.println("INVALID INPUT")
}
else {
System.out.println("You are too young to vote");
}
For elif statements you put the elif before the else, but make sure to add a clause for the elif statement to run just like you did with the original if statement.
if (yourage >= votersage) {
System.out.println("Have you registered to vote?");
}
else if (yourage <= votersage){
System.out.println("You must register before you can vote.");
}
else {
System.out.println("You are too young to vote");
}
Nested if statement work in these scenarios...
if (yourage >= votersage)
{
System.out.println("Have you registered to vote?");
bool registered = input.next();
if(registered)
{
System.out.println("You can vote");
}
else
{
System.out.println("Please get yourself register on voting portal!");
}
}
else {
System.out.println("You are too young to vote");
}
Hello I am writing a simple program for a user to take a 3 question test. I am trying to validate the user input however if the user enters in a loop to enter the correct data because they previously entered the wrong data they cannot get out of the loop. Even if there next answer is correct. Something is setting one of my flags to false and I cannot figure out what. I tried debugging it to no avail.
import java.util.Scanner;
public class ALittleQuiz {
private static int correct = 0;
public static void main (String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("Are you read for the quiz? ");
keyboard.next();
System.out.println("Okay, here it comes!");
questionOne();
questionTwo();
questionThree();
System.out.println("Overall, you got "+correct+" out of 3 correct.");
System.out.println("Thanks for playing!");
}
public static void questionOne(){
System.out.println("Q1) What is the capital of Alaska?");
System.out.println(" 1) Melbourne");
System.out.println(" 2) Anchorage");
System.out.println(" 3) Juneau");
System.out.print("> ");
getUserInputForQuestionOne();
}
public static void questionTwo(){
System.out.println("Q2) Can you store the value 'cat' in a variable of type int? ");
System.out.println(" 1) Yes");
System.out.println(" 2) No");
System.out.print("> ");
getUserInputForQuestionTwo();
}
public static void questionThree(){
System.out.println("Q3) What is the result of 9+6/3?");
System.out.println(" 1) 5");
System.out.println(" 2) 11");
System.out.println(" 3) 15/3");
System.out.print("> ");
getUserInputForQuestionThree();
}
public static void getUserInputForQuestionOne(){
int testvar = 0;
try{
Scanner inputForQuestionOne = new Scanner(System.in);
testvar = inputForQuestionOne.nextInt();
validateUserInputForQuestionOne(testvar);
} catch (Exception e) {
System.out.println("Error: invalid entry please try again");
getUserInputForQuestionOne();
}
}
public static void getUserInputForQuestionTwo(){
int testvar = 0;
try{
Scanner inputForQuestionTwo = new Scanner(System.in);
testvar = inputForQuestionTwo.nextInt();
validateUserInputForQuestionTwo(testvar);
} catch (Exception e) {
System.out.println("Error: invalid entry please try again");
getUserInputForQuestionTwo();
}
}
public static void getUserInputForQuestionThree(){
int testvar = 0;
try{
Scanner inputForQuestionThree = new Scanner(System.in);
testvar = inputForQuestionThree.nextInt();
validateUserInputForQuestionThree(testvar);
} catch (Exception e) {
System.out.println("Error: invalid entry please try again");
getUserInputForQuestionThree();
}
}
public static void validateUserInputForQuestionOne(int choiceOne){
if(choiceOne >= 1 && choiceOne <= 3){
sendResponseForQuestionOneToDetermineIfCorrectOrNot(choiceOne);
}else {
System.out.println("Please enter 1, 2 or 3 for your selection");
getUserInputForQuestionOne();
}
}
public static void validateUserInputForQuestionTwo(int choiceTwo){
if(choiceTwo >= 1 && choiceTwo <= 3){
sendResponseForQuestionTwoToDetermineIfCorrectOrNot(choiceTwo);
}else {
System.out.println("Please enter 1 or 2 for your selection");
getUserInputForQuestionTwo();
}
}
public static void validateUserInputForQuestionThree(int choiceThree){
if(choiceThree >= 1 && choiceThree <= 3){
sendResponseForQuestionThreeToDetermineIfCorrectOrNot(choiceThree);
}else {
System.out.println("Please enter 1, 2 or 3 for your selection");
getUserInputForQuestionThree();
}
}
public static void sendResponseForQuestionOneToDetermineIfCorrectOrNot(int validChoiceOne){
switch (validChoiceOne){
case 1: System.out.println("Sorry, that is not correct\n");
break;
case 2: System.out.println("Sorry, that is not correct\n");
break;
case 3: System.out.println("That's right\n");
correct++;
break;
}
}
public static void sendResponseForQuestionTwoToDetermineIfCorrectOrNot(int validChoiceTwo){
switch (validChoiceTwo){
case 1: System.out.println("Sorry, 'cat' is a string. Ints can only store numbers\n");
break;
case 2: System.out.println("That's right\n");
correct++;
break;
}
}
public static void sendResponseForQuestionThreeToDetermineIfCorrectOrNot(int validChoiceThree){
switch (validChoiceThree){
case 1: System.out.println("Sorry, that is not correct\n");
break;
case 2: System.out.println("That's right\n");
correct++;
break;
case 3: System.out.println("Sorry, that is not correct\n");
break;
}
}
}
Here is what is happening in my terminal:
Are you ready for a quiz? y
Okay, here it comes!
Q1) What is the capital of Alaska?
1) Melbourne
2) Anchorage
3) Juneau
> 456
Please enter 1, 2 or 3 for your selection
Q1) What is the capital of Alaska?
1) Melbourne
2) Anchorage
3) Juneau
> 3
That's right
Please enter 1, 2 or 3 for your selection
Q1) What is the capital of Alaska?
1) Melbourne
2) Anchorage
3) Juneau
> 2
Sorry, that is not correct
Please enter 1, 2 or 3 for your selection
Q1) What is the capital of Alaska?
1) Melbourne
2) Anchorage
3) Juneau
>
Edit: So after reading the article one of you had posted I went back to the drawing board and was able to resolve my issue. I do want to thank those that took the time to help me with this. I updated my code which I believe is a lot more comprehensible and easier to look at. Above is my newly created code. If anyone has any notes on this I would much appreciate it!
Inside of questionOne, you make a call to validateQuestionOneUerInput. In validateQuestionOneUerInput, if the user enters something other than 1, 2, or 3, it sets flagForQuestionOne and then calls questionOne again. Regardless of the result of this call, flagForQuestionOne is false, so you now have an infinite loop.
That method could see if the user's response is valid or not and return true or false, or could throw an exception for invalid input, but should not re-call questionOne.
in the do while loop, instead of using the flag, you are checking the flag equals == false.
Below is incorrect because when you set the flag value to true the while condition evaluates to false.
while (flag == false);
Change it to
while(flag)
I am making a basic calculator, where it does addition, multiplication, etc. It first checks the type of operation it is e.g, 1 is for addition, 2 for multiplication and so on. If it detects that the operation type input is invalid, it just simply tells me in the console an error. Is there any method I can use to detect the method, and then re-enter the input?
public void printCheck() throws ArithmeticException{
if (op == 2) {
System.out.println("You have chosen addition");
}
else if (op == 3) {
System.out.println("You have chosen subtraction");
}
else if (op == 4) {
System.out.println("You have chosen multiplication");
}
else if (op == 5) {
System.out.println("You have chosen division");
}
else {
throw new ArithmeticException("Entered an invalid operation");
}
try {
a.op(0);
}
catch(ArithmeticException e){
System.out.println("You have entered an invalid operation");
}
You may repeat the input of the operation code until it is valid.
I don't recommend using exceptions here because it's a common and well known case that the user gives an invalid input. Instead you should create a simple method isValidOperationCode which checks the input. For improved readability I have removed the global variable op and turned it into a local variable which gets passed as parameter into the methods which need it.
Example:
int op;
do {
op = askUserForOperation();
printCheckOperation(op);
} while (!isValidOperationCode(op));
with a modified printCheckOperation method
...
} else if (op == 5) {
System.out.println("You have chosen division");
} else {
System.out.println("Entered an invalid operation");
}
and the new method
private boolean isValidOperationCode(int op) {
return 2 <= op && op <= 5;
}
I'm Sorry i couldn't be more elaborate since I'm using a mobile phone to answer to this question. I hope this answer helps.
public void printCheck(){
while(true){
if(op<2 || op>5){
enterNewOp();
}
else {
switch(op) {
case 2:
System.out.println("You have select addition");
case 3:
System...
case 4:
......
}
break;
}
}
}
So I just have a quick little issue
int pickmeup = 0;
while (true)
{
pickmeup = scanner.nextInt();
if (pickmeup == 1)
{System.out.println ("you entered 1");}
if(pickmeup == 2)
{System.out.println ("you entered 2");}
{
break;
}
System.out.println ("Invalid code");
Now when I run this code it all works fine however in regards to the strings but it seems as though the loop doesn't work all that well when I enter '3', as it doesn't return the string 'Invalid code'.
If I were to get rid of the strings after both if statements, then it works perfectly fine. What exactly am I doing wrong? Are there other ways to automatically have strings output?
I believe you want to use a logical or || and an else like,
int pickmeup;
while (true) {
pickmeup = scanner.nextInt();
if (pickmeup == 1 || pickmeup == 2) {
System.out.printf("you entered %d%n", pickmeup);
} else {
System.out.println("Invalid code");
}
}
Alternatively, you could use an else if chain like,
int pickmeup;
while (true) {
pickmeup = scanner.nextInt();
if (pickmeup == 1) {
System.out.println("you entered 1");
} else if (pickmeup == 2) {
System.out.println("you entered 2");
} else {
System.out.println("Invalid code");
}
}
You could start with firstly correcting your code, you can do that in eclipse Source-Format or by pressing CTRL+SHIFT+F
For your example, I corrected as much as I understood, currently it breaks only if else is reached. Break can be modified.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int pickmeup = 0;
while (true){
pickmeup = scanner.nextInt();
if (pickmeup == 1){
System.out.println("one");
}
else if (pickmeup == 2){
System.out.println("two");
}
else{
System.out.println("Invalid code");
break;
}
}
I'm trying to write some code that makes the user input a valid username and they get three tries to do it. Every time I compile it I get an else without if error wherever I have a else if statement.
Scanner in = new Scanner(System.in);
String validName = "thomsondw";
System.out.print("Please enter a valid username: ");
String input1 = in.next();
if (input1.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
String input2 = in.next();
}
else if (input2.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
String input3 = in.next();
}
else if (input3.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
return;
}
You are misunderstanding the use of if-else
if(condition){
//condition is true here
}else{
//otherwise
}else if{
// error cause it could never be reach this condition
}
Read more The if-then and if-then-else Statements
You can have
if(condition){
}else if (anotherCondition){
}else{
//otherwise means 'condition' is false and 'anotherCondition' is false too
}
If you have an if followed by an else, that ends the block. You can have if followed by multiple else if statements, but only one else -- and the else must be last.
You need to either: change all your "else" except the last to "else if", or put plain "if" before the following "else if" statements:
(1)
else if (input2.equals(validName))
{
System.out.println("Ok you made it through username check");
}
(2)
else if (input3.equals(validName))
{
System.out.println("Ok you made it through username check");
}
Your code is not very maintainable. What would you do, if the user got 5 tries? Add some additional if blocks? And what if the user has 10 tries? :-) You see what I mean.
Try the following instead:
Scanner in = new Scanner(System.in);
int tries = 0;
int maxTries = 3;
String validName = "thomsondw";
while (tries < maxTries) {
tries++;
System.out.print("Please enter a valid username: ");
String input = in.next();
if (input.equals(validName)) {
System.out.println("Ok you made it through username check");
break; //leaves the while block
}
}