Java - Scanner vs JOptionPane

I’m trying to collect athlete’s personal info using a scanner, and I am running into a problem when whatever I am writing has a space and a second word, like a first and second names or Street x. When I use JOptionPane all is good. Is there something I can do, because I’m trying to use the scanner for this exercise.

Thanks.

Scanner scanner = new Scanner(System.in);
		
		System.out.println("Choose a sport: 1[Soccer] 2[Volleyball] 3[MMA]");
		sport = scanner.nextInt();
		while(sport < 1 || sport > 3) {
			System.out.println("Number has to be greater than 0");
			sport = scanner.nextInt();
		}
		switch (sport) {
		case 1:
			//Soccer
			numAthlets = numeroAtlCadastrar(scannerNum);	
			for(int i = 0; i < numAtletas; i++) {
				System.out.println("Name");
				strName = scanner.next();			
				System.out.println("Nickname");
				strNickname = scanner.next();			
				yearOfbirth=yearOfbirthAtl(scanner);//method	
				height = heightAtl(scanner); //method
				weight = weigthAtl(scanner); //method			
				
			
				SoccerAthlete Afut = new SoccerAthlete(strName, strNickName, yearOfbirth, height, weight);

Spelling is fine, if there is a mistake it’s because I had to translate some words and make the necessary changes.

can you specify what you mean by problem?
(syntax error? unexpected output? please be more specific)

Edit: I’m guessing that you want to use nextLine() instead of next() then parse the String to see if it has multiple words in it…

1 Like

Let’s say I enter Max Smith for the person’s full name. What ends up happening is that the console is going to ask for the nick name and year of birth at the same time and when, let’s say, I enter the nick name I get a Exception in thread "main" java.util.InputMismatchException back.

I didn’t do it at first, because it is in Portuguese. But here it goes:

import java.util.Scanner;

import ravim.clube.DAO.ClubeDAO;
import ravim.clube.view.View;
import ravim.model.Atleta;
import ravim.model.AtletaDeFutebol;
import ravim.model.AtletaDeMMA;
import ravim.model.AtletaDeVolei;
import ravim.model.Endereco;
import ravim.model.Posicao;

public class AppCollection {

	public static void main(String[] args) {
		
		String strNome = null, strApelido= null, strPosicao= null, strEstiloDeLuta= null, endereco=null, bairro = null, referencia = null;
		int anoNascimento=0, vitorias=0, numeroAtletas=0, esporte = 0, opcaoEstiloDeLuta=0, nocautes=0;
		float altura=0, peso=0;
		char federado;
		
		int num = 0;
		
		
		int cep = 0;
		
		Scanner scanner = new Scanner(System.in);
		Scanner scannerNum = new Scanner(System.in);
		Scanner scannerNum2 = new Scanner(System.in);
		
		System.out.println("Insira o número referente ao esporte do jogador a ser cadastrado: 1[Futebol] 2[Voleibol] 3[MMA]");
		esporte = scanner.nextInt();
		while(esporte < 1 || esporte > 3) {
			System.out.println("Número tem que ser de 1 a 3: repita");
			esporte = scanner.nextInt();
		}
		switch (esporte) {
		case 1:
			//Football
			numeroAtletas = numeroAtlCadastrar(scannerNum);	
			for(int i = 0; i < numeroAtletas; i++) {
				System.out.println("Nome");
				strNome = scanner.next();			
				System.out.println("Apelido");
				strApelido = scanner.next();			
				anoNascimento = anoNascimentoAtl(scanner);			
				altura = alturaAtl(scanner);			
				peso = pesoAtl(scanner);			
				federado = federadoAtl(scanner);			
				Posicao.opcoesPosicoesFutS();
				strPosicao = Posicao.posicaoFut(strPosicao, Posicao.coletarPosicaoFut(scanner));
			
				AtletaDeFutebol Afut = new AtletaDeFutebol(strNome, strApelido, anoNascimento, altura, peso, federado, strPosicao);
				
				//*TESTE!!!
				Endereco end = new Endereco();
				System.out.println("Logradouro");
				//endereco = scanner.next();
				end.setLogradouro(endereco= scanner.next()); //Where's the second word?
				System.out.println("Numero") ; 
				//num = scannerNum.nextInt();
				end.setNumero(num= scannerNum.nextInt());				
				System.out.println("Bairro"); 
				//bairro = scannerNum.next(); //Bairro pega L de Rua L
				end.setBairro(bairro= scanner.next());
				System.out.println("Referencia"); 
				//referencia = scannerNum.next();
				end.setReferencia(referencia= scannerNum.next());				
				System.out.println("CEP"); 
				//cep = scanner.nextInt();
				end.setCep(cep= scannerNum.nextInt());
				//Endereco end = new Endereco(endereco, num, bairro, referencia, cep);
			
				Afut.setEndereco(end);
				ClubeDAO.gravar(Afut);//adding object to ArrayList
				//System.out.println(new ClubeDAO().gravar(Afut));//message if recorded 
				
				//*TESTE!!!
			}		
		break;	
		case 2:
			//Volleyball
			numeroAtletas = numeroAtlCadastrar(scannerNum);
			for(int i = 0; i < numeroAtletas; i++) {
				System.out.println("Nome");
				strNome = scanner.next();			
				System.out.println("Apelido");
				strApelido = scanner.next();			
				anoNascimento = anoNascimentoAtl(scanner);			
				altura = alturaAtl(scanner);			
				peso = pesoAtl(scanner);			
				federado = federadoAtl(scanner);			
				Posicao.opcoesPosicoesVolei();
				strPosicao = Posicao.posicaoVolei(strPosicao, Posicao.coletarPosicaoVolei(scanner));
				AtletaDeVolei atlVolei = new AtletaDeVolei(strNome, strApelido, anoNascimento, altura, peso, federado, strPosicao);
				ClubeDAO.gravar(atlVolei);//adding object to ArrayList
				//System.out.println(new ClubeDAO().gravar(atlVolei));//message if recorded 
			}
		break;
		case 3:
			//MMA
			numeroAtletas = numeroAtlCadastrar(scannerNum);
			for(int i = 0; i < numeroAtletas; i++) {
				System.out.println("Nome");
				strNome = scanner.next();			
				System.out.println("Apelido");
				strApelido = scanner.next();			
				anoNascimento = anoNascimentoAtl(scanner);			
				altura = alturaAtl(scanner);			
				peso = pesoAtl(scanner);			
				federado = federadoAtl(scanner);
				strEstiloDeLuta = opcoesDeEstilosDeLuta(scanner);
				System.out.println("Número de vitórias do(a) " + strNome);
				vitorias = scanner.nextInt();
				while(vitorias < 0) {
					System.out.println("Número invalido: insira novamente");
					vitorias = scanner.nextInt();
				}//while
				System.out.println("Número de KOs do(a) " + strNome);
				nocautes = scanner.nextInt();
				while(nocautes < 0) {
					System.out.println("Número invalido: insira novamente");
					nocautes = scanner.nextInt();
				}
				AtletaDeMMA atlMMA = new AtletaDeMMA(strNome, strApelido, anoNascimento, altura, peso, federado,
						strEstiloDeLuta, vitorias, nocautes); 			
				ClubeDAO.gravar(atlMMA);
				//System.out.println(new ClubeDAO().gravar(atlMMA));
			}			
		}
		for(Atleta x : ClubeDAO.listAtleta) {
			System.out.println(x);
		}
		scanner.close();
		scannerNum.close();
	}//main
	
	private static String opcoesDeEstilosDeLuta(Scanner scanner) {
		String strEstiloDeLuta;
		int opcaoEstiloDeLuta;
		System.out.println("Insira o número referente ao estilo de luta: 1[Luta-livre] "
				+ "2[Karate] 3[Jiu-jitsu] 4[MMA] 5[Outro]");
		opcaoEstiloDeLuta = scanner.nextInt();
		switch (opcaoEstiloDeLuta) {
		case 1:
			strEstiloDeLuta = "Luta livre";
			break;
		case 2:
			strEstiloDeLuta = "Karate";
			break;
		case 3:	
			strEstiloDeLuta = "Jiu-jitsu";
			break;
		case 4:
			strEstiloDeLuta = "MMA";
			break;
		default:
			System.out.println("Insira o estilo de luta");
			strEstiloDeLuta = scanner.next();
			break;
		}
		return strEstiloDeLuta;
	}

	private static int numeroAtlCadastrar(Scanner scannerNum) {
		int numeroAtletas = 0;
		System.out.println("numero de atletas cadastrar");
		try {
			numeroAtletas = scannerNum.nextInt();
			while(numeroAtletas < 1) {
				System.out.println("Somente maior que zero");
				numeroAtletas = scannerNum.nextInt();
			}
		} catch (Exception e) {
			System.out.println("Erro");//ISSUE: the following scanner catches the input--string, float
		}
		return numeroAtletas;
	}

	private static char federadoAtl(Scanner scanner) {
		char federado;
		System.out.println("Federado: S ou N");
		federado = scanner.next().charAt(0);
		while(Character.isLetter(federado) != Character.isLetter('S') || Character.isLetter(federado) != Character.isLetter('N')) {
			System.out.println("Insira somente S ou N: repita");
			federado = scanner.next().charAt(0);
		}
		return federado;
	}

	private static float pesoAtl(Scanner scanner) {
		float peso;
		System.out.println("Peso");
		peso = scanner.nextFloat();
		while(peso < 50 || peso > 90) {
			System.out.println("Peso inválido: insira ano novamente");
			peso = scanner.nextFloat();
		}
		return peso;
	}

	private static float alturaAtl(Scanner scanner) {
		float altura;
		System.out.println("Altura");
		altura = scanner.nextFloat();
		while(altura > 2.5 || altura < 1.5) {
			System.out.println("Altura inválida: insira ano novamente");
			altura = scanner.nextFloat();
		}
		return altura;
	}

	private static int anoNascimentoAtl(Scanner scanner) {
		int anoNascimento;
		System.out.println("Ano nascimento");
		anoNascimento = scanner.nextInt();
		while(anoNascimento > 2021 || anoNascimento < 1920) {
			System.out.println("Ano inválido: insira ano novamente");
			anoNascimento = scanner.nextInt();
		}
		return anoNascimento;
	}
}
	

@camperextraordinaire I’m going to translate everything and post it again.

I’m trying to use nextLine.

You have to use nextLine to get the whole line (next only gets one token unless you give it an input pattern or delimiter)

1 Like

It’s working here but not there… just gotta spend more time on it. Cheers @hbar1st !

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.