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:");
}
}
Related
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.
I'm taking an Intro to Java class, and I haven't been having any trouble until now. I don't know if I'm just being a fool and the answer is simple but here goes.
I need to create a simple menu. I prompt the user, and then they enter an integer to choose one option. But there also needs to be an option to type "X" and exit the program.
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the Math Study Guide!");
System.out.println("Which arithmetic table would you like to use?");
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("X) Exit the program");
int input = in.nextInt();
if (input <= 5 )
{if (input == 1){System.out.println("Addition");}
{if (input == 2){System.out.println("Subtraction");}
{if (input == 3){System.out.println("Multiplication");}
{if (input == 4){System.out.println("Division");}
else {System.out.println("You have exited");}
Testing it, whenever I type "X" it shuts down everything and doesn't tell me I've exited. Is there a general input I can use where you can enter either an int or a String?
As already stated in some comments, your probleme is the data-type. If someone enters 'X' in the program, it is expected to be an integer value, which it is not.
To get your Program working you need to alter your datatype from int to String
String input = in.next();
this will get you the input.
Now make a switch/case instead of your if-statements
switch (input) {
case "1" : System.out.println("Addition");
break;
case "2" : System.out.println("Subtraction");
break;
deafult: System.out.println("You have exited the program");
break;
}
If you are not familiar with the switch/case statement: case "1" checks if input equals "1". If true it prints out "Addition", after that it is important to make a break; otherwise it would go on checking if input equals "2" and so on.
the default branch is activated if nothing else matches. So your program would also write "You have exited the program" if your input was e.g. "r". If you don't want that, just add another case "x" and write your thing.
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.
This is my first time on this site. I am taking a course in Java right now and I am having some trouble with this code/program that I am supposed to make that allows the user to select whether they want to see "good monkeys", "bad monkeys" or "show monkeys". It is nowhere near done but I am having trouble returning to the command screen/area after a command is completed. I would like the commands to be used as many times as possible. Secondly, my program treats every input if someone put in "Good Monkey". So if you put in a word like "pineapple", it will still greet you with the output designated for the "Good Monkeys" input.
I've looked online and seen that maybe I should use a "do-while" loop and use "switch". Any input/ help would be greatly appreciated. Thank you so much!
Here is my code: public class and public static and Scanner import are in this code, but for some reason I cannot add them into this post without messing up the formatting of the code.
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
First, you need to define the loop. Second, you need to put the input instruction inside the loop.
I'll include a done variable to detect when the user wants to escape
So, let's code:
Scanner jScanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
System.out.println("(or enter 'done' to exit");
String userChoice = jScanner.nextLine();
swithc(userChoice.toLowerCase()) {
case "good monkeys":
/*
* The code for this option
*/
break;
case "bad monkeys":
/*
* The code for this option
*/
break;
case "show monkeys":
/*
* The code for this option
*/
break;
case "done":
done = true;
break;
default:
System.out.println("Your input isn't what I expected!\nTry again!");
break;
}
}
The code, explained:
That while(!done) stuff can be read as "while 'not done' do what follows"
userChoice.toLowerCase(): I convert the userChoice to lower-case, to simplify comparissons. That way, I only need to compare the string with other lower-case strings
switch(userChoice.toLowerCase()): ... hmmm... I think you can figure it out yourself ;)
That default block is what happens if no other case is valid
The "done" block will set the done variable to true, and thus it will terminate the loop
Important: ALWAYS end the case blocks with break
Further reading:
The Java Tutorials: Language basics
The while and do-while statements
The switch statement
Also, I recommend you study Flowcharts and, before start coding, try to draw in paper a flowchart of your program. That way, you will have a clear image of your program before you start writing the very first line of code.
This is a follow up to a question I have asked previously that did get answers that should have fixed my problem, but unfortunately did not. My program reads in a text file and organises data before giving the user a number of options. When the program gets to this point I want to user to be able to select an option, that performs an operations, but then returns the user back to the start point to be able to perform more operations. This is the answer I liked best (thanks to Octopus) and am currently trying to implement.
//set choiceentry to -1, this will make it to enter while loop
int choiceentry = -1
while(choiceentry < 1 || choiceentry > 3){
System.out.println("Enter \"1\", \"2\" or \"3\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
switch(choiceentry){
case 1:
//do logic
break;
case 2:
//do logic
break;
case 3:
//do logic
break;
}
}
As I see it, the program should enter the loop initially, allow the user to input a selection, then return back to "enter a value". However, the program does not return, and terminates after one operation. How can I prevent this to continue the program running infinitely?
Thanks in advance!
The current while loop is there to get valid input -- don't change it.
You need to wrap this code in another while loop that loops til a sentinal value is entered.
while (!isSentinalValue) {
while (inputNotValid) {
// get valid input
}
}
Edit
More specifically in pseudocode:
while (!isSentinalValue) {
input = invalidValue
while (inputNotValid) {
getInput
}
use input to do menu things
}
So I would not have the switch block inside of the inner loop, since that loop concerns itself only with making sure that the input entered is valid. Do the switch block outside of the inner loop, and be sure to set the sentintal value that allows the user to escape the outerloop when appropriate.
Your while(choiceentry < 1 || choiceentry > 3) condition is wrong. If you want it to loop , then you have to make it between 1 and 3 .
So this also means that you will have to change your choiceentry initialization value. This will work.
int choiceentry = 1
while(choiceentry >=1 && choiceentry <= 3){
System.out.println("Enter \"1\", \"2\" or \"3\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
....
}
your loop only runs while choiceentry is less than 1 or greater than 3. As soon as the user enters one of those values, the loop exits.
Learn to use a debugger.
place the following code after switch
if(choiceentry == 4){
break;
}
Now when you will input 4 then it will be terminated, you can use any value other then 4
Use break only when user wants to quit(Say when choiceentry=0). You can use "continue" to make loop infinite. Sample code is given for reference
int choiceentry = 1; // can set any int value except 0 (exit code is 0 for this example)
Scanner scanchoice = null;
while (choiceentry != 0) {
System.out.println("Enter \"1\", \"2\" or \"3\" ..Press 0 to quit");
scanchoice = new Scanner(System.in);
if (scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
// System.out.println("choiceentry=" + choiceentry);
switch (choiceentry) {
case 0:
{
System.out.println("Bye Bye");
break;
}
case 1:
{
System.out.println("In Case 1");
continue;
}
case 2: {
System.out.println("In Case 2");
continue;
}
case 3: {
System.out.println("In Case 3");
continue;
}
}
}