Problem to validate the input from the user in java calculator - java

So I'm writing a code for a calculator in Java as a homework and I wanted to include an else statement in the end where if the user didn't input a valid operator, you get an error msg. Problem is that even when I input a valid operator, it prints the result and then the else error msg. Any help would be appreciated.
public class Main {
public static void main(String[] args){
Scanner inputi=new Scanner(System.in);
double num1,num2;
char operator;
System.out.println("Please enter the first number: ");
num1=inputi.nextDouble();
System.out.println("Please enter the second number: ");
num2=inputi.nextDouble();
Scanner oper=new Scanner(System.in);
System.out.println("Please enter the operator, the operators are +,-,*,/,%");
operator = oper.next().charAt(0);
if(operator== '+') {
System.out.println("The sum of these numbers is: "+(num1+num2));
}
if(operator=='-') {
System.out.println("The diff of these numbers is: "+ (num1-num2));
}
if(operator=='*') {
System.out.println("The result of this multiplication is: "+(num1*num2));
}
if(operator=='/') {
System.out.println("The division is: "+(num1/num2));
}
if(operator=='%') {
System.out.println("The module is: "+(num1%num2));
}
else {
System.out.println("Please just pick an operator..");
}
}
}

I'd recommend using switch instead:
switch (operator) {
case '+':
System.out.println("+");
break;
case '-':
System.out.println("-");
break;
/* Other operators */
default:
System.out.println("Please just pick an operator..");
}

You have "if if if if else" you want "if else if else if else". Your one else currently only applies to the if (operator == '%')

Try 'else if':
if(operator== '+') {
System.out.println("The sum of these numbers is: "+(num1+num2));
}
else if(operator=='-') {
System.out.println("The diff of these numbers is: "+ (num1-num2));
}
else if(operator=='*') {
System.out.println("The result of this multiplication is: "+(num1*num2));
}
else if(operator=='/') {
System.out.println("The division is: "+(num1/num2));
}
else if(operator=='%') {
System.out.println("The module is: "+(num1%num2));
}
else {
System.out.println("Please just pick an operator..");
However, a switch statement would be clearer:
switch(operator) {
case '%':
System.out.println("The module is: "+(num1%num2));
break;
default:
System.out.println("Please just pick an operator..");
}

The problem here is that you are not fully understanding the if else-if else statements.
The "If" means: if this conditional statement is true then execute the code to follow in the brackets.
The "If-else" means: if the statements above (if and else-if) are not true then execute this code.
The "else" means: if the preceding statement above (if or else-if) are not true then execute this code.
Given this, I'm sure not that you can see your error. All of your "if" statements are evaluating to if this condition then do this. Whereas you really wanted, to use "else-if" where if this is true then only execute the following code with the exclusion of the rest of the conditionals. You are correct in having an else clause pick up the default, however since you are not using "else-if" it really is compiling down to if this statement is not true, (the statement right before your else clause):
if(operator=='%') {
System.out.println("The module is: "+(num1%num2));
}
Then execute the else statement, which is not what you want.
I would recommend really figuring out what your code actually compiles down to in terms of machine instructions.

Related

Ask for input again if wrong input is entered

I am new to Java programming. I want the program to ask for input again if wrong input is entered by the user. What must I do? Please help! Jump to the 'if else if' part if you want to avoid the mess... And not being rude but please don't request for closing the question if you can't answer.
case 'A': case 'a':
System.out.println("You selected NOS Tank.");
int price;
double quantity;
double variant=0;
System.out.println("Select the variant: ");
System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
variant=xss.next().charAt(0);
if (variant=='D' || variant=='d')
{
System.out.println("The price of dry nitrous oxide system is: $600");
}
else if (variant=='w' || variant=='W')
{
System.out.println("The price of wet nitrous oxide is: $740");
}
else
{
System.out.println("Invalid input.");
}
It has been 28 days since you asked your doubt so I don't know if you have come across the answer or not but here's my solution.
To accept the correct input you need to make use of a while loop, loops are iterations in java which run for multiple number of times as per the given instructions. In this program I have incorporated a while loop whose condition is true always, so basically it is an infinite loop. If the inputted variant is correct and matches with any one of the if condition then the loop will break automatically because of the "break;" statement.
break; is a jump statement in java which allows you to terminate a loop when your requirements are met.
Given below is your required program code.
Hope this solves you query :)
case 'A': case 'a':
System.out.println("You selected NOS Tank.");
int price;
double quantity;
double variant=0;
System.out.println("Select the variant: ");
while(true)
{
System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
variant=xss.next().charAt(0);
if (variant=='D' || variant=='d')
{
System.out.println("The price of dry nitrous oxide system is: $600");
break;
}
else if (variant=='w' || variant=='W')
{
System.out.println("The price of wet nitrous oxide is: $740");
break;
}
else
{
System.out.println("Invalid input.");
System.out.println("Please enter the variant again:");
}
}

