do while looping forever [closed] - java

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'm having trouble with this method, I'm forever stuck on "Sorry you must specify a Deeppan or thin base, try again: " even if I type jimmy, harry, deeppan, thin, Thin.. etc After I type either deeppan or thin, I want the String stored in the variable "size" and returned
Any ideas what I'm missing?
public String Input(){
String size;
Scanner sc = new Scanner(System.in);
System.out.println("thin or thick: ");
do {
size = scan.next();
if ( !size.equalsIgnoreCase( "thick") || !size.equalsIgnoreCase( "thin" )) {
System.out.print("Sorry you must specify a thick or thin base, try again: ");
} else {
break;
}
} while ( true );
return size;
}

Change your || for a && in the if condition. At the moment the condition will be true if you type in 'thin' because it is not deeppan and vice versa.

The statement inside your if is always true.
You should use either
!size.equalsIgnoreCase( "Deeppan") && !size.equalsIgnoreCase( "thin" )
or
!(size.equalsIgnoreCase( "Deeppan") || size.equalsIgnoreCase( "thin" ))

while(true) will make your loop infinite as its always true
reason is you are doing || operation

reason:
!size.equalsIgnoreCase( "Deeppan") || !size.equalsIgnoreCase( "thin" )
size cannot be "Deeppan" and "thin" at the same time :-)
try:
do {
size = scan.next();
if (size.equalsIgnoreCase( "Deeppan") || size.equalsIgnoreCase( "thin" )) {
break;
}
else {
System.out.print("Sorry you must specify a Deeppan or thin base, try again: ");
}
} while ( true );
ps. "size" isn't the best variable name...

No reason to use a do-while, try a while like this, the condition checking becomes more straightforward:
while (true) {
size = scan.next();
if (size.equalsIgnoreCase("deeppan") || size.equalsIgnoreCase("thin"))
return size;
System.out.println("Sorry you must specify a Deeppan or Thin base, try again:");
}

It will always be true, and therefore never reach the else
Example 1: Size is "Deeppan":
!size.equalsIgnoreCase( "Deeppan") || !size.equalsIgnoreCase( "thin")
= !true || !false
= false || true
= true
Example 2: Size is "foo":
!size.equalsIgnoreCase( "Deeppan") || !size.equalsIgnoreCase( "thin")
= !false || !false
= true || true
= true

Yuor statement
if ( !size.equalsIgnoreCase( "Deeppan") || !size.equalsIgnoreCase( "thin" ))
is always true.

Related

How to make do-loop conditions "when string does not equal"

