Putting 2 Boolean controllers in a do while expression? - java

newbie programmer here. I'm using Java to try and create a number guessing game. I want my do while loop to continue looping until the user inputs the correct number OR they run out of guesses. This is what I have and I can't figure out how to use 2 boolean controllers for the life of me.
do
{System.out.println("Enter guess #1");
userGuess = keyboard.nextInt();
} while ((userGuess != actualNumber) || (remainingGuesses = guesses; remainingGuesses >= 1; remainingGuesses--));
Any help is appreciated!

I think that you want something closer to this effect:
remainingGuess = guesses;
do {
System.out.println("Enter guess #1");
userGuess = keyboard.nextInt();
} while ( userGuess != actualNumber || remainingGuesses-- > 0 )
Line by line:
remainingGuesses = guesses;
assigns guesses to remainingGuesses once, if you were to do it every iteration of your loop, it would never end
userGuess != actualNumber || remainingGuesses-- > 0
Keep iterating while the user has guessed incorrectly OR remainingGuesses is more than 0.
remainingGuesses--
Evaluates to the current value of the variable remainingGuesses, then after the expression decrements it by 1.

Initialize remaining guesses before entering the loop. Only check the condition in the while paranthesis "()"
reaminingGuesses = guesses;
do
{System.out.println("Enter guess #1");
userGuess = keyboard.nextInt();
remainingGuess--;
} while ((userGuess != actualNumber) || (remainingGuesses >= 1));

If you want it as a do while I would make a few minor changes, and assuming you have constants defined for things like actualNumber and the total number of allowed guesses:
// break the calls into seperate methods, to make them easier to read in the long term and to
// seperate logical concerns into discrete elements.
do {
// get the user guess
guess = getGuess();
// if shouldStop returns true you would stop, if it returns false you should continue, thus the !..
} while (!shouldStop(guess)) {
// decrement the guesses.
--remainingGuesses;
}
/// define these methods somewhere..,
// get your guess
public int getGuess() {
System.out.println("Enter guess #1");
return keyboard.nextInt();
}
public boolean shouldStop(int guess) {
// condensed if statement syntax in java, very handy for this kind of thing
// do we have enough remaining guess to keep going? If so, compare the guess to the actual number
// otherwise return true (the stop signal
return remainingGuesses > 0 ? guess == actualNumber : true;
}
If you really wanted to follow the whole thing through you could break the guess==actual number into a method as well, but its probably not needed in this case since its a simple equality check.
The methos shouldStop could be defined a number of ways however...
Early on I think it's helpful to write these logical blocks out fully, and condense from there, for example:
public boolean shouldStop(int guess) {
if(remainingGuesses <=0) {
return true;
} else if(guess == actualNumber) {
return true;
} else {
return false;
}
}

Related

Check if an Array contains an Integer or not using for loop

I have created an array, and use a for loop to check if that array contains an input integer or not by this code:
import java.util.stream.IntStream;
import java.util.Arrays;
public class playGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
int guess;
int[] range = IntStream.rangeClosed(1, 100).toArray(); // Set the range from 1 - 100
System.out.println(Arrays.toString(range));
System.out.println("Please type a number ");
guess = TextIO.getlnInt();
for(int i:range) { // Check if input value is in range or not
if( i == guess){
System.out.println("good job");
//...
}
//...
}
This works quite well; However, when I:
Replace ( i == guess) with (i != guess) // if guess not in range. Java always prints "good job" whether input integer in range 1-100 or not.
When I add an else statement like else { System,out.println("terrible"); } or use break; to break the loop;
It always prints "terrible" or print the whether integer in range or not.
How can I ask people for input integer again if it's not in range 1-100. Should I use the nested loop, or is there anyway simpler?
Please help me with these 3 problems.
I suggest you build up a java.util.HashSet upon the array values, and use it to check easily if a given number is contained within them.
Set<Integer> mySet=new HashSet<Integer>(Arrays.asList(range));
boolean guessIsContained=mySet.contains(guess);
And if you want to loop a user input until a guess is OK, you'd enclose the whole operation within a while with a proper exit condition:
Set<Integer> mySet=...
do
{
// ... input one guess from user.
boolean guessIsContained=mySet.contains(guess);
// ... evaluate guessIsContained
} while (!guessIsContained);
not using an array and a for loop will solve all your issues. try
if (guess >= 1 && guess <= 100) {
System.out.println("good job");
} else {
System.out.println("terrible");
}
1) let's assume guess == 10. Your for loop will print "good job" 99 times. Because 10 != 1, 10 != 2, 10 == 10, 10 != 100.
2) because guess is != i 99 times again.
3) use a while ( true ) loop and a break after printing "good job".
First of all, for i to equal guess, i needs to be in range anyway...I find that contradictory. Anyway, to do it without a for loop:
if(1<=i<=100 && i == guess){
System.out.println("good job");
}
If 1<=i<=100, then it is in range. That makes the for loop an if statement, and I combined it with your other if statement, and put && i == guess.
1) Should work with the above code
2)I don't understand what your saying, but from the official java docs:
An unlabeled break statement terminates the innermost switch, for,
while, or do-while statement, but a labeled break terminates an outer
statement.
3) Try the following:
if(1<=i<=100 && i == guess){
System.out.println("good job");
}else if(i<1 || i>100)
System.out.println("Please type a number in range");
guess = TextIO.getlnInt();

