Java Do While Statement with two conditions - java

I'm trying to learn java but I'm stuck trying to do a single program which concerns Do While Statement with two conditions. Specifically, I want a method to run until the user write "yes" or "no". Well, down there is my thing, what is wrong with it?
String answerString;
Scanner user_input = new Scanner(System.in);
System.out.println("Do you want a cookie? ");
do{
answerString = user_input.next();
if(answerString.equalsIgnoreCase("yes")){
System.out.println("You want a cookie.");
}else if(answerString.equalsIgnoreCase("no")){
System.out.println("You don't want a cookie.");
}else{
System.out.println("Answer by saying 'yes' or 'no'");
}while(user_input == 'yes' || user_input == 'no');
}
}}

I'd do something similar to Tim's answer. But to do things the way you were trying to do them, you have a lot of problems that need to be fixed:
(1) String literals in Java are surrounded by double quote marks, not single quote marks.
(2) user_input is a Scanner. You can't compare a scanner to a string. You can only compare a String to another String. So you should be using answerString in your comparison, not user_input.
(3) Never use == to compare strings. StackOverflow has 953,235 Java questions, and approximately 826,102 of those involve someone trying to use == to compare strings. (OK, that's a slight exaggeration.) Use the equals method: string1.equals(string2).
(4) When you write a do-while loop, the syntax is do, followed by {, followed by the code in the loop, followed by }, followed by while(condition);. It looks like you put the last } in the wrong place. The } just before the while belongs to the else, so that doesn't count; you need another } before while, not after it.
(5) I think you were trying to write a loop that keeps going if the input isn't yes or no. Instead, you did the opposite: you wrote a loop that keeps going as long as the input is yes or no. Your while condition should look something like
while (!(answerString.equals("yes") || answerString.equals("no")));
[Actually, it should be equalsIgnoreCase to be consistent with the rest of the code.] ! means "not" here, and note that I had to put the whole expression in parentheses after the !, otherwise the ! would have applied only to the first part of the expression. If you're trying to write a loop that does "Loop until blah-blah-blah", you have to write it as "Loop while ! (blah-blah-blah)".

I might opt for a do loop which will continue to take in command line user input until he enters a "yes" or "no" answer, at which point the loop breaks.
do {
answerString = user_input.next();
if ("yes".equalsIgnoreCase(answerString)) {
System.out.println("You want a cookie.");
break;
} else if ("no".equalsIgnoreCase(answerString)) {
System.out.println("You don't want a cookie.");
break;
} else {
System.out.println("Answer by saying 'yes' or 'no'");
}
} while(true);

Related

How to strictly allow exactly ONE char as input using SCANNER reader with reference to my code?