What expression would I use to stay in this switch statement?

I have the pieces that work which is the final total of the burgers, however I can't seem to keep the loop going so that if I select 1 it, grabs the burger and ask me to select again, adding more to the total. When I'm done it exits out and shows the final total and if I press 2. And other number it states in the loop and ask me again.
I don't know what to put into the switch statement to keep it going. Based on what I have I tried I tend to get the statement: "Cannot switch on a value of type boolean. Only convertible int values, strings or enum variables are permitted"
Based on what I have so far, I'm stuck.
boolean valid = true;
do {
System.out.println("Select an Option: ");
int userInput = scnr.nextInt();
switch (userInput <=2) {
case 1:
burgerOrder++;
subTotalBurgers = burgerPrice * burgerOrder;
finalSubTotal = burgerPrice * tax;
finalBurgerTotal = burgerPrice + tax;
break;
case 2:
System.out.println("2. Exit");
valid = true;
default:
System.out.println("Sorry");
continue;
}
}while(!valid);
System.out.println("BurgerOrder is " + finalBurgerTotal);
switch (userInput). The <= 2 is making it a boolean expression and is not necessary since you have a default case. Your loop requires that valid have an initial value of false (since that is your loop condition). And, you missed a break in case 2.
boolean valid = false;
do {
switch (userInput) {
case 1:
burgerOrder++;
subTotalBurgers = burgerPrice * burgerOrder;
finalSubTotal = burgerPrice * tax;
finalBurgerTotal = burgerPrice + tax;
break;
case 2:
System.out.println("2. Exit");
valid = true;
break;
default:
System.out.println("Sorry");
continue;
}
} while (!valid);
Your continue statement tells the program to break out of the loop. Just delete that.
For what it's worth, your case 2 also falls through to "default"; you might have intended a break statement after case 2.
And whatever you use as an expression for the switch statement is evaluated to see what case to go to -- userInput <= 2 seems unlikely for values of 1 and 2.

java program how add a function that goes back code if player has inputted it wrong

