Java if statement (beginner request) [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
If someone can help me with this. I'm complete -n o o b, only started to learn and got stuck.
If I'm asking this -
Scanner buck = new Scanner(System.in);
String fname;
System.out.println("Please Enter your Name ");
fname = buck.next();
which command do I use to make specific name only to be entered as an answer.
For example name would be Vani.
If name is "Vani" than "you are in".
If any else name "than you go out".
I understand this with numbers but not with letters.
Any help would be appreciated.

To "kick out" if the name is not "Vani":
if("Vani".equals(fname)) { //You can use equalsIgnoreCase instead if you like
System.out.println("You are in.");
} else {
System.out.println("You are out.");
}
To accept input until "Vani" is given:
do {
System.out.println("Please Enter your Name ");
fname = buck.next();
if(!"Vani".equals(fname)) {
System.out.println("You're not Vani!");
}
} while(!"Vani".equals(fname));

if ("Vani".equals(fName)) {
// you go in
} else {
// cannot go in
}
And if you want case insensitive check, do "Vani".equalsIgnoreCase(fName).

Related

Menu-driven application using If-Else Statement - Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I am trying to create a menu-driven application that uses If-Else statement. Unfortunately, it always results in the Else or Exit message. What's wrong with my code? Thank you!
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("""
Good day!
Get to now Java programming language!
Please enter the letter that corresponds to your choice.
A. What is Java language
B. How to display a message
C. How to get users' input
E. Exit the program
Choice: """);
String choice = console.nextLine();
while (true) {
if (choice == "A") {
String WhatIs = "Java is a Object-Oriented Programming Language \n";
System.out.println(WhatIs);
} else if (choice == "B") {
String display = "Just use System.out.println \n";
System.out.println(display);
} else if (choice == "C") {
String GetUser = "Import the package and use the Scanner method \n";
System.out.println(GetUser);
} else {
String Exit = "Thank you for using this application.";
System.out.println(Exit);
break;
}
}
}
}
As the answer that #maloomeister mentioned in the comment:
Strings need to be compared via equals. So change choice == "A" etc., to choice.equals("A").
The detailed explanation is provided in this answer.

#Java Help. Creating a simple chatbot that enables user to create their own questions and answers [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am tasked to create a simple chatbot that enables a user to create questions and answers, which will then be stored into two arrays. Hence, whenever the user input the same question, the chatbot will be able to print out the answer.
For example, My intended run is:
Bot: 1st question that you want to create.
User: What is my name?
Bot: and the response is?
user: Tom
Bot: 2nd question that you want to create.
user: How tall am I?
Bot: and the response is?
You: 179cm
You: How tall am I?
Bot: 179cm
You: What is my name?
Bot: Tom
Below is my source code:
public static void main(String[] args) {
String reply = "";
String[] storeQuestions = new String [100];
String[] storeAnswers = new String [100];
do {
/* first question*/
System.out.println("Bot: 1st question that you want to create.");
Scanner input = new Scanner (System.in);
System.out.print("You: ");
String createQuestion = input.nextLine(); // change to string
System.out.println("Bot: and the response is?");
System.out.print("You: ");
String answer = input.nextLine();
/* storing question and answer into the two arrays */
storeQuestions[0] = createQuestion;
storeAnswers[0] = answer;
/* second question */
System.out.println("Bot: 2nd question that you want to create.");
System.out.print("You: ");
createQuestion = input.nextLine();
System.out.println("Bot: and the response is?");
System.out.print("You: ");
answer = input.nextLine();
storeQuestions[1]= createQuestion;
storeAnswers[1] = answer;
System.out.print("You: ");
reply = input.nextLine();
if(storeQuestions[0]==createQuestion) {
System.out.println("Bot: "+storeAnswers[0]);
}
else if ( storeQuestions[1]==createQuestion) {
System.out.println("Bot: "+storeAnswers[1]);
}
}while(reply!="bye");
}
}
The == operator compares the hash codes of the two objects. Since they might not be the same for two strings (even though, they are identical) you have to check character by character. A built-in method that can do this for you is String.equals(). If upper and lower case doesn't matter, you'd use String.equalsIgnoreCase().
Examples:
"test".equals("test") true
"TEST".equals("test") false
"TEST".equalsIgnoreCase("test") true

Alternate method to .hasNextInt? [duplicate]

