The while block is intended to loop if the condition is still true and terminate otherwise. To evaluate the condition I have created a boolean. You are prompted if you want to continue entering data, and a Scanner stream awaits you. I have tried two options, the second, which is commented, works fine, with compareTo, but the first option does not work at all and if someone would be kind enough to enlighten me I would be very grateful.
Boolean y=true;
while(y) {
System.out.println("Que cantidad de artículos 1 desea declarar?");
v1.cant1=v1.cant1+entrada.nextInt();
System.out.println("Que cantidad de artículos 2 desea declarar?");
v1.cant2=v1.cant2+entrada.nextInt();
System.out.println("Que cantidad de artículos 3 desea declarar?");
v1.cant3=v1.cant3+entrada.nextInt();
System.out.println("Que cantidad de artículos 4 desea declarar?");
v1.cant4=v1.cant4+entrada.nextInt();
System.out.println("Desea declarar mas artículos?. Escriba 'y/Y' para declarar");
if(entrada.next()!="y") y=false;
//if(entrada.next().compareToIgnoreCase("y")!=0) y=false;
}
entrada.close();
System.out.println( v1.getSalario() + " $ es la cantidad que percibirá esta semana. Que pase un buen día " + v1.getNombre(
To compare the content of two instances of
String
you must use the methodString.equals()
:Otherwise you are comparing two instances of
String
different, which will always be different even if they contain the same character string inside.Code used to reproduce your problem (click to show):
It gives you an error because next() does not return a String comparable to "y". The method you should use to read a String with the scanner class is nextLine().
Changing that should be enough.
In addition to using equial, compareToIgnoreCase or compareto for string never == do not use nextINT if you use next int it is possible that lines will be skipped due to buffer overrun since it does not clean the carriage return, use Integer.parseInt(input.nextLine)