I looked at some other similar posts but was not able to figure out the solution, hence looking for your valuable input, thanks in advance.
What I want: You will be asked to enter a sign (+ , -, /) and the output will display "You entered minus" (if your input was -)
Class that takes the input
import java.util.Scanner;
public class TakeSign {
Scanner userInput = new Scanner(System.in); /*Create an object of scanner class*/
public char mySign() {
System.out.print("Enter a sign: ");
char input2 = userInput.next().charAt(0);
return input2;
}
}
Main Class
public class Main {
public static void main (String[]args) {
TakeSign ts = new TakeSign();
if (ts.mySign() == '+') {
System.out.println("You entered plus");
}
else if (ts.mySign() == '-') {
System.out.println("You entered minus");
}
else if (ts.mySign() == '/') {
System.out.println("You entered division");
}
}
}
Problem
If my 1st input is / (division) I get asked 3 times. I was expecting to be asked just 1 time.
Enter a sign: /
Enter a sign: /
Enter a sign: /
You entered division
I think the problem is in the loop which I probably did not write correctly. Can you please point me to right direction?
You need to assign ts.mySign() to a variable and use that variable in your if statements
public static void main(String[] args) {
TakeSign ts = new TakeSign();
char sign = ts.mySign();
if (sign == '+') {
System.out.println("You entered plus");
} else if (sign == '-') {
System.out.println("You entered minus");
} else if (sign == '/') {
System.out.println("You entered division");
}
}
The mySign method asks the user for input. So if you call ts.mySign() three times, it will ask the user three times. But this is what you're doing in your chain of if and else statements.
You need to call ts.mySign() just once before the if statements, assign the result to a variable, then just check the value of that variable in each of the if statements.
You might use
switch( ts.mySign() ){
case '+':
System.out.println ("You entered plus");
break;
case '-':
System.out.println ("You entered mimus");
break;
case '*':
System.out.println ("You entered asterisk");
break;
case '/':
System.out.println ("You entered slash");
break;
default:
System.out.println ("Input error");
break;
}
You're calling ts.mySign() 3 times in your if-statement.
Call it once and store it in a variable and then compare against your signs.
i.e.
char sign = ts.mySign();
if (sign == '+')
...
Related
This is the code I have at the moment and I am trying to figure out how to jump back up from case "A" to the top of the do-while loop to allow the user to selection another action. The idea is that the user would be able to check their balance and then go back after checking their balance and either top-up their card or buy a wash. I only know how to end the loop from this point, not how to jump backwards to the previous input.
do {
System.out.println("Please select an option:\nPress [A] to CHECK FUNDS, press [B] to TOP-UP CARD, press [C] to BUY WASH or press [Q] to quit.");
String actionSelection = scan.nextLine();
switch (actionSelection) { //I haven't defined all the cases yet! //The other cases should not need to refer to other classes, all the actions are within the WashCard
case "A":
System.out.println("Your current balance is: " + this.cardBalance + ".00 DKK.");
sentinel = true;
System.out.println("Would you like to do something else? Press [B] to go back or [Q] to quit.");
break;
case "B":
System.out.println("How much would you like to deposit?\nPlease type in a number between 200 and 1000.");
//user input
break;
case "C":
//any selection should display card balance
//insufficient funds conditional statement:
if (this.cardBalance < 50) {
sentinel = true;
System.out.println("Not enough credit! Please top-up your card first");
System.out.println("Your current balance is: " + this.cardBalance + ".00 DKK.");
}
//only 50 DKK left on the card:
else if (this.cardBalance == 50) {
sentinel = false;
System.out.println("You only have enough credit for the ECONOMY WASH.");
System.out.println("Your current balance is: " + this.cardBalance + ".00 DKK.");
}
//any other choice:
else {
sentinel = false;
System.out.println("Your current balance is: " + this.cardBalance + ".00 DKK.");
}
break;
default:
sentinel = true;
System.out.println("Please enter a valid input!");
}
} while ( sentinel == true );
You do not need this. This soulution breaks OOP pricniples. To solve it you should encapsulate different logic in different methods.
public class Foo {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
proceed(scan);
}
private static final char CHECK_FUNDS = 'A';
private static final char TOP_UP_CARD = 'B';
private static final char BUY_WASH = 'C';
private static final char QUIT = 'Q';
public static void proceed(Scanner scan) {
while (true) {
System.out.println("Please select an option:");
System.out.format("[%s] - CHECK FUNDS\n", CHECK_FUNDS);
System.out.format("[%s] - TOP-UP CARD\n", TOP_UP_CARD);
System.out.format("[%s] - BUY WASH\n", BUY_WASH);
System.out.format("[%s] - quit\n", QUIT);
System.out.print("> ");
String menu = scan.nextLine().toUpperCase();
char ch = menu.length() == 1 ? menu.charAt(0) : '\0';
if (ch == CHECK_FUNDS)
onCheckFunds();
else if (ch == TOP_UP_CARD)
onTopUpCard();
else if (ch == BUY_WASH)
onBuyWash();
else if (ch == QUIT)
return;
System.err.println("incorrect input");
}
}
private static void onCheckFunds() {
System.out.println("onCheckFunds");
}
private static void onTopUpCard() {
System.out.println("onCheckFunds");
}
private static void onBuyWash() {
System.out.println("onBuyWash");
}
}
After a switch statement I would like to request a 'Y' or 'N' statement and print out a statement for the respective response. How can I declare the input char, then provide a scanner input for that value?
I've tried using input as a char and an integer. I've also tried using the boolean method as well.
import java.util.*;
public class Dowhile {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
System.out.println("0,1,-1: ");
x = in.nextInt();
switch(x)
{
case 1:
System.out.println("Positive");
break;
case -1:
System.out.println("Negative");
break;
case 0:
System.out.println("Zero");
break;
default:
System.out.println("You're a bad person!");
break;
}
char input = (('Y'||'N'));
System.out.println("Enter 'Y' or 'N'");
in.nextInt();
if(input = 'Y')
System.out.println("OK");
else
System.out.println("wow");
}}
I expect the output to be the println response for the respective input.
I would try something like this:
System.out.println("Enter 'Y' or 'N'");
char input = in.next("Y|N").charAt(0);
if('Y' == input)
System.out.println("OK");
else
System.out.println("wow");
The in.next("Y|N") part requests either a 'Y' or a 'N' (the String "Y|N" is interpreted as a regular expression) and returns the result as a String. The charAt(0) function returns the first (and only) character from this String.
Note that this approach throws an exception if you enter neither 'Y' nor 'N'.
If you want to avoid the exception you can use the following code snippet:
System.out.println("Enter 'Y' or 'N'");
char input = in.next(".").charAt(0);
if('Y' == input)
System.out.println("OK");
else if ('N' == input)
System.out.println("wow");
else
System.out.println("You haven't entered a valid character");
But beware, because your first call to in.nextInt() will still fail if someone enters something that isn't an integer.
Assuming you don't need to expand your program to do anything other than print to the console, the following would be the approach I'd take:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("0,1,-1: ");
int x = in.nextInt();
System.out.println(
x == 1 ? "Positive" :
x == -1 ? "Negative" :
x == 0 ? "Zero" :
"You're a bad person!"
);
System.out.println("Enter 'Y' or 'N'");
System.out.println(in.next().equalsIgnoreCase("Y") ? "OK" : "wow");
in.close();
}
Ternary operators are used for checking the conditions and printing to the console without switch or if statements.
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;
}
}
}
Sorry I am new to this site so not sure how this will show up. I am trying to make a simple Rock, Paper, Scissors game. After the while statement, if R, P, S isn't entered, the program just does nothing. I want it to loop back to the question at the beginning so a right choice can be entered. Also, how would I enter a print statement like "Invalid Choice Please Retry"?
package rps.gameapp;
import java.util.Scanner;
public class RPSGameApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int randNum = (int) (Math.random() * 3);
do
{
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));
String compChoice = "";
switch (randNum)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer entered \"" + compChoice + "\".");
if (compChoice.equalsIgnoreCase(userChoice))
{
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase(userChoice)
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P"))
{
System.out.println("User Wins");
} else
{
System.out.println("User Loses");
}
System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();
} while (playAgain.equalsIgnoreCase("Y"));
System.out.println("Thanks for Playing!");
}
}
It looks like you forgot one do for your inner do while loop.
It should be :
do {
do {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P") && !userChoice.equalsIgnoreCase("R") && !userChoice.equalsIgnoreCase("S"));
...
} while (playAgain.equalsIgnoreCase("Y"));
Without that inner do (and the curly braces surrounding that loop's body), the inner loop becomes a while loop with an empty body.
Like Eran said, you need to wrap your do-while loop in another loop, that will keep asking user for correct input. This is fully working code. One thing that could be better is the message after user inputs wrong letter.
Edit: also make sure you draw random number for every iteration.
Edit 2: to change the message depending on user input you can introduce a new variable that will keep the track of number of times you asked user for correct input. If it is 0- it means user is asked the first time and we should print "Welcome" message. It is anything other than 0- you need to ask the user for correct input. After every round we assign zero to the variable again and the cycle repeats. I have implemented this change in the code. Note that this variable can also be a boolean.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int iterationNumber;
while (true) {
iterationNumber = 0;
do {
if (iterationNumber == 0) {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
} else {
System.out.println("Please enter valid letter.");
System.out.println("Pick R, P, or S.");
}
iterationNumber++;
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));
String compChoice = "";
int randNum = (int) (Math.random() * 3);
switch (randNum) {
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer entered \"" + compChoice + "\".");
if (compChoice.equalsIgnoreCase(userChoice)) {
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase("R")
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P")) {
System.out.println("User Wins");
} else {
System.out.println("User Loses");
}
System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();
if (playAgain.equalsIgnoreCase("N")) {
break;
}
iterationNumber = 0;
}
System.out.println("Thanks for Playing!");
}
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.