I have a problem with my program is not with the code is how I am going to do it that's the confusing part that I am stuck with. just to let you know I am a basic java coder I do not understand complicated stuff so bear in mind that my code isn't the best.
----------------------------------------------------------- program explaintion-----------------------------------------------------------------
let's get into the point of explaining how it works before I show you my problem, ok when you execute the program it prompts you a sort of like a menu in a video game but it's a text-based, it shows you different options like enter player details, play the math game show score and then quit. enter player details it tells player 1 to enter he/she name and then tells another one to input he/she player name then prompts you back to the menu. play the math game is where a player 1 is asked to input he/she math equation after that player 2 has to solve it if he gets it right he gets 10 points if no the player gets no points at all. then repeats for another player to input he/she math equation then prompts you back to the menu. show scores it shows who got the most scores in the math game it calculates who's got the most if both of them got the same score then means a tie then prompts you back to the menu. and the last thing the quit option when you choose that option it stops the program. if the player chooses a wrong choice he gets an error message and puts you back to the menu
ok here is the first class called menu and other class which is connected with menu called game factions
menu:https://gist.github.com/LOLMEHA/86ff28b038d85030e346785e953644e0
gamefactions:https://gist.github.com/LOLMEHA/f05a51e07c8823a0e65cebbf81cc52ef
so this section of code that I have trouble fingering it out myself
import java.util.*;
public class Gamefunctions // this is a core when player choosess one of these options from the menu
{
String[] player =new String[2];
double scorea = 0; // verribles of all the objects
double scoreb = 0;
int i;
Scanner input = new Scanner(System.in);
double answer = 0;
double numA, numB;
char operator;
char operator2;
boolean quit = false;
double sum1;
double sum2;
public void enterDetails(){ // if player select enter details
for ( i=0;i<2;i++) {// tell's player to input he/she's name and stores them
int c=i;
System.out.println("Welcome to the maths quiz game please input player name "+c++);
player[i] = input.next();
}
}
public void mathGame(){ // if player select enter details
System.out.println("Please enter your equation please "+player[0]+" press enter for each number and mathematical symbol"); // tells the player 1 to input
System.out.println("");
System.out.println("such as for ex input a number or how many you like, then hit enter and input such as /*-+^ hit enter, then input any number one or how many you like ");
String s=input.next();
numA = Double.parseDouble(s); // numa and numb and operator is the aera of player to input he/she equation
operator = input.next().charAt(0);
numB = input.nextDouble();
if () {
if (operator == '+') {// this is if operator is one of these like +-*/^ and then it works out the sum
answer = numA + numB;
}
if (operator == '-') {
answer = numA - numB;
}
if (operator == '*') {
answer = numA * numB;
}
if (operator == '/') {
answer = numA / numB;
}
if (operator == '^') {
answer = Math.pow(numA, numB);
}
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
System.out.println("");
System.out.println(player[1]+"\t solve the equation"); // tells other player to slove the equation
sum2 = input.nextDouble();
if (sum2 == answer){// checks if the answer from the player is good or not if its good he/she gets 10 points if he/she gets it wrong gets no points and shows the right answer so the player learns from his/she mistakes
scoreb = scoreb + 10.00;
System.out.println("correct you got 10 points to your score");
System.out.println("");
} else{
System.out.println("incorrect you got no points the correct answer was:"+"" + answer);
}
you know when the program ask to player to input his math eqtion and outputs this and continues with the program and waiting for the user to input
public void mathGame(){ // if player select enter details
System.out.println("Please enter your equation please "+player[0]+" press enter for each number and mathematical symbol"); // tells the player 1 to input
System.out.println("");
System.out.println("such as for ex input a number or how many you like, then hit enter and input such as /*-+^ hit enter, then input any number one or how many you like ");
String s=input.next();
numA = Double.parseDouble(s); // numa and numb and operator is the aera of player to input he/she equation
operator = input.next().charAt(0);
numB = input.nextDouble();
let's say that the player inputs like this 10+10 enter but it will not work since they are stored in numA which is an int, I want to make a error message saying that you can not input like this 10+10 you have to input like this 10 enter + enter 10 enter so it will be able to work
if the player inputs it correctly it will continue the program
so if you have any problems with my explaintion of my plroblem pls ask so I can edit it thank you for time :)
Here’s the bit of your code I’m going to be looking at:
String s = input.next();
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
if (/* Some condition */) {
// Calculate answer
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
First up, a couple nitpicks: Java is not C. You don’t need to declare all your variables at the beginning of your code blocks. numA, numB and operator are never used outside this bit of code, so it makes sense to declare them in here as well.
You’re also using input.next() with Double.parseDouble() once, then input.nextDouble() the next time. Stick to one or the other, it’ll make debugging easier if something doesn’t work properly.
And finally, what happens if someone enters 10 +1 0? The error is silently ignored because the 1 gets picked up as part of the operator string then discarded by charAt(0). A more resilient parsing method here would be to fetch the entire String first, then check for length == 1 before calling charAt(0).
double numA = input.nextDouble();
String operatorString = input.next();
char operator;
if (operatorString.length() == 1) {
operator = operatorString.charAt(0);
} else {
// Handle error
}
double numB = input.nextDouble();
if (/* Some condition */) {
// Calculate answer
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
Onto your question then: how do we detect an invalid input? Take a look at the documentation for Scanner#nextDouble() (emphasis mine):
public double nextDouble()
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
So we know nextDouble() can detect the invalid input for us. It does this in the form of an exception, which we can listen for (or catch) using a try ... catch statement:
try {
double numA = input.nextDouble();
} catch (InputMismatchException e) {
System.err.printf("Invalid input! Expected number, found '%s'.\n", input.next());
}
We could extend this and wrap the entire section of code in a single try ... catch, but then the user would have to start again if they make one mistake. A more user-friendly solution would be this:
double numA;
while (1) {
try {
numA = input.nextDouble();
break;
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected number, found '%s'.\n", input.next());
}
}
Note the even if you don’t print it, the call to input.next() is necessary to prevent an infinite loop.
Now we just need to do something similar for operator:
char operator;
while (1) {
String operatorString;
try {
operatorString = input.next();
if (operatorString.length() != 1) {
throw new InputMismatchException();
}
operator = operatorString.charAt(0);
break;
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected character, found '%s'.\n", operatorString);
}
}
This seems very similar to the previous snippet for a number - let’s try to refactor some of the common code here into a method:
#FunctionalInterface
public interface ScannerGetter<T> {
T apply() throws InputMismatchException;
}
public <T> T getValueFromScanner(ScannerGetter<T> getter, String type) {
while(1) {
try {
return getter.apply();
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected %s.");
}
}
}
There’s a lot going on in these few lines. The first part declares a functional interface - this is a basically a custom type of lambda function. We’ll come back to that in a moment.
The method itself (getValueFromScanner()) is a generic method. It allows us to use the same method with different types in place of the generic parameter (T) without duplicating it.
This is how you’d use the above method to retrieve your three inputs:
double numA = this.<Double>getValueFromScanner(() -> input.nextDouble(), "number");
char operator = this.<Char>getValueFromScanner(() -> {
operatorString = input.next();
if (operatorString.length() != 1) {
throw new InputMismatchException();
}
return operatorString.charAt(0);
}, "operator");
double numB = this.<Double>getValueFromScanner(() -> input.nextDouble(), "number");
// Once your code gets here, all three variables will have valid values.

Changing an if else statement to a switch statement

I was wondering what would be the best way to convert this if statement within a do while loop to a switch statement within a do while loop.
What would be a better way to tighten up this code?
do{
currency = keyboard.nextInt();
if (currency == 1)
{
sterling = euros * 0.79;
System.out.printf("£ %.2f", sterling);
}
else if (currency == 2)
{
usDollars = euros * 1.28;
System.out.printf("$ %.2f", usDollars);
}
else if (currency == 3){
auDollars = euros * 1.44;
System.out.printf("$ %.2f", auDollars);
}
else{
System.out.printf("Invalid Option");
}
System.out.printf("\nWould you like to go again");
System.out.printf("\n1. Yes\n2 No");
repeat = keyboard.nextInt();
if (repeat == 2){
System.out.printf("Exit Program");
System.exit(0);
}
}while(repeat == 1);
For your example, if statement and switch will do exactly the same things. No differences.
What you could change from your code would be the last if statement:
if (repeat == 2){
System.out.printf("Exit Program");
System.exit(0);
}
You can write this if statement outside the do while, and like this will be checked only once.
Switch case looks something like this
switch (currency) {
case 1: System.out.printf("£ %.2f", euros * 0.79);
break;
case 2: .
.
.
.
.
.
.
case n: .
break;
default: System.out.printf("Invalid Option");
break;
}
Its no different even if it is in a loop (for, while, do while)
Read more about the Switch statement and try to complete the code yourself
On a side note, no need to create variables (sterling,usDollars,auDollars) to store the values of the expressions euros * 0.79 unless you are using storing for later use which doesn't seem to be the case.
You could put the conversion rates in an array, then use what would have been the
switch/if variable to index that array. Something like:
float[] rates = {0.79f, 1.28f, 1.44f};
answer = euros * rates[currency-1];
System.out.printf("$ %.2f", answer);
Then you don't need the selection statement(s). In general, if you see a lot of structural repetition, look for the common code and try to factor it out.

Java validating a range of numbers from user input

I have been having problem with my validation, and it is stressing me out, I have done it in various ways with different loops, and the one I have as of now is this one, if I take out the IF statement if will function well for numbers, but since my program can only accept numbers from 1 to 5 I want to take the extra step into validating the number and then returning it. I try declaring the int option inside a loop but does not carry out to the return statement.
public int makeOption(){
int option;
System.out.println("Choose from the following options: ");
System.out.println("(1)Create entry || (2)Remove entry || (3)List entry || (4)List All || (5)Exit ");
while(!reader.hasNextInt()){
System.out.println("Choose a valid option.");
reader.next();
}
if(reader.nextInt()<1 || reader.nextInt()>5){
System.out.println("Choose a valid number from options.");
reader.next();
}
option = reader.nextInt();
System.out.println("You choosed: " + option);
return option;
}
Swap out your if statement for a switch statement:
int input = reader.nextInt();
switch(input)
{
case 1: // Do something
break;
// blah blah blah more cases.
default: System.out.println("Please enter a correct value.");
}
A note on your code
When you call reader.nextInt(), you're telling the stream to expect another int. You're not viewing the same value. You should store it in a variable, before using it.

Categories