I want to make my do loop run while the input the user made is not equal to the required letters (a-i) For some reason,even when i input the proper letters, it loops forever.
I've tried using switch cases as well as != inside the comparison.
Here is my code:
do {
System.out.println("Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
lL1=in.nextLine();
if (!lL1.equals("a")||!lL1.equals("b")||!lL1.equals("c")||!lL1.equals("d")||!lL1.equals("e")||!lL1.equals("f")||!lL1.equals("g")||!lL1.equals("h")||!lL1.equals("i")){
System.out.println("Invalid Input. Try again.");
}//End if statement
}while(!lL1.equals("a") || !lL1.equals("b") || !lL1.equals("c") || !lL1.equals("d") || !lL1.equals("e") || !lL1.equals("f") || !lL1.equals("g") || !lL1.equals("h") || !lL1.equals("i"));
My skills in Java are limited but this should work, unless i'm missing something obvious. Any help would be amazing!
Instead of using an operator for each case of the input, you might want to create a list of the accepted answers and then your condition will look like:
while answer is not in accepted answers, ask another input
An example would be:
Scanner scanner = new Scanner(System.in);
List<String> acceptedAnswers = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i");
String input;
do {
System.out.println(
"Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
input = scanner.nextLine();
} while (!acceptedAnswers.contains(input));
scanner.close();
System.out.println("Got correct input: " + input);
If you have a negation you need AND to join the conditions not OR.
That's because if you or some not-ed values, they form an and.
Let me explain better.
If you input a, then the first is false (because you not it), and the others are true, so the or condition make the result be true.
You should instead group all the ors and then not it.
e.g.
!(lL1.equals("a") || lL1.equals("b") || lL1.equals("c") || lL1.equals("d") || lL1.equals("e") || lL1.equals("f") || lL1.equals("g") || lL1.equals("h") || lL1.equals("i"))
Please try this:
char lL1;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
lL1=scanner.next().charAt(0);
}while(lL1!='a' && lL1!='b' && lL1!='c' && lL1!='d' && lL1!='e' && lL1!='f' && lL1!='g' && lL1!='h' && lL1!='i');
Since you are only getting a single character, you can check that it does not match either [a to i] characters as shown above. This is the shortest way to do so by making the check as the condition of the loop. If it fails then the loop will be called.

Do while string validation (with multiple strings)

For some reason, when I have multiple correct strings, the statement keeps repeating
do {
System.out.println("Enter Service Code");
Scanner a = new Scanner(System.in);
serviceCode = a.nextLine();
} while (!serviceCode.equals("ORB1") || !serviceCode.equals("ORBH") ||
!serviceCode.equals("ISS5") || !serviceCode.equals("ILLOYDS") ||
!serviceCode.equals("DLAB") || !serviceCode.equals("LEOM7") ||
!serviceCode.equals("MOON2"));
However, when there's just one string that the code checks against. The do while statement works fine and will stop looping when the correct input is entered
do {
System.out.println("Enter Service Code");
Scanner a = new Scanner(System.in);
serviceCode = a.nextLine();
} while (!serviceCode.equals("ORB1"));
If you enter "ORB1", "!serviceCode.equals("ORB1")" will return false but the others will return true; and you are using the "OR" operator. So, this sentence :
!serviceCode.equals("ORB1") || !serviceCode.equals("ORBH") ||
!serviceCode.equals("ISS5") || !serviceCode.equals("ILLOYDS") ||
!serviceCode.equals("DLAB") || !serviceCode.equals("LEOM7") ||
!serviceCode.equals("MOON2")
will always be true. You need to use the "AND" operator
!serviceCode.equals("ORB1") && !serviceCode.equals("ORBH") &&
!serviceCode.equals("ISS5") && !serviceCode.equals("ILLOYDS") &&
!serviceCode.equals("DLAB") && !serviceCode.equals("LEOM7") &&
!serviceCode.equals("MOON2")
Your comparison can never return false. it's either A or B.
so, if you were to say:
if ( !A OR !B ){
--> Input = A => true (because !B returns true)
--> Input = B => true (because !A returns true)
--> Input = C => true (because !A returns true)
Change your OR (||) by AND (&&)
Also: declare and instantiate your Scanner before your loop.
A better approach would be create a Listof string which includes the valid codes and check if that list contains the provided user input.
List<String> validServiceCodes = Arrays.asList("ORB1", "ORBH", "ISS5", "ILLOYDS", "DLAB", "LEOM7", "MOON2" );
do {
System.out.println("Enter Service Code");
Scanner a = new Scanner(System.in);
serviceCode = a.nextLine();
} while (!validCodes.contains(validServiceCodes));

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.

How to make a x = y or z statement in Java

In my program, I have a String called yesOrNo that is a keyboard input. I created an if statement to test if yesOrNo is one of the following : "Y", "y", "Yes",
"yes" by using the || operator.
I got the error message: The operator || is undefined for the argument type(s) java.lang.String, java.lang.String. What is the right way to do something like this? Thanks.
Scanner keyboard = new Scanner(System.in);
String yesOrNo = keyboard.nextLine();
System.out.println(yesOrNo + "?" );
if (yesOrNo.equals("Y" || "y" || "Yes || "yes")){
The shortest I can think of is :
if (yesOrNo.equalsIgnoreCase("Y") || yesOrNo.equalsIgnoreCase("Yes"))
Your syntax is invalid. It needs to have separate clauses:
if(yesOrNo.equals("Y") || yesOrNo.equals("y")...)
or cleaner would be if you used regex:
if(yesOrNo.matches("Y|y|Yes|yes")) {
// Code.
}
Extra Reading
You should look at the String Docs. They detail all sorts of useful stuff.
Read up on Regex. It makes complex String comparison very simple.
Finally, look at the different Operators to see what kind of logical statements you can form, with the correct syntax.
Alternatively, you could create a list of acceptable answers and check whether the answer is in that list.
List<String> kindOfYes = Arrays.asList("yes", "y", "okay", "righto");
if (kindOfYes.contains(yesOrNo.toLowerCase())) { ...
Two ways:
Using equals:
if (yesOrNo.equals("Y") ||
yesOrNo.equals("y") ||
yesOrNo.equals("Yes") ||
yesOrNo.equals("yes")) {
//...
}
Using regexp (shorther than using || multiple times):
if (yesOrNo.toLowerCase().matches("y|yes")) {
//...
}
Try:
if(yesOrNo.equals("Y") || yesOrNo.equals("y")
|| yesOrNo.equals("Yes") || yesOrNo.equals("yes"))
if (yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes") || yesOrNo.equals("yes"))
What about the next code?
String yesOrNo = keyboard.nextLine();
if (yesOrNo.toLowerCase().charAt(0) == 'y') {
//
}
NOTE: Do you think there's a quicker way? I think not.
Like this:
if (yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes") || yesOrNo.equals("yes")){
//...
}
Your program syntax is wrong.
This is correct:
Scanner keyboard = new Scanner(System.in);
String yesOrNo = keyboard.nextLine();
System.out.println(yesOrNo + "?" );
if(yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes") || yesOrNo.equals("yes")) {

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
}

Categories