Program Keeps Out Printing Both Messages - java

I have some code going on here, I'm trying to get the user to input a Letter,
Number, or a Symbol, I have them all working, but when I enter a Letter, it
outprints both the "You have entered a Letter" and "You have entered a
Symbol" But thing is, I never entered a Symbol in the first place, just a
Letter. Heres how it looks:
Enter a SINGLE character:
D
You entered a LETTER!
You entered a SYMBOL!
import static java.lang.System.*;
import java.util.*;
public class Java1304
{
public static void main(String[] args)
{
new Problem();
}
}
class Problem
{
char letter;
public Problem()
{
input();
process();
output();
}
void input()
{
Scanner scan = new Scanner(in);
out.println("Enter a SINGLE character:");
letter = scan.nextLine().charAt(0);
}
void process()
{
if(Character.isLetter(letter))
{
out.println("You entered a LETTER!");
}
if(Character.isDigit(letter))
{
out.println("You entered a NUMBER!");
}
if(!Character.isLetter(letter) || !Character.isDigit(letter))
//else
out.println("You entered a SYMBOL!");
}
void output()
{
out.println();
out.println();
out.println();
}
}

Your desired behavior is not reflected in the code you wrote. The statement !Character.isLetter(letter) || !Character.isDigit(letter) evaluates to true if either the character is not a letter OR not a number (as || is the logical operator for or).
Going back to your example, if you type "A", Character.isDigit(letter) evaluates to false, so !Character.isDigit(letter) evaluates to true, so !Character.isLetter(letter) || !Character.isDigit(letter) evaluates to true.
Based on your example, your if block could be better written as:
if(Character.isLetter(letter)){
out.println("You entered a LETTER!");
} else if(Character.isDigit(letter)){
out.println("You entered a NUMBER!");
} else {
out.println("You entered a SYMBOL!");
}

De Morgan's laws strike again! The || is your culprit. It needs to be && for your case.

Your second if statement is true because !Character.isLetter(letter) is true. The || is a logical or. That means if one of the statements is true it enters the if clause.
So just change the last if for an else and you should be fine.

