Java: not exiting while loop? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
import java.util.Scanner;
public class OrigClass {
public static void main (String[] args){
Scanner ScanObj = new Scanner(System.in);
System.out.println("Set Password: ");
String SetPass = ScanObj.nextLine();
System.out.println("Guess Password: ");
String GuessPass = ScanObj.nextLine();
while (GuessPass != SetPass){
System.out.println("Incorrect. Try Again: ");
GuessPass = ScanObj.nextLine(); }}}
So as you can see I'm trying to make a very simple program that lets the user enter a password then re-enter it. I'm a little confused as to why this isn't working. I've tried everything I can think off and have read up on other similar problems on here, but can't find anything...
Sorry if this is a bit basic, but it's annoying me that I can't get this to work :(

You should compare the string with String.equals
so your code should look like this :
while (!GuessPass.equals(SetPass)){
and as mentionned in the comments I'd change the name of your variables to match the Java standards (camelCase for local variables and methods) , so to sum up :
while (!guessPass.equals(setPass)){

When comparing strings use String.equals("some string").
while(!guessPass.equals(setPass)){
//do something
}
I included changes to your variable names. Standard for variables is first word lowercase and all subsequent words uppercase (first letters). This will help you and your peers understand your code. Hope this helps.

Here is the fix for you. You need to use dot equal when comparing strings.
public static void main(String[] args) {
Scanner ScanObj = new Scanner(System.in);
System.out.println("Set Password: ");
String SetPass = ScanObj.nextLine();
System.out.println("Guess Password: ");
String GuessPass = ScanObj.nextLine();
// the fix
while (!GuessPass.equals(SetPass)){
System.out.println("Incorrect. Try Again: ");
GuessPass = ScanObj.nextLine(); }}
}

Related

Why doesn't this If statement properly compare the stored variable with an element in an array? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 12 months ago.
So i'm just doing some elementary testing while I learn java, and i'm curious why this doesn't work:
public static void main(String[] args) {
String[] names={"John","Mark","Suzy","Anthony"};
String[] passwords={"passw0rd","CandyC4ne","x5021","ADawg55"};
System.out.println("Please indicate which user you would like to log in as:\n(1)John\n(2)Mark\n(3)Suzy\n(4)Anthony");
Scanner x=new Scanner(System.in);
int y=x.nextInt()-1;
System.out.print("Please enter the password to log into "+names[y]+"'s account: ");
Scanner a=new Scanner(System.in);
String newpass=a.nextLine();
System.out.println(passwords[y]);
if(passwords[y]==newpass){
System.out.print("Hello "+names[y]+"!");
}else{
System.out.println("Incorrect Password. "+passwords[y]+" "+newpass);
}
}
Both passwords[y] and newpass are the exact same string, and when I try:
if(passwords[y]=="passw0rd");
(And obviously pick the 'John') it does work, so i'm hoping someone can explain the difference and how to get around it so as to better accept user input.
Also i'll take a for loop as an answer, but i'm hoping I can avoid it.
never use == to compare strings. Always use equals or equalsIgnoreCase methods. == will check both references pointing to the same object and equals will check the content of the strings.
Use equals or compareTo method to compare to two Strings instead of == which compares reference.
import java.util.*;
public class Password{
public static void main(String[] args) {
String[] names={"John","Mark","Suzy","Anthony"};
String[] passwords={"passw0rd","CandyC4ne","x5021","ADawg55"};
System.out.println("Please indicate which user you would like to log in as:\n(1)John\n(2)Mark\n(3)Suzy\n(4)Anthony");
Scanner x=new Scanner(System.in);
int y=x.nextInt()-1;
System.out.print("Please enter the password to log into "+names[y]+"'s account: ");
Scanner a=new Scanner(System.in);
String newpass=a.nextLine();
System.out.println(passwords[y]);
if(passwords[y].equals(newpass)){
System.out.print("Hello "+names[y]+"!");
}else{
System.out.println("Incorrect Password. "+passwords[y]+" "+newpass);
}
}
}
Output:
$ javac Password.java && java Password
Please indicate which user you would like to log in as:
(1)John
(2)Mark
(3)Suzy
(4)Anthony
1
Please enter the password to log into John's account: passw0rd
passw0rd
Hello John!

#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

Basic program for a learning programmer [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
So I just started taking my first classing in programming with Java, so don't hurt me for being a new guy. I understand this may be a simple thing to do, but I'm stuck on where to even begin. I want to make a program that simply counts the number of characters in a string using the Scanner utility. So far I have...
import java.util.scanner
class Counter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence, and I will tell you how many
characters are in it.");
String sentence = input.nextString();
And this is as far as I have gotten. What I want to do is the previous plus...
Char character;
and do something with that, maybe a for-loop, but I'm simply stumped.
And even if I did want to do this I wouldn't know how to go about it. Any ideas?
Thanks!
~Andrew
EDIT:
import java.util.Scanner;
class Counter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence, and I will tell you how many
characters are in it.");
String sentence = input.nextLine();
sentence = sentence.trim();
System.out.print("This sentence has " + sentence.length() + "
characters in it.");
}
}
Did not seem to work.
You have to use input.nextLine() instead of input.nextString() to capture the sentence given by the user.
You also have to use the trim() method on that sentence to delete the spaces given by the user in the front and back side of the sentence.
Ex: sentence.trim()
You can get the length of the sentence by the length() method.
Ex: sentence.length()
Now, I am giving you the full code to count letters of a given sentence:
import java.util.Scanner;
public class LetterCount
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence, and I will tell you how many characters are in it.");
String sentence = input.nextLine();
System.out.print("This sentence has " + sentence.trim().length() + " characters in it.");
}
}
First of all, to read by Scanner you have to use input.nextLine(); instead of input.nextString();.
After, you can use .length() function to know how much positions have your String (how much chars have your String) so you won't have to convert it to any char or whatever.
System.out.println(sentence.length());
I expect it will be helpful for you!

