I need help with Java - New to Java

import javax.swing.JOptionPane;
import java.util.*;

public class GUI{
 public static void main(String[] args)
     String fn = JOptionPane.showInputDialog("Enter first number");
     String sn = JOptionPane.showInputDialog("Enter second number");
     Scanner user_input = new Scanner("System.in");
     String operation;
     operation = user_input.next();
     JOptionPane.showInputDialog("Enter the operation you want to use. Operations: M, D, A, and S.");
    if (operation.equals("D && d")) {
     int num1 = Integer.parseInt(fn);
     int num2 = Integer.parseInt(sn);
     int sum = num1 / num2;
        System.out.println("The answer is " +sum);
    if (operation.equals("M && m")) {
     int num1 = Integer.parseInt (fn);
     int num2 = Integer.parseInt (sn);
     int sum = num1 * num2;
        System.out.println("The answer is " +sum);
    else {
        System.out.println("Syntax Error");

There is my code. So basically what happens is that, despite my input to change the variable “operation”, it just seemingly defaults to the else statement instead of carrying out the if statements to solve the problem… This is a calculator, not too hard, but again, I am new to Java.

"d" isn’t equal to "D && d" (the first one has a length of 1 while the second one has a length of 6)

You can use prints to follow along in what your code does. If you’ve got a debugger set up you could use that as well. You can also isolate the part that you’re experimenting with, put it in its own program while you figure out how it behaves.

1 Like

I am going to sound rude here, but trust me I am not trying to be. I know that d isn’t equal to D && d. I have also tried it with out the D && d with just the d, with still the same problem.

     -Thanks for your help

Right, but then you should probably remove the code that does that comparison.

You ask for things like “D”, “M”, “A”, “S”, so comparing the input to those might make more sense.

You may also want to make a minimal program for testing out the operation that you’re trying to get to work like you want.

"d".equals("d") evaluates to true by the way, so whatever you did try, it wasn’t that.

public class Main {
    public static void main(String[] args) {
        System.out.println("d".equals("d"));  // true

Wouldn’t you say this is a more straight-forward way to test that operation?

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.