Your problem is that last if statement- let's step through your use case there:
you enter D.
isLetter('D') is true so it prints
isDigit('D') is false so that doesn't print
!isLetter('D') && !isDigit('D') is the same as
! true || ! false (evaluating the method calls) which is the same as
false || true (evaluating the !'s) which is the same as
true (evaluating the ||) so it prints.
To fix it, you can change your || to &&, or put back the else clause you have commented out. I personally think the else clause is a better solution because it clearly communicates your idea that what's not a letter and not a digit must be a symbol without having to explicitly check for each one.

if(!Character.isLetter(letter) || !Character.isDigit(letter))
You used OR instead of AND, so letter "D" will pass when you check for !Character.isDigit(letter)
In the last if statement, change the || to &&.

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 use a boolean with two meanings within an if, nested if, else statement

Ok, So when I run the code, after typing in no or anything that which is false, my program doesn't jump to the Else statement at the bottom (Outside of the nested if_Else statement) What am I doing wrong? I tried initiating it with else if (yes!=true) or Else (!yes), I mean you name it, including changing the initial arguments and imputing ( yes==true ^ no==true) however, defining another boolean variable to no and set to true as well!
import java.util.Scanner;
public class Flights
{
public static void main(String args[]){
String txt;
boolean yes=true;
Scanner type=new Scanner(System.in);
int days;
System.out.println("Is this a round trip? ");
txt=type.next();
if(yes==true){
System.out.println("How many days in advance do you plan to book your flight?: ");
days=type.nextInt();
if(days>180)
System.out.println("Error: Flights can't be booked for more than 180 days out");
else if( days<=180 && days>=14)
System.out.println("Your flight cost is: $275");
else if(days<14 && days>=7)
System.out.println(" Your flight cost is: $320");
else if(days<7)
System.out.println("Your flight cost is: $440");
}
else
{
System.out.println("Enter your discount code");
}
}
}
Well, you initiate the yes variable to true, and didn't update it whatsoever before you start the conditional statement where you compare the value of yes to true. That's the issue.
This is where you begin:
boolean yes=true;
and then you wait for user typing in, but do not update the yes value, instead, you go ahead and check it like this.
if(yes==true){
}
This results in the else statement will never be reached.
What you could do is, following this line:
txt=type.next();
You can update the value of the yes variable, something like this:
txt=type.next();
yes = (txt != null) && "yes".equals(txt.toLowerCase());
if(yes==true){
//...
} else {
}
Hope this helps.
For your program to make a decision based on the user input, you have to look at the value of txt.
Change your code to something like this:
yes = txt.equalsIgnoreCase("yes");
if (yes == true) {
...
} else {
...
}
Or even shorter:
if (txt.equalsIgnoreCase("yes")) {
...
} else {
...
}

how to end a method in java through another method?

Here's my code:
public boolean isConsonant(char x){
if (!Character.isLetter(x)){
System.out.print ("What you have entered cannot be a consonant or vowel.");
return false;
}
return (x != 'a' && x != 'e' && x != 'i' && x != 'o' && x != 'u');
}
The problem I'm having is the first if statement. I call the isConsonant method multiple times in the code after this and depending on the return calue (true or false) the code does some action.
The problem is that I don't want the method to continue at all if the char isn't a letter. I want the program to end. What I tried to do is write another method that looked like this:
public voidisNotLetter(char x)
if (!Character.isLetter(x){
System.out.println("What you have entered cannot be a consonant or vowel.");
}
This is where I'm stuck. I don't know what I can put in that method that will stop the program from running and just print that statement to the user. I thought about throwing an IllegalArgumentException, but that's not technically true since the argument is valid but just isn't what I want.
If you want to "stop the program from running and just print that statement to the user", this might help :
if (!Character.isLetter(x)){
System.out.print ("What you have entered cannot be a consonant or vowel.");
System.exit(0); //This would terminate the execution if the condition is met
}
More details here. Hope it helps.
You can try nesting if statements.
if(isLetter(input)){
if(isConsonant(input)
//input is consonant
else
//input is not consonant
}else{
//input is not letter
}

Left hand side of an assignment must be a variable Error

Please don't mind the logic of the code; I just want help understanding the error, which seems to occur at the last else statement.
package day1.samples;
import java.util.Scanner;
public class Horscope {
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] Birth={"January","February","March"};
System.out.println("Please Enter Your BirthMonth");
Scanner input =new Scanner(System.in);
String X;
X=input.nextLine();
if (X==Birth[0]) {
System.out.println("Your Horoscope is Gemini");
} else if(X==Birth[1]) {
System.out.println("your Horscope is libra");
} else (X==Birth[2]) {
System.out.println("Your horscope is Leo");
}
}
You need to remove the else condition. Only else if can have condition. You can also change the last else to else if.
X=input.nextLine();
if (X.equals(Birth[0])) {
System.out.println("Your Horoscope is Gemini");
} else if(X.equals(Birth[1])) {
System.out.println("your Horscope is libra");
} else {
System.out.println("Your horscope is Leo");
}
Also you don't compare strings with == you should use .equals more details click here
EG:
X.equals(Birth[0])
It should be .equals
} else if (X.equals(Birth[2])) {
Here:
} else (X==Birth[2]) {
should be
} else if (X==Birth[2]) {
Besides == should not be used instead of equals method. I'm just answering about the cause of Left hand side of an assignment must be a variable error.
Else don't have condition checking part. Remove () in front of else.
Or
Use another ladder of else if simply put if before braces.
And other than logic use X.equals("some value") to compare values rather == compares references.
You don't need to specify the condition for the last condition in an if...else ladder. You can either use else if (condition) or just the else.
You are getting the error as your syntax is wrong by using else (condition). Hope this helps.
Also, you should always use the equals() method to check if two strings are equal as it compares the original content of the string. It compares the values of string for equality.
Hence, in your case it should be -
X.equals(Birth[2])

What's wrong in this string comparison inside main method?

I am comparing a value of a string inside a main method, however, it keeps on saying that it is invalid.
Here is the code:
public static void main(String[] args) {
String a = "X";
if(!a.equalsIgnoreCase("X") || !a.equalsIgnoreCase("Z")){
System.out.println("invalid");
}
}
There is nothing wrong with your code.
public static void main(String[] args) {
String a = "X";
if(!a.equalsIgnoreCase("X") || !a.equalsIgnoreCase("Z")){
System.out.println("invalid");
}
}
Explanation:
a.equalsIgnoreCase("X") is true, and !a.equalsIgnoreCase("X") is false.
Since first condition is false, it evaluates the second condition.
a.equalsIgnoreCase("Z") is false, and !a.equalsIgnoreCase("Z") is true.
Second condition is true, hence "invalid" is printed.
Note: Maybe you should let us know what you are trying to achieve with the String comparisons, so that we can give you better feedback. Let us know what is the desired logic, i.e. what is valid, and what is not.
Based on the comment "Any letter that is not equal to "X" or "Z" should be invalid",
Answer:
if( !(a.equalsIgnoreCase("X") || a.equalsIgnoreCase("Z")) ) {
System.out.println("Invalid");
}
or its equivalent (as proposed by Fast Snail):
if( !a.equalsIgnoreCase("X") && !a.equalsIgnoreCase("Z") ) {
System.out.println("Invalid");
}
¬(X ∨ Z) ≡ ¬X ∧ ¬Z (De Morgan's Law)

Categories

Resources