Need to fix program in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I want user to input text while it is not equal to "start".When it is equal to "start" I want to show "Bravo".In my code when I enter "start" it just continue to ask to input a text.What is missing in my code to process the operation i described.
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String komanda = "a";
do {
System.out.println("Unesi komandu ");
komanda = input.nextLine();
}
while(komanda != "start");
System.out.println("Bravo");
}
}
You have to use the equals method to compare strings in java:
while (!komanda.equals("start"));
or even better
while (!"start".equals(komanda));
this does not crash if komanda is null
See How do I compare strings in Java? for more information.
do it this way
Scanner input = new Scanner(System.in);
String komanda = "a";
do {
System.out.println("Unesi komandu ");
komanda = input.nextLine();
}
while(!"start".equals(komanda));
System.out.println("Bravo");

I can't get out of this while loop [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This is the first section of my main method, where I prompt the users to input as many phrases as they want, and the input gets saved in an ArrayList. I coded this so that the program would stop asking for more input if the user puts 'q', but for some reason, when I run this, even if I input q, it doesn't exit the loop. It just keeps on asking for more inputs. I'm assuming I made a mistake in the while loop, but I'm not entirely sure what.
I'm really new to Java so I may have made a blatant mistake but I'm not sure..
public static void main(String [] args)
{
//vars
String userInput;
int quitter = 0;
//arraylist
ArrayList<RecursivePalindrome> a = new ArrayList<RecursivePalindrome>();
//scanner
Scanner in = new Scanner(System.in);
//user input
System.out.println("\t Palindrome Checker");
System.out.print("Input phrase one at a time (press 'q' to quit): ");
while(quitter == 0)
{
userInput = in.next();
if(userInput == "q" )
{
quitter++;
}
a.add(new RecursivePalindrome( userInput));
System.out.print("Input phrase one at a time (press 'q' to quit): ");
}
System.out.println();
Comparison of strings
use .equals
if(userInput.equals("q"))
{
quitter++;
}
Compare the String with equals() and put break it will exit the while loop
if(userInput.equals("q" ))
{
quitter++;
break;
}

Categories

Resources