Do While Questions [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Ok, I'm taking a Comp. Prog. class at my high school and the teacher that "teaches" the class knows practically nothing about programming. I joined the Java UIL team and am teaching the class with curriculum from some college website. Anyways, I started writing a Body Mass Index Calculator yesterday, and have had success but my problem is that I want to have a println prompt to run the program again after the calculations have been completed. Now, I have learned the Do While loop for this occasion, but my problem is with the scanner. I want to receive input as a string but when I do
String a = sc.nextLine();
outside of the do, it says that y or yes, cannot be resolved to a variable. A friend suggested switch cases, what do you think? I use Eclipse BTW.
String a = sc.nextLine();
do{
wow(); //My method name
}while(a == y); //Error is here

To compare objects in java use .equals() method instead of "==" operator
Use while(a.equals("y")); instead of while(a == y);

while(a == y);
This will never work for two reasons:
== compares references, not the contents of the object. So here it is only checking that a and y point to the same object, not that they contain the same thing.
You have not declared y anywhere. I'm assuming that you want to compare a against the literal string "y", in which case you should be using a.equals("y").
Your loop can be structured like this:
String input;
do {
wow();
input = scanner.nextLine();
} while(input.equalsIgnoreCase("y")); //using equalsIgnoreCase because user
//can input "y" or "Y".

Related

JAVA trying to find positions of the year. Not Working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have a small program that reads a json file that gives the
weather, time, temp, wind, ect. I need to calculate the average
tempature for 2009 through 2015. The years are in an array, and are in
length, around 60k. I am trying to write a small loop that will first
find the position of the first instance of the year 2009 and then
the last instance of the year 2009. Then I can run my
average temp loop through that, but I am running into an issue as seen
below.
place will be the index of the array. However, no matter how I run my
code, it always equals -1, rather than giving me the position of
the index in the array. Both arguments in the if statements are
strings.
So what am I doing wrong?
String twozerozeronine = "2009";
int place = -1;
for (int a = 0; a < years.size(); a++){
if (years.get(a) == twozerozeronine){
place = 1;
break;
}
}
System.out.println(place);
years.get(a) == twozerozeronine
checks whether the object on the left side of the operator and the object on the right side of the operator are the very same. In your case they might be similar, but will never be the very same.
You will need to check whether they are similar instead:
years.get(a).equals(twozerozeronine)
You can use equals() method to compare the value of the Strings.
Like: if ( years.get( a ).equals( twozerozeronine ) ){
The == operator compares the Object references (in your case, both are not equal) whereas equals() method compares the actual string values (in your case, the string values are "2009").

Trying to find a true condition for an empty record [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
OK. Im reading all the objects from an arraylist and grabbing thier names.
for(Contractor o : fa.allValues){
System.out.println(o.getName());
}
This returns
Bobs Tools
//The problem
Ic Remodeling
Fred and Nobby
Dogs With Tools
Dogs With Tools
Bitter Homes and Gardens
Etc etc
Now....when i create and add an object, i want to put the new object in any empty spaces that it finds. It should find an empty space when it comes to the 2nd record.
However........
String str = allValues.get(1).getName(); // where 1 is the location of the empty record
all the following returns false
System.out.println(str == "");
System.out.println(str == " ");
System.out.println(str == null);
I want to input a condition that returns true. What basic issue have i over looked here?
use equals for testing equality of string and not ==
Your equality for an empty string is wrong. In java you should compare it using the equals-method.
I would recommend using the apache commons lang StringUtils.isEmpty() method.

Can't get java to recognize when input is 'quit' which is supposed to end the loop/program [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Here's my code. I'm super noobie so don't flame me too hard haha. I've tried a few different ways, and looked at numerous posts and sites about how to close loops. I think the problem is that (i==("quit")) is not recognizing when the user types in quit. It just loops infinitely through making me input a new word and telling me it's the wrong word.
heres the code.
package monty;
import java.io.*;
import java.io.Console;
import java.util.Arrays;
import java.io.IOException;
import java.util.Scanner;
public class firsttry2 {
public static void main(String[] args) {
System.out.print("Enter the word 'quit' to end this program. Otherwise, it will run indefinitely.");
int x=0;
Scanner in=new Scanner(System.in);
while (x<1) {
String i;
i=in.next();
if (i==("quit")) {x++; in.close(); break;}
else {System.out.print("You did not enter the word 'quit'. Please try again .");
}
}
}
}
thanks for any help you guys can give me! I also tried it with while (true) and couldn't get that to work either. same result, doesn't recognize when i type 'quit'.
best alternate would be i.equals("quit") instead of i==("quit")
The reason is == and equals() are not same.Below explains the difference
== checks for identity. That is whether the two objects are the same object and point to the same address in memory.
.equals() by default does the same thing, but can be overridden to perform different equality comparisons. (i.e. strings are considered equal if they have the same characters in the same order)
If you want users can also write quit or Quit then instead of equals() you can also use equalsIgnoreCase()
You have made the very common mistake of using the == operator to compare strings in Java. You need to use the equals() function. You can learn more about it here.

Simple Java If/Else if Statement Unfunctional [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I was working on my game I am making, when I came across an error. My if/else if statement skips right to the else if statement, even if it shouldn't.
String neededCredits = "200";
if(Peeamnt.getText() == neededCredits) {
System.out.println("You can afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You have unlocked the Poop Button for 200 Pee Credits!",
"Toilet Master",
JOptionPane.WARNING_MESSAGE);
}
else if((!(Peeamnt.getText() == neededCredits))) {
System.out.println("You cannot afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You do not have enough Credits to buy this!\n"
+ "To buy it, you need 200 Pee Credits!",
"Toilet Master",
JOptionPane.ERROR_MESSAGE);
}
Even if the text of Peeamnt is an even 200, the code will jump to the else if statement, telling me that I don't have 200 Pee Credits. (The game I am making included a lot of toilet humor.) Anyway, if anyone sees the error I have in this code, please let me know. Let me know if you need more code.
With a Java String object, the == operator doesn't compare the string value.
Try changing the first if comparison to:
if(Peeamnt.getText().equals(neededCredits)) {
You will need to do something similar for the else if as well.
Strings are objects. Objects have a reference. Two String objects containing the same sequence of characters may not be the same object, thus having different references. The == operator (generally) checks for reference equality.
To compare the character sequence of two String objects for equality, you have the equals method. So use Peeamnt.getText().equals(neededCredits) instead.
String is an Object. Comparing Object, you have to use equals to judge whether the Object content is same. Using == is to compare Object reference
Use equals method to compare String object, because == operator means you compare object base on memory address. Always remember to never use == to compare objects in Java.
Try to use equals method if the getText() returns a string don 't use == sign. I suppose that getText() returns aString` object.
FYI: Double equal sign is used to see if two Objects are the same
and TO check if the objects has the same value equals() method should be used. Note: The objects that You compare with equals() should override it otherwise the results are corrupted, and the last thing when You overridesequals() method remember to override hashCode() too.
Use method equals to compare String object, because == operator means you compare object base on memory address.
* never use == to compare object.
String neededCredits = "200";
if(neededCredits.equals(Peeamnt.getText()) {//compare following you never see, because nullPointerException "neededCredits" always has value :-)
System.out.println("You can afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You have unlocked the Poop Button for 200 Pee Credits!",
"Toilet Master",
JOptionPane.WARNING_MESSAGE);
}
else if((!(neededCredits.equals(Peeamnt.getText()))) {
System.out.println("You cannot afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You do not have enough Credits to buy this!\n"
+ "To buy it, you need 200 Pee Credits!",
"Toilet Master",
JOptionPane.ERROR_MESSAGE);
}

Why is not "Ellie" == "Ellie", when one of them was read from the user? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
The following question is from a quiz I took a few weeks ago and got incorrect, but the answer wasn't provided:
Consider the following code, which contains no compile errors:
String secret = "Ellie";
Scanner kb = new Scanner(System.in);
System.out.println("Guess which name I'm thinking of:");
String guess = kb.next();
if (guess == secret)
{
System.out.println("Wow! You're smart!");
}
else
{
System.out.println("Wrong!");
System.out.println("You guessed: " + guess);
System.out.println("The correct answer was: " + secret);
}
Suppose the user enters "Ellie" at the prompt.
What output would result, and why that output and not the other output?
Here was my incorrect answer:
The output would be the else statement "WRONG!" because of the capitalization of the letter 'E'. A solution to this would be
to either change the String secret to "ellie" as well as the user's guess, or one can write in the ignoreCase keyword to
String secret.
The program actually outputs "Wrong", I tested it.
Aside from simply knowing the answer, could someone really explain this to me so I can understand the concept better?
The == does a reference comparison, and so it'll always say 'Wrong!', even if the two string references are equal. In order for it to match correctly, it would have to use secret.equals( guess ).
In java:
the == operator tests if the two objects are the same exact instance
the .equals() method of String compares if the objects "have the same value"
Since the user input the value, it's a new instance of String, so it will never be true that secret == input.
You should always use str1.equals(str2) when comparing Strings.

Categories

Resources