The code below is for a simple calculator with the four basic mathematical operators. It is a working program, it works as expected. However, I have a few questions to understand and improve both my program as well as my understanding of Java. (I have used google but the amount of redundant info confuses me and haven't found any perfect answers on StackOverflow too, though there are dozens of related questions. Believe me, I did tried before posting here).
How can I make sure that the user input is exactly and strictly one char?
here in my program, it accepts more than one character (+-*) but operates on the first char (+) only. I want to make sure more than one character is not accepted as input.
After successful execution of the program, how can I somehow let the user repeat the main method? I mean, a user adds two numbers, gets his answer and he wants to do another calculation, maybe multiply two numbers this time. I can ask the user for yes or no to continue but how do I take him/her back to the beginning? (will a loop work? how?)
A the end of the program I used two methods to output a message. The system.out.print works fine but the JOptionPane method doesn't display the message and the program doesn't terminate (I have commented it out). I would like to understand why?
Is the default case required in the switch? And Am I following the correct code structure? (the arrangements and uses of curly braces)
NB: As I said this calculator works fine and can be used by newbies like myself to better understand the concept as I have commented on every detail. Please understand that I couldn't add everything in the question title due to limits...
package mycalculator;
import javax.swing.JOptionPane;
import java.util.*;
public class MyCalculator{
public static void main (String [] args){
// Let us code a simple calculator//
// Variable type declarations//
char OP;
int firstNum;
int secNum;
// Display an explanation of what this program does//
System.out.println("This is a simple calculator that will do basic
calculations such as :"
+ "\nAddition, Multiplication, Substraction and Division.");
// Create a scanner object to Read user Input.//
Scanner input = new Scanner(System.in);
// Ask user to input any positive number and read it//
System.out.println("Enter Any positive number followed by pressing
ENTER.");
firstNum = input.nextInt();
// Ask user to input/decide his choice operator and read it //
System.out.println("Enter a valid OPERATOR sign followed by pressing
ENTER.");
OP = input.next().charAt(0);
// Loop the below statement till one of the four (+,-,*,/) is entered.//
while(OP != '+' && OP != '-' && OP != '*' && OP != '/'){
System.out.println("Please Re-enter a valid Operator (+,-*,/)");
OP = input.next().charAt(0);}
// Ask user for any second number and read it//
System.out.println("Enter your Second number followed by an ENTER
stroke.");
secNum = input.nextInt();
// Various possible Resolution based on OP value.//
int RSum = firstNum+secNum;
int RSubs= firstNum-secNum;
int RPro = firstNum*secNum;
double DPro = firstNum/secNum;
// Conditional statements for Processing Results based on OP and display.//
switch(OP){
case '+': System.out.println("The Resulting sum is "+ RSum);
break;
case '-': System.out.println("The Resulting sum is "+ RSubs);
break;
case '*': System.out.println("The Resulting Product is "+ RPro);
break;
case '/': System.out.println("The Resulting Divisional product is "+
DPro);
break;
//Maybe the default case is actually not needed but is added for totality//
default : System.out.println("Try Again");
break;
}
// The following code maybe deleted, it is for experimental purpose//
// Just checking if additional statements executes after a program
completes//
System.out.println("Test Message ");
// JOptionPane.showMessageDialog(null, "The Process Ends Here!");
//The test message works fine//
//The JOptionPane statement don't work and program doesn't end. WHY?//
}
}
How can I make sure that the user input is exactly and strictly one
char? here in my program, it accepts more than one character (+-*) but
operates on the first char (+) only. I want to make sure more than one
character is not accepted as input.
If you use console application and Scanner, only thing that you can do is read a String and check its length. In case you use Swing, you could implement KeyPressListener and proceed exactly after user press a button (but not for console application).
After successful execution of the program, how can I somehow let the
user repeat the main method? I mean, a user adds two numbers, gets his
answer and he wants to do another calculation, maybe multiply two
numbers this time. I can ask the user for yes or no to continue but
how do I take him/her back to the beginning? (will a loop work? how?)
You can't repeat main method. In Java main method is been executing only once. To repeate your code, you could wrap whole main method content to the infinite loop or move the content to the separate method and call it from the loop in the main method.
A the end of the program I used two methods to output a message. The
system.out.print works fine but the JOptionPane method doesn't display
the message and the program doesn't terminate (I have commented it
out). I would like to understand why?
JOptionPane works only for graphic application (Swing/AWT). This is not available in console. You have only standard input and output there.
Is the default case required in the switch? And Am I following the
correct code structure? (the arrangements and uses of curly braces)
No, default case is optional by JVM syntax. I remember, that e.g. in C++ there was reccomendation to place it (event empty), to exclude side effects of compilators. I do not know, is there such reccomendation in Java, but when I use switch, I prefer to always add it to exclude logical problem (but this is definetly optional according to syntax case). You use switch correctly.
public static void main(String[] args) {
System.out.println("This is a simple calculator that will do basic calculations such as :"
+ "\nAddition (+)"
+ "\nMultiplication (*)"
+ "\nSubtraction (-)"
+ "\nDivision (/)");
System.out.println();
try (Scanner scan = new Scanner(System.in)) {
while (true) {
System.out.println("Enter Any positive number followed by pressing ENTER.");
int first = scan.nextInt();
System.out.println("Enter a valid OPERATOR (+,*,-,/) sign followed by pressing ENTER.");
String operator = scan.next();
while (operator.length() != 1 || !"+*-/".contains(operator)) {
System.out.println("Please Re-enter a valid Operator (+,-*,/)");
operator = scan.next();
}
scan.nextLine();
System.out.println("Enter your Second number followed by an ENTER stroke.");
int second = scan.nextInt();
if ("+".equals(operator))
System.out.println("The Resulting sum is " + (first + second));
else if ("*".equals(operator))
System.out.println("The Resulting mul is " + (first * second));
else if ("-".equals(operator))
System.out.println("The Resulting sub is " + (first - second));
else if ("/".equals(operator))
System.out.println("The Resulting div is " + ((double)first / second));
System.out.println();
System.out.println("Do you want to exit ('y' to exit)?");
if ("y".equals(scan.next()))
return;
System.out.println();
}
}
}
1) you can check size of string input.next() .If it is one then continue else again prompt for operator choice .
2)I would suggest better create a different method and put all logic in it and call it the number of time you want or call infinite number of times.
4)Should switch statements always contain a default clause?