Why is there a "deadbranch" in my code?

below my code was working fine until my last if-else. It appears I've done something wrong with my boolean variables canGraduate and onProbation. Perhaps I'm reassigning them incorrectly in the prior if-else statements. The deadbranch occurs at the else half of my last if-else.
package lab5;
import java.util.Scanner;
public class Lab5 {
public static void main(String[] args) {
//creates scanner object
Scanner scanner = new Scanner(System.in);
//PART II
//creating variables
double gpa;
int totalCreditsTaken;
int mathScienceCredits;
int liberalArtsCredits;
int electiveCredits;
boolean canGraduate = true;
boolean onProbation = false;
//prompts user for imput
System.out.println("What is your GPA?");
gpa = scanner.nextDouble();
System.out.println("What's the total amount of credits you've taken?");
totalCreditsTaken = scanner.nextInt();
System.out.println("How many math and science credits have you taken?");
mathScienceCredits = scanner.nextInt();
System.out.println("How many liberal arts credits have you taken?");
liberalArtsCredits = scanner.nextInt();
System.out.println("How many elective credits have you taken?");
electiveCredits = scanner.nextInt();
//creates first "if" statment to determine if GPA is high enough to be on track or on probation
if (gpa < 2.0){
System.out.println("You're on academic probation.");
onProbation = true;
}
//PART III
//creates a conditional to see if there's enough credits to graduate
if (totalCreditsTaken < 40 ){
System.out.println("You need more credit(s) to graduate.");
canGraduate = false;
}
else{
System.out.println("Examining credit breakdown...");
canGraduate = true;
}
//PART VI
//Nested if-else if-else to determine if the student qualifies for BA or BS
if ((mathScienceCredits >= 9) && (electiveCredits >= 10)){
System.out.println("You qualify for a BS degree.");
canGraduate = true;
}
else if ((liberalArtsCredits >= 9) && (electiveCredits >= 10)){
System.out.println("You qualify for a BA degree.");
canGraduate = true;
}
else{
System.out.println("You currently don't meet the degree requirments.");
canGraduate = false;
}
//PART V
//Uses an if statement to either congradulate the student or tell the student to take more classes
if ((onProbation = true) || (canGraduate = false)){
System.out.println("You don't qualify to graduate.");
}
else{
System.out.println("Congradualations you qualify to graduate.");
}
}
}
You are assigning the values here:
if ((onProbation = true) || (canGraduate = false)){
You need to compare them using == instead
UPDATE (after comments)
Better yet, don't compare boolean values. Instead, since onProbation and canGraduate are both boolean types, you can use:
if (onProbation || ! canGraduate ){
credit to #RealSkeptic and #FredK (in their comments)
A bit more explanation about what's happening here.
In Java, the = operator is assignment, not comparison (The comparison operator is ==). So if a is an int, a = 3 means "put the value 3 in the variable a".
But an assignment is also an expression. In addition to putting the value in that variable, the expression also evaluates to the value that was assigned.
So the value of the expression a = 3 is 3. You can do things like:
System.out.println( a = 3 );
This will both put 3 in a, and print 3 on the console.
Usually, Java doesn't allow you to confuse between = and ==. If the variable is an int or a float or a String, writing a statement like:
if ( a = 3 ) ... // Compilation error
will not work because the value of the expression is 3, an int value, and if expects an expression of type boolean. So it will tell you that the expression is wrong, and you'll notice: "Oh, I meant ==".
But if the type of a is boolean, then writing a = false or a = true is an assignment, that also returns the value that was assigned - which is a boolean. Because of that, you can write
if ( a = false ) ... // Compiles correctly
and the compiler won't complain, because the value of the expression is boolean and that's what the if expects. The compiler doesn't know you actually meant to compare. All it knows is that it got an expression of the appropriate type.
For this reason it is recommended never to compare boolean variables at all. Instead of
if ( a == true )
It is perfectly correct to write
if ( a )
Because the if will succeed when a is true and fail when a is false. No need to compare! It's important to give the variable a good name like you did - canGraduate is a good name, and a statement like
if ( canGraduate )
is nicely readable "If [the user] can graduate...".
For false, you can use
if ( ! canGraduate )
it's not as nice-sounding in English, but it's clear enough, and clearer than if ( canGraduate == false ), with the added bonus that you will not miss the = and write if ( canGraduate = false ) by mistake.

input validation and refuse improper input

I am attempting to validate user input. I have tried some if statements and attempted Boolean. I cant get anything to give the output or rather the validation I am wanting
Users are asked to choose between "red" or "blue" I want them to be required to type either "red" or "blue". I know this could be solved easier through buttons but I am trying to use string input. the code below give an example of where i am.
custColorMsg = "Which color do you want your shirt to be red or blue?";
customerColor = getstringInput(custColorMsg);
String color = null
if( customerColor.equalsIgnoreCase("yes")) {
color = true}
if( customerColor.equalsIgnoreCase("no")) {
color = true}
else if(!customerColor.equalsIgnoreCase("yes" || "no") {
color = false}
I know this last portion is wrong I am just unsure how to go about fixing it. Customers will have three chances to input a valid response then the program will terminate, this portion i can handle. If i can just figure out how to accept "yes" or "no" and refuse anything else.
In terms of the design of this program, I would recommend adding a for loop, that goes from 0 to 2 (this will iterate 3 times). Within the loop, the program can determine what the user's input is. I would also recommend looking at my syntax for the for loop below, I use ifs, else ifs and elses to evaluate the data set more efficiently.
The implementation of the program could be:
for(int i = 0; i < 3; i++)
{
customerColor = getstringInput(custColorMsg);
String color = null
if( customerColor.equalsIgnoreCase("yes")) {
color = true;
break;
}
else if( customerColor.equalsIgnoreCase("no")) {
color = true;
break;
}
else{
color = false;
}
custColorMsg = "Invalid Input, Please Input Again";
}
This will give the user 3 times to input the data, and if they input it correctly, it will stop asking, however, if they do not, it will ask again until they run out of attempts.
There's a few things wrong with your approach.
The semantics of your variable names are a bit off. Which makes the code difficult to read. For example, the variable color which you have defined here as a String, but consistently use as a Boolean is a bit confusing. I'm guessing you mean to define it as a Boolean type and intend to use it as the breaking condition from your loop - it would be more meaningful to name the it as isValidColor or something along those lines.
The following line doesn't do what you think it does:
customerColor.equalsIgnoreCase("yes" || "no")
The method equalsIgnoreCase() takes in a String and not a Boolean like this line of your code will have for an argument. Since the || will resolve to a Boolean value of true or false. Furthermore, those are bad operand types for that operator and the code won't compile.
For your control structure you can use a while loop which will exit when you have reached the max amount of tries or entered a valid response.
Here's a working Console version of what you are trying to accomplish:
String custColorMsg = "Which color do you want your shirt to be red or blue?";
String customerColor;
Boolean validInput = false;
Scanner in = new Scanner(System.in);
int tries = 0;
while (tries < 3 && !validInput)
{
System.out.println(custColorMsg);
customerColor = in.nextLine();
if( customerColor.equalsIgnoreCase("red")) {
validInput = true;
}
else if( customerColor.equalsIgnoreCase("blue")) {
validInput = true;
}
tries++;
}

For loop and charAt problems, trying to determine whether a string is numeric [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to write a program is for checking a real number, so i input "99aa", it says it is a right, but in fact, it should be wrong. i have check many time and i still can't fix the problem. can some one give me some hints?
public class jj {
public static void main( String[] args ) {
String num;
// Create a Scanner object for console input
Scanner input = new Scanner(System.in);
System.out.print("Enter the number: ");
num = new String( input.nextLine() );
for ( int i=0; i<=num.length(); i++ ) {
int j = num.charAt(i);
if (j>57 || j<42 || j==44 || j==47 ) {
System.out.print("This is not a real number.");
break;
} else
System.out.print("This is a real number.");
break;
}
}
}
I commented what's wrong with your logic but don't reinvent the wheel.
Use NumberUtils.isNumber from org.apache.commons.lang.math.NumberUtils :
Checks whether the String a valid Java number.
Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).
if(NumberUtils.isNumber(num))
System.out.println("This is a valid number");
else
System.out.println("This is not a valid number");
Alternatively, if you want to check that you have only digits in your String, you can use
NumberUtils.isDigits:
Checks whether the String contains only digit characters.
boolean valid = NumberUtils.isDigits(num);
Your logic is wrong.
try this instead
if ((j >= 48 && j <= 57) || j==44 || j==47 ) {
}
You want to check whether it is between 48 (0) and 57 (9), boundaries included.
See the ascii table.
Sidenotes:
You're allowing j==47. 47 is /, dot is 46. What one do you want?
Your second break; will leave the iteration after the first cycle.
Try,
char ch = num.charAt(i);
if (!Character.isDigit(ch)) {
System.out.print("This is not a real number.");
break;
}
I'd just like to point out some logic trouble that's giving you some fits:
if (j>57 || j<42 || j==44 || j==47 ) {
System.out.print("This is not a real number.");
break;
} else
System.out.print("This is a real number.");
break;
}
First of all, nevermind the problems with the if check. Jeroen Vannevel's answer covers this.
After any number returns true on the if check, you print the error and break; the loop. This is fine (assuming we fix the if check). You don't need to check every digit if you know the first one is wrong, you can quit checking.
But your else prints a message guaranteeing that the whole number is real despite just checking a single letter.
And then the break; isn't contain in the if or the else (not your brackets and my indentation that makes it more clear). No matter what happens, you'll break; after a single iteration.
What you need should look something more like this:
boolean numberFlag = true;
for ( int i=0; i<=num.length(); i++ ) {
int j = num.charAt(i);
if ((j >= 48 && j <= 57) || j==44 || j==47 ) {
numberFlag = false;
break;
}
}
if(numberFlag) {
// logic when a valid number is checked
} else {
// logic when an invalid number is checked
}
We can't say whether num is a valid number of not until we've checked every single character in the string.
And please be sure to check #ZouZou's answer, as this is what you should really be doing.
You could think about this in terms of Characters and implement the following:
if (Character.isDigit(num.charAt(i))) {
//do something
}

Beginner looping issue- while ... do

What the program does: Reads two values from input, asks user whether to add, subtract, or find the product. If user enters one of the three options, it calculates, otherwise the program will loop back to the beginning. The program should STOP after calculation if the user enters one of the three options.
I'm not sure why it keeps on looping. How do I make the script loop only when the user types in a string other than "sum", "difference", or "product"? Also, how can I make the code simpler? Is there any way to loop the program without using do ... while?
import java.util.Scanner;
import java.util.Random;
public class simp_calculator
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
double a, b;
String response;
boolean noresponse;
do
{
System.out.println ("Please enter first number.");
a = scan.nextDouble();
System.out.println ("Please enter second number.");
b = scan.nextDouble();
System.out.println ("Would you like to find the sum, difference, product?");
response = scan.next();
if (response.equalsIgnoreCase ("sum"))
{
System.out.println (a + b);
}
if (response.equalsIgnoreCase ("difference"))
{
System.out.println (a - b);
}
if (response.equalsIgnoreCase ("product"))
{
System.out.println (a * b);
}
else
{
noresponse = true;
System.out.println ("Starting again...");
}
}
while (noresponse = true);
}
}
You are using the assignment operator, =, so noresponse will always be true. The result of the assignment expression is thus true.
You want to check if it is true, so use the comparison operator ==:
while (noresponse == true);
or, because it's already a boolean:
while (noresponse);
Also, you may be getting a compiler error that noresponse may not have been initialized. You will need to make sure that it's initialized in all cases, and that something sets it to false so the loop will eventually end.
change while (noresponse = true); to while (noresponse == true);.
= is an assignment operation - where as == comparison.
Two errors:
The else applies only to the last if; so for any value, other that "product", noresponse becomes true and the loop goes on. Replace all your ifs from the second on with else ifs.
noresponse should be given the value false at the beginning of the loop.
There are 2 issues:
Currently you are looping while noreponse equals true. So to exit that loop, you need to setnoresponse to false when a particular condition is met :) I could give you the answer, but you should be able to figure it out with the info I've given you. (hint: at some point you need to set noresonse to false).
Also, you are setting noresponse to equal, rather than comparing it. You need to use == to compare.
So make while (noresponse = true); into while (noresponse == true);.
just change while (reponse = true) to while(reponse) and name the variable ..

Categories