0

I'm creating a program to solve problems that are in one-dimension kinematics. I initially started with solving for only one variable--solving for final position--but decided to play around and solve for final velocity. Now, I want to give the user an option. After they input the necessary known variables, prompt them to ask "Would you like to calculate final position or final velocity? " . Based on the user input I want to branch the calculations, however I don't know how to get that done.

This is what I have so far...

    Scanner reader = new Scanner(System.in);

    System.out.print("Enter time in seconds: ");
    double time = reader.nextDouble();
    System.out.print("Enter the initial position in meters: ");
    double initialPosition = reader.nextDouble();
    System.out.print("Enter intial velocity: ");
    double initialVelocity = reader.nextDouble();
    System.out.print("Enter acceleration: ");
    double acceleration = reader.nextDouble();

    System.out.println("What would you like to calculate? ");
    System.out.print("Final position or final velocity?");
    String userInput = reader.nextLine();

    if (userInput == "final position") {
        double finalPosition = ((0.5) * (acceleration * (time * time)) + (initialVelocity * time) + initialPosition);
        System.out.print("The final position is: " + finalPosition);
    } else {
        double finalVelcoity = (initialVelocity + (acceleration * time));
        System.out.print("The final velocity is: ");
    }

I understand that the condition I set in the if-statement is not allowed, but what can I replace that with?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Your logic looks good, but you're not comparing Strings correctly. Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Oct 01 '16 at 01:50
  • so not `if (userInput == "final position") {` but `if (userInput.equals("final position")) {` – Hovercraft Full Of Eels Oct 01 '16 at 01:50

0 Answers0