This question already has answers here:
Check if String contains only letters
(17 answers)
Closed 7 years ago.
I'm new to java and I'm wondering if there is a different method that I can use instead of has.nextInt() as this method messes up my scanner. For example
do {
System.out.println("Please enter your full name: ");
memberName = input.nextLine();
if (input.hasNextInt()) {
System.out.println("Your name cannot contain a number");
input.next();
} else {
successful = true;
}
} while (successful == false);
console
Create new member
Please enter your full name:
jack
jack
I have to enter my name twice before it moves on
I know theres questions out there like this but I've had no luck with any of there solutions. Thanks
EDIT
I'm trying to make sure that the input does not contain any number at all and if it does then
System.out.print("Your name cannot contain any numbers");
happens
The usage of if(input.hasNextInt()){ is wrong here. As you want to find numbers in your previous entered string which is memberName
You could use regex for this purpose:
Pattern digitPattern = Pattern.compile("\\d+");
And then you can use this to validate any string:
System.out.println(digitPattern.matcher("Marcinek 234").matches());
do {
System.out.println("Please enter your full name: ");
memberName = input.nextLine();
if (memberName.contains("1234567890")) {
System.out.println("Your name cannot contain a number");
} else {
successful = true;
}
input.next();
} while (successful == false);
You were using input in your if-statement to check, but you assigned memberName to the whole line.
Try creating your own method which will test if passed name is valid. It can look for instance like this:
private static boolean isValidName(String name){
return name.matches("[a-z]+(\\s[a-z]+)*");//can be optimized with precompiled Pattern
}
Now your code can look like:
System.out.println("Please enter your full name: ");
do {
memberName = input.nextLine();
successful = isValidName(memberName);
if (!successful) {
System.out.println("Your name is not valid. Valid name can contain only letters and spaces. No digits are allowed.");
System.out.println("Please try again: ");
}
} while (!successful);
System.out.println("welcome: "+memberName);
If you want just read line from user input you can use:
hasNextLine()
Or you can just use:
hasNext()
And try to change this:
while (successful == false);
With this:
while (successful);
You could use: enteredName.contains("1") to check for numbers.
For example:
boolean containsNumbers = false;
for(int i = 0; i<9; i++){
if (name.contains(""+i)) containsNumbers = true;
}

Java: while loop doesn't return [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
New to Java, taking college course.
I am writing a program that asks users for their internet package so it can calculate their bill. Here's the snippet where I ask for their package, and have to confirm that they have answered either A, B, or C.
For some reason, it enters the while loop even if I enter "a"..
//Create Keyboard scanner
Scanner keyboard = new Scanner(System.in);
//Get user package
String servicePackage;
System.out.println("Enter your internet package: A, B, or C");
servicePackage = keyboard.nextLine();
servicePackage = servicePackage.toUpperCase();
System.out.println(servicePackage);//This line is for debugging
//Validate User Package Input
while (servicePackage != "A" && servicePackage != "B" && servicePackage != "C"){
System.out.println("Please enter a valid internet package (A, B or C)");
servicePackage = keyboard.nextLine();
servicePackage = servicePackage.toUpperCase();
System.out.println(servicePackage);//for debugging
}
System.out.println(servicePackage);//for debugging
Not sure if it's relevant, but I am using jGrasp.
Any help is appreciated!
"string" (declared) == "string" return false. You should use equals ("string".equals("string") return true) or equalsIgnoreCase (for example: "STRING".equalsIgnoreCase("string") return also true)

Difficulty With System Output [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 9 years ago.
So I'm fairly new to Java and I am trying to run a program that will display a certain number of letters from a name and ask the user for a response. The user's response should determine one of two answers ("Correct" or "I'm sorry, that's incorrect").
The problem I'm encountering is that when I run the program and put in the answer that should lead to "Correct," which is 'Billy Joel,' I get the response of "I'm sorry, that's incorrect."
I'm not actually sure what's going on, but here's a link to a picture of the CMD when I input what should lead the system to say "Correct" and instead it says "I'm sorry, that's incorrect":
And here is a copy of the relevant code:
System.out.println("\nLet's play Guess the Celebrity Name.");
String s6 = "Billy Joel";
System.out.println("\n" + s6.substring(2, 7));
Scanner kbReader3 = new Scanner(System.in);
System.out
.print("\nPlease enter a guess for the name of the above celebrity: ");
String response = kbReader3.nextLine();
System.out.println("\nYou entered: \n" + response + "\n");
if ((response == "Billy Joel")) {
// Execute the code here if Billy Joel is entered
System.out.println("\nCorrect!");
} else {
// Execute the code here if Billy Joel is not entered
System.out.println("\nI'm sorry, that's incorrect. The right answer was Billy Joel.");
}
System.out.println("\nThank you for playing!");
There's more before this that the program also does, but I'm not having a problem with any of that and it's all correct. I took out the Billy Joel part and everything else ran exactly as it was supposed to. It's just the above code in relation to what it should put out and what it is putting out that's the problem. I'm wondering if maybe I'm missing something in my code or I put something in wrong, but whatever I did, help would be much appreciated.
Your problem lies here. You are using wrong operator to compare strings
if ((response **==** "Billy Joel")) {
System.out.println("\nCorrect!");
} else { ... }
the correct should be
if ((response.equals("Billy Joel")) {
System.out.println("\nCorrect!");
} else { ... }
To compare strings in java you have to use .equals() operator. And to use '==' operator you need to have int, bool etc.
if (response!=null && response.length>0){
//trim the input to make sure there are any spaces
String trimmed=response.trim();
if (response.equals(s6))
System.out.println("\nCorrect!");
} else { ... }

Categories

Resources