0

I created a simple program for calculating the % of profit/loss in an investment. This is how it works: the program asks you to input your initial amount of money, then it asks you to input your final amount of money. The result is the program calculating what % of return you earned. This is the code:

public class Application {
public static void main(String[] args) {
    boolean valid = true;
    System.out.println("Introduce tu capital inicial.");
    Scanner scanner = new Scanner(System.in);
    while (valid) {
        try {
            int capitalInicial = Integer.parseInt(scanner.nextLine());
            System.out.println("Introduce tu capital final.");
            int capitalFinal = Integer.parseInt(scanner.nextLine());
            System.out.println("Tu ganancia ha sido del " + (capitalFinal * 100 / capitalInicial - 100) + "%.");
            System.out.println("Introduce, si quieres, otro capital inicial para volver a calcular tus ganancias/pérdidas o escribe 'salir' para terminar.");
            if (scanner.nextLine() == "salir") {
                break;
            }
        }
        catch (NumberFormatException e) {
            System.out.println("Por favor introduce un número válido.");
        }
    }
}

After completing the process it gives you the chance of introducing a new amount of money for calculating the profit/loss % again. But what I would like and what I tried to achieve with the if statement is ending the loop and finishing the program, but it still lets you input numbers. How can I fix this?

daniirp
  • 23
  • 2
  • 1
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – maloomeister Jul 21 '21 at 12:14
  • 1
    Change `scanner.nextLine() == "salir"` to `(scanner.nextLine().equals("salir")` – sanjeevRm Jul 21 '21 at 12:14
  • Since you never change the value of ``valid``, I would just make it a ``while (true)`` loop and break out of it. – NomadMaker Jul 21 '21 at 12:17

0 Answers0