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?