I am a beginner.
I am experimenting with java while loop. I have knowledge of both java while loop and if statements but have never nested them before. I will first post the script and then tell you guys the problem.
here is the script:
import java.util.Scanner;
class whileloop{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.println("This is a basic calculator.");
System.out.println("To exit, input exit when asked to input the method.");
System.out.println("----------------------------------------------");
while (true){
System.out.println("to add, input '+', to subtract, input '-', to divide, input '/', to multiply, input '*' and to exit, input 'exit.'");
System.out.println("----------------------------------------------------");
System.out.print("Please enter a method here:");
String method = scan.nextLine();
if (method == "exit"){
System.out.println("You chose to exit.");
break;
}
else if (method == "+"){
System.out.println("You chose to add.");
System.out.print("Please enter first number here:");
double fnum = scan.nextInt();
System.out.print("Please enter second number here:");
double snum = scan.nextInt();
double ans = fnum + snum;
System.out.print("The answer is");
System.out.println(ans);
}
}
}
}
First of all, i have no knowledge about this type of nesting i am just experimenting right now so maybe that's why my method may seem a bit unusual to you people.
now, the problem is that whenever i execute this code, the infinite while loop works perfectly but it always skips the if statement no matter what i input and starts to loop the instructions again.
please help me with this.