Java While loop won't loop [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
package pack;
import java.util.Scanner;
public class Calculator {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
String cont = "Yes";
while(cont == "Yes" || cont == "yes" ){
System.out.print("Enter a Number: ");
int x = scan.nextInt();
System.out.print("Enter another Number: ");
int y = scan.nextInt();
int diff = x - y;
int sum = x + y;
int prod = x * y;
int quot = x / y;
System.out.println("The Sum is: " + sum);
System.out.println("The Diffrence is: " + diff);
System.out.println("The Product is: " + prod);
System.out.println("The quotient is: " + quot);
System.out.print("Enter Yes to Continue: ");
cont = scan.next();
System.out.println(cont);
}
}
}
This entire code works, but the while loop doesn't repeat. The cont = scan.next(); is catching the string. The output looks like this:
[
Enter a Number: 5
Enter another Number: 6
The Sum is: 11
The Diffrence is: -1
The Product is: 30
The quotient is: 0
Enter Yes to Continue: Yes
Yes
]
Then the program terminates without any problems. All I need it to get the while loop to repeat. Thanks for the help!

Compare Strings with .equals instead of ==
while(cont.equals("Yes") || cont.equals("yes") )
Or even better:
while(cont.equalsIgnoreCase("Yes"))

You need to need to compare the Strings this way:
while("Yes".equalsIgnoreCase(cont))...
That's because when using input, you won't have String literals, but String objects. Those need to be compared via equals() and not ==.

Change
while(cont == "Yes" || cont == "yes" ){
As
while(cont.equalsIgnoreCase("Yes"))
Reason
You need to know the reason behind == and equals()
equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects!. That means, the contents of the objects. Whereas the == operator is expected to check the actual object instances are same or not.
Example with if statement
Consider two different reference variables str1 and str2
str1 = new String("abc");
str2 = new String("abc");
if you use the equals()
System.out.println((str1.equals(str2))?"TRUE":"FALSE");
You will get the output as TRUE
if you use ==
System.out.println((str1==str2)?"TRUE":"FALSE");
Now you will get the FALSE as output because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() everytime a new object is created.

instead of (cont == "Yes" || cont == "yes" ) you should use (cont.equals("Yes") || cont.equals("Yes"))

change to this
while(cont.equalsIgnoreCase("Yes"))

Related

An error with for loop

I am working on problem of string manipulation.Following is my code snippet.
I am really not sure why my code control is not going inside IF loop.
public class test{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int searchVariable = scan.nextInt();
int numberOfValues = scan.nextInt();
scan.nextLine();
while (numberOfValues-- != 0) {
String strg = scan.nextLine();
String[] arrayInt = strg.split(" ");
for (int i = 0; i < arrayInt.length; i++) {
// System.out.println("test 1===");
// System.out.println("i value" + i);
// System.out.println("i " + strg.charAt(i));
// System.out.println(searchVariable);
if (searchVariable==strg.charAt(i)) {
System.out.println("===>");
System.out.println("index " + i);
return;
}
}
}
}
}
Input
4
6
1 4 5 7 9 12
Output
output should be 4.
As i am writing this code for finding integer 4 in the third line of input.
Problem
Program control is not going inside the loop if (searchVariable==strg.charAt(i))
.Please help!!
The is problem in your logic: What you actually want is
if (searchVariable==Integer.parseInt(arrayInt[i]))...
When java compares different objects, it checks different aspects, one of them is their type.
For example, the char '1' is different from the integer 1 and therefore '1'==1 will return false.
char c = '1';
System.out.println(c==1); //false
When comparing char to integer you should use parsing or the method Character.getNumericValue(c):
System.out.println(Character.getNumericValue(c)==1); //true
Also note that when java compares char to integer it uses the ascii value of the char, therefore ,char 'a' equals to the integer 97 and '1' equals integer value of 49: (and so on..)
System.out.println(c==49); //true

Simple java console calculator

