character comparison not working - java

I have to write a program making a 2-D array and printing it out. Then I am supposed to guide a "character" through this maze. so I want to make it move Up/Down/Left/Right. The user would be allowed to type in u/U/d/D/l/L/r/R.
I put in so that it would give me an error if one of those was not typed in. However it still gives me an error if it is typed in correctly.
char move;
System.out.println("Which way do you want to move? U/D/L/R");
move=stdin.nextLine().charAt(0);
while(move != 'u' || move !='U') {
while( move != 'd' || move != 'D'){
while( move != 'l' || move != 'L'){
while(move != 'r' || move != 'R'){
System.out.println("Invalid input. Try again.");
move = stdin.nextLine().charAt(0);
}}}}

Try this:
Scanner stdin;
stdin = new Scanner(System.in);
move = stdin.nextLine().charAt(0);;
move = Character.toUpperCase(move);
while(move !='U' && move != 'D' && move != 'L' && move != 'R' )
{
System.out.println("Invalid input. Try again.");
move = stdin.nextLine().charAt(0);
move = Character.toUpperCase(move);
}
Your current code do not make sense. If I type R (for example), this would make the program to enter in infinite loop. Since, all the condition on the upper while would evaluate true. Thus, not reaching the instruction that will ask for another input (stdin.nextLine()).

You may also try the following (does the same thing in a different way).
Along with other field declarations:
private static final String keySet = "uUdDlLrR";
And inside the method:
char move = stdin.nextLine().charAt(0);
while (keySet.indexOf(move) == -1) {
System.out.println("Invalid input. Try again.");
move = stdin.nextLine().charAt(0);
}
It's just a bit more readable and requires little change in case you wish to modify the set of allowed keys.

The syntax is a little bizarre (why "while" and not "if"?.... and why nested?) ... but basically you want to be testing with '&&' not '||'.
In english: you want if input is not A and input is not B, then error. If you do "or" then it will always error because one of those nots will alway be true.
EDIT:
easy mistake to make --- for style/clarity, I'd suggest:
switch (move) {
case 'u': case 'U':
/*up code*/
break;
case 'd'' case 'D':
/*down code*/
break;
case 'l'' case 'L':
/*left code*/
break;
case 'r'' case 'R':
/*right code*/
break;
default:
System.out.println("Invalid input. Try again.");
break;
}

Related

Java loop confusion requiring assistance

So i need help, i am trying to input a Y/N program but it is not accepting a big 'Y' or 'N'. Also another thing that i am trying to do is after pressing 'Y'/'y' i am trying to get the program to loop back to the code written above. Example a program that displays '123' and do i need to continue? Y/N, if entered yes it goes back up to restart the program from scratch. Please help me.
System.out.println("continue? Yes or no ");
char check = s.next().charAt(0);
while (check != 'y' && response != 'n')// corrected this part, however need help with restarting the loop back to the first line of code in a loop {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
} if ((check == 'n') || (check == 'N')) {
// I tried (check == 'n' || check == 'N')
System.out.println("Program terminated goodbye.");
System.exit(0);
} else if (check == 'y') {
//need help with restarting the loop back to the first line of code in a loop
}
I think this is what you are looking for.
char check;
Scanner scanner = new Scanner(System.in);
do
{
//your piece of code in here e.g.
System.out.println("Printed 123");
System.out.println("Do you wish to continue?[Y/y] or [N/n]");
choice = scanner.next().charAt(0);
}while (check =='Y' || check == 'y');
System.out.println("Program terminated goodbye.");
A do-while loop runs at least once before the condition is checked and so when a user enters either Y or y, then the condition will be true, meaning that they wish for the loop to run again. If the user enters any other value, then the condition will become false since choice is neither Y nor y and the loop will terminate.
Use String.equals() to compare the value of strings, == compares the strings in memory.
If you want to check without case-sensitive, you should convert the char to a String, then do s1.equalsIgnoreCase(s2);
So
while(true) {
System.out.println("Continue? [Y/N]");
char check_char = s.next().charAt(0);
String check = Character.toString(check_char);
while(check.equalsIgnoreCase("y") && !response.equalsIgnoreCase("n")) {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
}
if (check.equalsIgnoreCase("n")) {
System.out.println("Program terminated goodbye.");
System.exit(0);
}
}
For returning to the first line, I used a while loop that loops forever.
To the end if it is n then exits, otherwise it returns back to the first line of the loop.

How to fix "error: bad operand types for binary operator '||' " in java