How to check for strictly formatted input?

I am doing a coding project for a basic non recursive, non GUI form of Minesweeper. One of the requirements is that input commands must be strictly formatted like so:
For marking commands (reveal, guess, mark):
["reveal"/"r"] [int] [int]
For help and quit:
just ["help"/"h"] or ["quit"/"q"]
Any inputs outside of these restrictions must be considered ill-formatted. My code for reveal looks something like this:
case "reveal":
case "r":
roundsCompleted ++;
if(input.hasNextInt()){
par1 = input.nextInt();
}
else{
commandIn = null;
}
if(input.hasNextInt()){
par2 = input.nextInt();
correctInput = true;
}
else{
commandIn = null;
}
if(correctInput && isInBounds(par1, par2)){
reveal(par1, par2);
where this is all inside a switch statement of course. The commandIn = null statements are designed to throw the default case which prints "command not recognized". I realize part of my issue here is that these are in two separate if-else statements. Another problem is that input.hasNextInt() doesn't seem to evaluating to false when there is not an int after the first one.
The essence of this problem is in completely restricting these commands to the formats I listed above. Can anyone give me some insight into this issue? Thanks.
I'd use regex to first see if something is either a good input or not just cause it'd be easier
String input = "r 3 4";
if (input.matches("^(help|h|quit|q|((r|reveal) \\d \\d))$"))
//switch case
System.out.println("match");
else
//null string
System.out.println("no match");
then after you've got a match you can use your switch case like what you're doing, if it's a "reveal" or "r", I would just use split() and turn it into an array to get the different x and y coordinates

While not (or equivalent) java

I'm making a program with Java that needs to involve some error checking. I can stop users from entering bad numerical inputs like this (assume the input scanner has already been created):
while (n == 0){
System.out.println("Can't use 0 as a denominator! Please enter a real, nonzero number");
n = input.nextInt();
}
But how do I stop users from entering an invalid string? I can't use !=, because strings can only be compared with the string.equals() method, right? So, is there a while not loop? ie:
while !(string.equals("y") || string.equals("n")){
//here have code
}
Or something of that nature?
While there is no such thing as a while-not loop, you can always invert the condition:
while (!(string.equals("y") || string.equals("n"))){
This is read, "while the string is not equal to "y" or "n"".
You could also apply DeMorgan's identity to rewrite this as:
while (!(string.equals("y")) && !(string.equals("n"))){
which is a bit clearer as "While the string isn't equal to "y" and isn't equal to "n"".
There isn't a while-not instruction, but you can simply negate the condition in a normal while loop. Try this:
while (!string.equals("y") && !string.equals("n"))
Or even better, to guard against the case where the string is null and/or it's in a different case:
while (!"y".equalsIgnoreCase(string) && !"n".equalsIgnoreCase(string))
You almost get it, just change where you position your !
like this:
while (!(string.equals("y") || string.equals("n")))
Why not try regex?
Scanner sc = new Scanner(System.in);
String string = sc.nextLine();
while (!string.matches("(?i)^(?:y|n|yes|no)$"))
{
System.out.println("Invalid input...");
string = sc.nextLine();
}
boolean answer = string.matches("(?i)^(?:y|yes)$");

User input for an if/else statement

its only my second program with java and im running into some issues.
I'm trying to get input from a user, either yes or no, then based on that go to an if else statemene. Heres what I have so far
String answer= UI.askString("Do you want to continue?");
if(answer=="yes"){
UI.println("Lets go");
}
else if(answer == "no"){
UI.println("Thank you. Goodbye");
}
else{
UI.println("Please enter yes or no");
}
Im thinking perhaps its better to use booleans for this?
Any help is gladly appreciated!
(also if you're wondering, its a custom import hence the weird syntax in some lines)
Cheers.
When you compare two Strings in Java with the == operator, they are compared to see if they are the same object, rather than whether they contain the same text. So, you could type "yes", and when you use if (answer == "yes") the comparison fails, because the object you got back from UI.askString is a different object, stored at a different place in memory, than the String the compiler generated from the literal "yes".
To compare the value of the two Strings you need to write answer.equals("yes"), or "yes".equals(answer). Either one will work, and will call the equals method of the String class, which will compare the actual text.
The latter syntax, "yes".equals(answer), is often recommended because it will not cause a NullPointerException, even if the variable answer is set to null. This is because the equals method handles null and simply returns false. If, on the other hand, you used the answer.equals("yes") form, and answer was null, you would be trying to invoke a method on null and an exception would be thrown.
what you are looking for is a dialog box. Here is oracle examples, with code. It is more than I can write here. There are ton of yes, no boxes and detection's of user input with them.
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
Quick answer:
int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){ ... }
Other choices ...
YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, and CLOSED_OPTION
For a command line program you need...
import java.util.Scanner;
The code will look like ...
Scanner in = new Scanner(System.in);
String line = in.nextLine();
//ask them to write yes, no, whatever
if(line.equal("yes"){ }
else if (line.eqals("no") {}
else {}
using MikeG010590's answer, you can try:
Scanner in = new Scanner(System.in);
String line;
System.out.println("you want to continue?");
Boolean exit = null;
do {
line = in.nextLine();
switch (line) {
case "yes":
exit = false;
break;
case "no":
exit = true;
break;
default:
System.out.println("Please enter yes or no");
break;
}
}
while (exit == null);
System.out.println(exit ? "Thank you. Goodbye" : "Lets go");

Program compiles but does not run

This is an assignment i have to complete.
Can someone lead me in the right direction?
The program compiles but wont run correctly.
The error is InputMissmatch exception.
The error you are getting means that you are trying to use some kind of data as another one, in your case, you are probably trying to use a String as a float.
When using any of the next methods in the Scanner class you should first be sure that there's an appropiate input from the user.
In order to do so, you need to use the has methods.
Your problem is that you are not checking wether the input is a correct float or not before using your Scanner.nextFloat();
You should do something like this:
if (hope.hasNextFloat())
{
// Code to execute when you have a proper float,
// which you can retrieve with hope.nextFloat()
}
else
{
// Code to execute when the user input is not a float
// Here you should treat it properly, maybe asking for new input
}
That should be enough to point you in the right direction.
Also, check the Scanner api documentation for further details.
EDIT
Also, you are asking the user to input characters (or strings): "A", "B", etc..., but you are trying to compare them with a float. That's wrong, you should compare them with a string or character, like this:
if (hope.hasNextString())
{
if (hope.nextString().equals("A"))
{
// Code for option "A"
}
else if (hope.nextString().equals("B"))
{
// Code for option "B"
}
else ...
}
You could use a switch there, but it seems that you are not yet very fammiliar with java, so I'll leave it for another time.
Your problem is that you are entering a letter into a float field.
In your program you're asking the user to enter a float:
A = hope.nextFloat();
But if you enter the letter "A", you're going to get an exception because "A" is not a float, it's a string.
A simpler way to solve your problem is instead of having all the choices fields, you just read the input the user enters from the scanner like:
String choice = hope.next();
Next in the if statement, you check if the value from the string choice is equal to a specific letter, for example
if (choice.equals("A")) {
number4 = (number1 + number2 + number3);
System.out.printf("Your results are:" + (number4));
}
And you can do the same thing for the other choices you have.

Categories

Resources