Without directly giving me the answer can someone help me with this simple calculator that I am trying to write?
Everything seem to work well except for the very end when I ask the user to make a choice for add,subtract, multiply, or divide. It does not allow me to enter my choices in the console.
I think it has something to do with the array of String that I created and the if statement. Not sure. Any tips would be much appreciated.
import java.util.Scanner;
public class simpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//declare my variables
int firstNum;
int secondNum;
int division = 0, addition = 0, subtraction = 0, multiplication = 0;
String userChoice = "";
String choices[] = {"add","multiply","divide","subtract"};
//ask for user input
System.out.print("Please enter first number: ");
firstNum = input.nextInt();
System.out.print("Please enter second number: ");
secondNum = input.nextInt();
System.out.println("What type of operation would you like to perform on these numbers?");
System.out.println("add " +"multiply " +"subtract " + "divide ");
userChoice = input.nextLine();
if (userChoice == "add"){
System.out.print("Answer = " + addition);
}
//calculator formulas
addition = firstNum + secondNum;
multiplication = firstNum * secondNum;
subtraction = firstNum - secondNum;
division = firstNum / secondNum;
}
}
nextInt() reads just the number and not the end of the line after the number. You will need a nextLine() after each nextInt() to consume the rest of the line.
Also, before you beat your head against the wall the following statement won't work for you:
if (userChoice == "add")
== tests for reference equality.
.equals() tests for value equality. So you need something like this instead:
if (userChoice.equals("add"))
I wanted to give you that freebie because I love your attitude that you don't want anyone to give you the answer. That is great that you wan to learn it. Keep up the good work.
Saying that String a == String b means that you're comparing two strings to see if they have reference equality, while saying a.equals(b) will compare the values stored in the string.
Reference equality is used to compare whether two object references point to the same object, which in this case you shouldn't be using as you're trying to compare whether the value of two variables are equal. So definitely go with
if(userChoice.equals("add"))

