-1
Good morning, I was training in Java and was building a form so I made a way that if the person enters an invalid data will run a do while with the same question (I don’t know if this is the right way to do it) and then was doing this in case the person selects a sex that is not M or F
Only when I do it makes a mistake. I’ll post all the code so you can see it and I’ll post it because I don’t know if you need it or not
package projeto1;
import java.util.Scanner;
public class Projeto1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nome;
String sexo;
int idade;
int estadoCivil;
String nomePai;
String nomeMae;
int rendaMensal;
String rendaString;
System.out.println("Olá, Para começarmos quero saber qual o seu nome.");
nome=scan.nextLine();
System.out.println("Ok "+nome+" vamos começar.\n");
System.out.println("Qual sua idade?");
idade=scan.nextInt();
if(idade<0||idade>120){
System.out.println("Digite uma idade válida");
do{
System.out.println("Qual sua idade?");
idade=scan.nextInt();
}while(idade<0||idade>120);
}
System.out.println("Qual seu sexo?"+
"M - Masculino"+
"F - Feminino");
sexo=scan.nextLine();
if(sexo!="M"||"F"{
System.out.println("Digite um sexo válido");
do{System.out.println("Qual seu sexo?"+
"M - Masculino"+
"F - Feminino");
sexo=scan.nextLine();
}while(sexo!="M"||"F"))
}
System.out.println(" Qual seu Estado Civil?\n"+
"1 - Casado\n"+
"2 - Solteiro\n"+
"3 - Viúvo\n"+
"4 - Divorciado\n");
estadoCivil=scan.nextInt();
if(estadoCivil>4){
System.out.println("Digite um Estado Civil válido");
do{
System.out.println(" Qual seu Estado Civil?\n"+
"1 - Casado\n"+
"2 - Solteiro\n"+
"3 - Viúvo\n"+
"4 - Divorciado\n");
estadoCivil=scan.nextInt();
}while(estadoCivil>4);
}
System.out.println("Digite o nome de seu pai");
nomePai=scan.nextLine();
System.out.println("Digite o nome de sua mãe");
nomeMae=scan.nextLine();
System.out.println("Digite sua renda mensal\n"+
"1 - Menos de 1500\n"+
"2 - Entre 1500 e 2500\n"+
"3 - Entre 2500 e 3500\n"+
"4 - Entre 3500 e 4500\n"+
"5 - Mais de 4500\n");
rendaMensal=scan.nextInt();
if(rendaMensal>5){
System.out.println("Digite uma renda mensal válida");
do{System.out.println("Digite sua renda mensal\n"+
"1 - Menos de 1500\n"+
"2 - Entre 1500 e 2500\n"+
"3 - Entre 2500 e 3500\n"+
"4 - Entre 3500 e 4500\n"+
"5 - Mais de 4500\n");
rendaMensal=scan.nextInt();
}while(rendaMensal>5);
}
thank you in advance
As already indicated in the link above (in the blue box), in Java one should compare strings with
equals. And in that case, unfortunately, it can’t be shorter thanif ((! "M".equals(sexo)) && (! "F".equals(sexo)))- note the&&instead of||, because I want to know if it’s different from M and other than F (if it were||he would see if it is different from M or different from F, so if it were equal to F, it would be different from M and enter theif)– hkotsubo