I want to end the loop after the correct input.
It's working with the code inside the comment but is not working when I use
|| operator. Is the first while equivalent with the second?
public static void main(String[] args)
{
char group, response;
Scanner sc=new Scanner(System.in);
do
{
System.out.println();
System.out.println("[1] Time for group A");
System.out.println("[2] Time for group B");
System.out.println("[3] Time for group C");
System.out.println("[4] Quit program");
System.out.print("Enter choice[1,2,3,4]: ");
response=sc.next().charAt(0);
System.out.println();
switch(response)
{
case '1': System.out.println("10.00 a.m ");break;
case '2': System.out.println("1.00 a.m ");break;
case '3': System.out.println("11.00 a.m ");break;
case '4': System.out.println("Goodbye! ");break;
default: System.out.println("Options 1-4 only!");
}
} //while(response!='4'&&response!='3'&&response!='2'&&response!='1');
while(response=='4'||response=='3'||response=='2'||response=='1');
I will expect to end the loop after the correct input in both cases.
To answer your question about the while loop condition directly (are the two conditions equivalent?):
No, they aren't equivalent, but it's only a small change needed. The following two conditions are equivalent by DeMorgan's Law.
boolean b1 = (response != '4' && response != '3' && response != '2' && response != '1');
// (note: I corrected what looked like a typo here ^^)
boolean b2 = !(response == '4' || response == '3' || response == '2' || response == '1');
So basically you have to add a ! before your second while loop condition to make them equivalent (assuming it really was a typo in the first one).
(Note: you still need to have the ! inside the while loop parentheses though, so it will look like while (!(...)))
Well java operator precedence hit you. Use braces:
while((response=='4')||(response=='3')||(response=='2')||(response=='1'))
Explanation:
Literals of type char( like '1') are integer numbers.
Now java evaluates your code for some weired reaseon like "( ... || response) == ..." and complains because "response" is a char and not a boolean. If you use braces you ensure the monoms are evaluated first and the "||" gets booleans as operands. My opninion is: in cases like the above you shouldn't get the error - but well, just uses braces and the error should go away.
Also the expresions are not equivalent. You get the equivalent by negeting each monom and the whole structure an toggle the operators.
The following is eqivalent to the above or:
while(!((response!='4')&&(response!='3')||(response!='2')&&(response!='1')))

Bad operand types for binary operator '||' - Java

I'm having trouble with a project, and I don't quite have the vocabulary to search for the issue I'm having. I think it has to do with syntax of Java regarding chars. Other than the code below, the input is taken as a string above and parsed into a char.
switch (accountType)
{
case 'c':
case 'C':
// Determine interest based on balance
if (balance >= 5000)
interest = balance * .03;
else
interest = balance * .01;
break;
case 's':
case 'S':
interest = balance * .04;
break;
default:
// Catch all for invalid account types
if (accountType != 'c' || 'C' || 's' || 'S');
validAccount = false;
}
Replace
if (accountType != 'c' || 'C' || 's' || 'S');
by
if (accountType != 'c' || accountType != 'C' || accountType != 's' || accountType != 'S')
But to be honest, the condition inside this if will always be true. Take for example, if accountType is c, the first condition will fail but others still pass, and since it's a logical OR, even one true is enough for the entire conjunction to return true. You can take any other value of accountType but it will always return true.
Also, you should remove the ; at the end of if statement for the sake of correct semantics. But you may remove the entire if as well.
Why are you using the last if condition?
I think it is unnecessary. All invalid accounts will fall to the default block automatically.
You have to write accountType every time for comparision:
if(accountType != 'c' || accountType != 'C' || accountType != 's' || accountType != 'S'){
//your code...
}
http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.24
"Each operand of the conditional-or operator must be of type boolean or Boolean, or a compile-time error occurs."
char is not boolean.
Too many or's hurting my head... Just use a string that contains what you want and see if the character is contained within it like so
String chars = "cCsS";
if(!chars.contains(accountType + ""))
validAccount = false;
While comparing, each time you have to compare against the variable:
if (accountType !='c'|| accountType !='C' || accountType != 's' || accountType !='S')
validAccount = false;
Replace your code with above one.
Note: Remove the ; at the end.
As mentioned in the comments, since it reaches the default case, you can assume it's a invalid account. So in your switch case
default:
validAccount = false
will suffice...

My else statement doesn't seem to function(JAVA)

import java.util.Scanner;
import static java.lang.System.*;
public class Whativelearned {
enum MyfirstEnum {one, two, three}
public static void main(String[] args) {
Scanner keyboardinput = new Scanner(in);
MyfirstEnum trolley;
char a1;
out.println("Do you pee in the shower"? Y/N");
a1 = keyboardinput.findWithinHorizon(".", 0).charAt(0);
if (a1=='Y'||a1=='y') {
trolley=MyfirstEnum.one;
out.println("Ewwwwwww");
}
if (a1=='N'||a1=='n') {
trolley=MyfirstEnum.two;
out.println("Well somebody isn't being very honest");
}else {
out.println("You're not so keen on following instructions, are you?");
}
keyboardinput.close();
}
}
I expect my else statement to cover all outcomes except for the cases in the if cases.
As I expect it to act as (!(a1=='Y'||(a1=='y'||a1=='n'||a2=='N'))
but when I run it the listing the else statement seems to be executed in all cases.
Try this
if (a1=='Y' || a1=='y') {
trolley=MyfirstEnum.one;
out.println("Ewwwwwww");
} else if (a1=='N' || a1=='n') {
trolley = MyfirstEnum.two;
out.println("Well somebody isn't being very honest");
} else {
out.println("You're not so keen on following instructions, are you?");
}
The else statement is always specific to one if statement. Therefore, your else clause is executed whenever the last if condition is not met.
To execute your clause only when none of the conditions are met, you need to change your if statements to else if like so:
if (a1 == 'y' || a1 == 'Y') {
// ...
} else if (a1 == 'n' || 'a1 == 'N') {
// ...
} else {
// ....
}
Another way to solve this would be using a switch statement. These are used to compare a variable to a set of constants. You can use them like this:
switch (a1) {
case 'y':
case 'Y':
// ...
break;
case 'n':
case 'N':
// ...
break;
default:
// ...
}
Please read up some more about the switch statement before you try it in other situations.
Just write else befor second for loop:
else if (a1=='N'||a1=='n') {
Code execution is best understood by a dry run.
If you do in your code you will find the first if statement is checked and if its true then its corresponding process is executed.
Now control moves down to execute the next if statement. This if statement checks the condition which os mutually exclusive of the above if. if its true (only in case above is false) then its corresponding process is executed and if its false then the else part process is executed.
You need to use if followed by if else followed by else

Why does my looped error message print out even though the condition set inside the loop is not satisfied

Here's a snip of my code:
while (true){
System.out.println("---Welcome to the Shape Machine---");
System.out.println("Available options:");
System.out.println("Circles");
System.out.println("Rectangles");
System.out.println("Triangles");
System.out.println("Exit");
//asks for selection
String option = console.next();
while (!option.equals("Cirlces") && !option.equals("Rectangles") && !option.equals("Triangles") && !option.equals("Exit")){
System.out.println("#ERROR Invalid option. Please try again.");
break;
}
switch (option) {
case "Circles": {
I have a menu set up and when the user inputs anything that isnt one of the options it's supposed to print out the error message and brings the user back into the menu. That works as intended, but if I put in a correct input the error message still prints out, but the switch statement runs as if there is no error and does the necessary calculations. I've tried using a while true loop within an if else statement and I still had the same problem. I also tried using an OR operator instead of an AND operator along with using a != instead of the !().equals method. I have no idea what to do to fix it. Any help would be very much appreciated.
I'm gonna go on a wild guess here and try to figure out what you were trying to accomplish.
Try this:
while (true){
System.out.println("---Welcome to the Shape Machine---");
System.out.println("Available options:");
System.out.println("Circles");
System.out.println("Rectangles");
System.out.println("Triangles");
System.out.println("Exit");
//asks for selection
String option = console.next();
switch (option) {
case "Circles":
//do something
break;
case "Rectangles":
break;
case "Triangles":
break;
case "Exit":
break;
default:
System.err.println("#ERROR Invalid option. Please try again.");
}
//now you can either put a flag or change the code to a DO..While
//depending on if you want to re-execute after each option..
}
If you want an if statement, you're gonna wanna do (to follow your version):
if (!option.equals("Cirlces") && !option.equals("Rectangles") && !option.equals("Triangles") && !option.equals("Exit")){
//print the error, then continue
}
or, easier to read
if( ! ( (option.equals("Circles") || option.equals("Rectangles") || option.equals("Triangles") || option.equals("Exit") ) ){
//print the error, then continue
}
Also please make sure that you're reading the right value, try printing it out and check.
If this doesn't work, there must be an error in the code you didn't provide, in that case please post a MCVE.

Categories

Resources