Need help - Java If/Else [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am fairly new to Java and am in need of help with my If/Else statement. Basically I want to make it so that if the person types in n or no do one thing, or if the person puts in y or yes, do another thing, and if the person doesn't put in n, no, yes or y than do a different thing. But no matter what the user puts in, it acts as if they did not put in n, no, yes or y. How can I fix this?
This is my code so far:
public class Main
{
public static void main (String[] args)
{
Scanner userInputScanner = new Scanner(System.in);
String [] charName = {"John", "Bob", "Sam"};
Random random = new Random();
int charNameChoice = random.nextInt(charName.length);
System.out.println("Random char selected: " + charName[charNameChoice]);
System.out.println("Y N Question1");
System.out.println("You can input y, yes, n or no");
String questionOneAnswer = userInputScanner.nextLine();
if (questionOneAnswer == "n" || questionOneAnswer == "no")
{
System.out.println("I disagree");
}
else if (questionOneAnswer == "y" || questionOneAnswer == "yes")
{
System.out.println("I agree");
}
else
{
System.out.println("Invalid");
}
}
}
You should use equals to compare String values, like stringVar.equals("something").
Better yet, reversing it "something".equals(stringVar) prevents Nullpointerexceptions.
== compares the pointers, which are almost never equal (unless you're comparing String constants).

Why is my condition never met? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Take a loot at the bottom in my for loop. It's probably a simple logical error but for some reason 'if' condition is never met. Sorry for asking basic stuff but I've searched and searched and can't seem to find the answer. Thanks for helping a noob.
Scanner scan = new Scanner(System.in);
System.out.println("How large would you like the array to be? (number)");
int arraySize = scan.nextInt();
scan.nextLine();
String [] myArray = new String [arraySize];
int i = 0;
if (arraySize <= 0 ) {
System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
} else {
while (i < myArray.length) {
System.out.println("Please type a string to be entered in the array");
myArray[i] = scan.nextLine();
i++;
}
System.out.println("Array contents: " + Arrays.toString(myArray));
}
System.out.println("What element would you like would you like to find in the array by performing a linear search?");
String search = scan.nextLine();
for (int j = 0; j < myArray.length; j++) {
if (myArray[j] == search){
int location = j + 1;
System.out.println("The element, " + search + " was found in the array, in which the linear search looped " + location + " times to find it." );
j = myArray.length;
}
}
You should always use .equals() and not == operator for String comparison. == operator will evaluate to true only when both the references are pointing to same String instance. To check whether String contents are equal you can use .equals() or equalsIgnoreCase().
So change your search condition from
if (myArray[j] == search)
to
if (myArray[j].equals(search))
You're using == instead of .equals which doesn't check if strings are equal. .equals will check that the values are equal, not just the reference numbers like this:
if( myArray[j].equals(search)){

Why does my java program skip a if statement? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
im only 15 and new to java so i am trying to build a simple calculator, but i cant seem to figure out why this if statement is being ignored. I have check to be sure that all values are being stored and yes they are so i can not see any other problems which would explain this. Any help would be great! Look for the comment in the second class //This if statement
The first class
public class CalculatorOperations {
double fnum, snum,answer;
String operation;
void plus(){
operation="+";
answer = fnum + snum;
}
void subtract(){
operation="-";
answer = fnum - snum;
}
void multiple(){
operation="*";
answer = fnum * snum;
}
void divide(){
operation="/";
answer = fnum / snum;
}
void invalidOperation(){
System.out.println("Invalid operation.");
}
void showAttributes(){
System.out.println(fnum);
System.out.println(snum);
System.out.println(operation);
}
}
The second class
import java.util.Scanner;
public class calculatorApplication {
public static void main(String [] args){
CalculatorOperations Operators = new CalculatorOperations();
Scanner userInput = new Scanner(System.in);
String loop2 = null;
boolean loop;
while (loop = true){
// Getting input and storing it
System.out.print("Please enter first number: ");
Operators.fnum = userInput.nextDouble();
System.out.println("TEST:"+Operators.fnum);
System.out.print("Please enter second number: ");
Operators.snum = userInput.nextDouble();
System.out.println("TEST:"+Operators.snum);
System.out.print("Please enter operation (+, -, * or /): ");
Operators.operation = userInput.next();
System.out.println("TEST:"+Operators.operation);
// this if statement
if (Operators.operation == "+") {
Operators.plus();
} else if (Operators.operation == "-") {
Operators.subtract();
} else if (Operators.operation == "*") {
Operators.multiple();
} else if (Operators.operation == "/") {
Operators.divide();
} else {
Operators.invalidOperation();
}
System.out.println("Answer: " +Operators.answer);
System.out.print("Would you like to do another sum? (yes or no): ");
loop2 = userInput.next();
}
if (loop2.equals("yes") || loop2.equals("Yes")){
loop = true;
System.out.println();
System.out.println();
}else{
loop = false;
// Closes scanner to prevent resource leaks
userInput.close();
System.exit(0);
}
}
}
Comparing Strings with == generally doesn't work the way you'd like it to. It's because Strings are Objects and == compares object references against each other, instead of checking if the Strings contain identical text.
Try String.equals instead:
if (Operators.operation.equals("+")) {
... //and of course the same for the rest of the statements
Good luck with your program!
Use the .equals(String) method, instead of ==. Your if-structure would change to this:
if (Operators.operation.equals("+")) {
Operators.plus();
} else if (Operators.operation.equals("-")) {
Operators.subtract();
} else if (Operators.operation.equals("*")) {
Operators.multiple();
} else if (Operators.operation.equals("/")) {
Operators.divide();
} else {
Operators.invalidOperation();
}
.equals(String) is used for comparing strings, whereas == is used for comparing everything else pretty much. == is comparing the reference to an object and .equals(String) is used to compare String values.
Also, change while (loop = true) to while(loop) or while (loop == true); otherwise you are indicating that you are actually changing the value of loop.
You don't want to compare strings with == because by doing that you're comparing the reference of the string, and not the value of the string. You need to use the .equals method.
if (Operators.operation.equals("+"))
From the javadoc:
boolean equals(Object anObject)
Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.
Also, you need to change
while (loop = true)
to
while (loop)
= is the assignment operator, == is the comparison operator.

Categories