quero criar um metodo que eu digite:"1" e me retorne o nome:"Janeiro" e assim sucesivamente.
agradeço a ajuda.
public String getMes(int m){
String[] meses={"janeiro","fevereiro","marco","anril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"};
return meses[m];
}
public class MesesAno {
public static void main(String[] args) {
HashMap hm = new HashMap();
JOptionPane jop = new JOptionPane();
int valor = 0;
hm.put(1, "Janeiro");
hm.put(2, "Fevereiro");
hm.put(3, "Março");
hm.put(4, "Abreil");
hm.put(5, "Maio");
hm.put(6, "Junho");
hm.put(7, "Julho");
hm.put(8, "Agosto");
hm.put(9, "Stembro");
hm.put(10, "Outubro");
hm.put(11, "Novembro");
hm.put(12, "Dezembro");
do {
valor = Integer.parseInt(jop.showInputDialog("Digite um mês: "));
if(valor > 1 && valor <= 12) {
String rs;
String novoValor = Integer.toString(valor);
int n1 = Integer.parseInt(novoValor.substring(0));
int n2 = Integer.parseInt(novoValor.substring(1));
if(n2 == 0) {
rs = "" + hm.get(n1);
} else {
n1 -= n2;
rs = "" + hm.get(n1) + " e " + hm.get(n2);
}
JOptionPane.showMessageDialog(null, rs);
} else if(valor >= 1 &&valor <= 12)
JOptionPane.showMessageDialog(null, hm.get(valor));
} while(valor >= 1 && valor <= 12);
}
}
Galera como crio um método em java?
quero criar um metodo que eu digite:"1" e me retorne o nome:"Janeiro" e assim sucesivamente.
agradeço a ajuda.
#Programação#Java#poo
Inicialmente devemos declarar o método que chamaremos de mês do tipo String. Assim:
public static String mes() {
Com isso necessitamos receber o número a ser digitado:
Scanner Scanner= new Scanner(System.in);
System.out.println("\nDigete o número");
int numero = Scanner.nextInt();
Assim, criamos um vetor do tipo string para armazenar o respectivo mês:
String[] vetormes = null;
Com a função swich verificamos o número e armazenamos o mês:
switch(numero) {
case 1:
vetormes[0]="Janeiro";
break;
case 2:
vetormes[0]="Fevereiro";
break;
case 3:
vetormes[0]="Março";
break;
case 4:
vetormes[0]="Abril";
break;
case 5:
vetormes[0]="Maio";
break;
case 6:
vetormes[0]="Junho";
break;
case 7:
vetormes[0]="Julho";
break;
case 8:
vetormes[0]="Agosto";
break;
case 9:
vetormes[0]="Setembro";
break;
case 10:
vetormes[0]="Outubro";
break;
case 11:
vetormes[0]="Novembro";
break;
case 12:
vetormes[0]="Dezembro";
break;
default:
return null;
}
Finalmente, retornamos a string desejada:
return(vetormes[0]);
}
Para escrever sua resposta aqui, entre ou crie uma conta
Programação Orientada A Objetos
•ESTÁCIO
Programação Orientada A Objetos
•Faculdade Descomplica
Compartilhar