Entrada do usuário em Java - classe Scanner

Nosso tópico hoje é Java User Input , e forneceremos exemplos para garantir que os alunos possam entendê-lo melhor.

Entrada do usuário Java

Como parte do Java User Input , existe uma classe Scanner que é usada para obter a entrada do usuário. Ele pode ser encontrado no pacote java.util.

Criar um objeto da classe Scanner e chamar um dos métodos listados na documentação permitirá que você use a classe Scanner.

Sintaxe:

Scanner mrx=new Scanner(System.in);

Aqui está um exemplo de uso do método nextLine() para ler uma string:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.Scanner; // Scanner Package is added OR Scanner class is imported here
public class Main { // Main Class body starts
public static void main(String[] args) {
Scanner my_input=new Scanner(System.in); // Creating an Object of Scanner Class
System.out.println("Enter Your Gender here: ");
String mrx_gender=my_input.nextLine(); // The input is taken in this line using Scanner Object and the value is stored in mrx_gender
System.out.println("Gender Entered: "+mrx_gender);
}
// Output: Gender Entered : Male
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Múltiplas entradas podem ser obtidas do usuário, conforme mostrado no exemplo abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Scanner; // Scanner Package is added OR Scanner class is imported here
public class Main { // Main Class body starts
public static void main(String[] args) {
Scanner num_input=new Scanner(System.in); // Creating an Object of Scanner Class
System.out.println("Enter First Number here: ");
int mrx=num_input.nextInt(); // The input is taken in this line using Scanner Object and the value is stored in mrx_gender
System.out.println("Enter Second Number here: ");
int ample=num_input.nextInt();
System.out.println("Product of Both Numbers is: "+mrx+" x "+ample+" = "+(mrx*ample));
}
// Output: Product of Both Numbers is: 7 x 6 = 42
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

O Tutorial de Pacotes Java oferece uma visão geral do que é um pacote e o que você pode fazer com ele.



Tipos de Entrada Java

Conforme mostrado nos exemplos acima, nextLine() foi usado para ler strings e nextInt() foi usado para buscar valores int. Confira a tabela abaixo para saber mais sobre outros tipos:

Métodos Visão geral
BigDecimal nextBigDecimal() Essa função verifica o próximo token como BigDecimal .
BigInteger nextBigInteger() Um BigInteger é usado para verificar o próximo token de entrada.
nextBoolean() Obtém um valor booleano do usuário.
nextByte() Lê um valor de byte do usuário.
nextDouble() Recebe um valor duplo do usuário.
nextFloat() Obtém um valor float do usuário.
nextInt() Obtém um valor int do usuário.
nextLine() Lê um valor String do usuário.
nextLong() Obtém um valor longo do usuário.
nextShort() Lê um valor curto do usuário.

 

Aqui estão alguns exemplos de leitura de dados de diferentes tipos usando diferentes métodos :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.Scanner;
// Following program takes all numeric input types;
public class Main {
public static void main(String[] args) {
Scanner my_input=new Scanner(System.in);
// Taking int input
System.out.println("Enter any integer here: ");
int mrx_I_num=my_input.nextInt();
// Taking float input
System.out.println("Enter any float value here: ");
float mrx_f_num=my_input.nextFloat();
// Taking double input
System.out.println("Enter any double value here: ");
double mrx_d_num=my_input.nextDouble();
// Taking long input
System.out.println("Enter any long value here: ");
long mrx_l_num=my_input.nextLong();
// Taking long input
System.out.println("Enter any short value here: ");
short mrx_s_num=my_input.nextShort();
// Printing the values below:
System.out.println("\nThe values are: \n");
System.out.println("Int value: "+mrx_I_num);
System.out.println("Float value: "+mrx_f_num);
System.out.println("Double value: "+mrx_d_num);
System.out.println("Long value: "+mrx_l_num);
System.out.println("Short value: "+mrx_s_num);
}
// Outputs: The values are:
// Output 1: Int value: 1231234
// Output 2: Float value: 23.63424
// Output 3: Double value: 34.4234324523
// Output 4: Long value: 2344684567549582323
// Output 5: Short value: 32,763
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Outra abordagem.

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.Scanner;
// Following program takes other Input types;
public class Main {
public static void main(String[] args) {
Scanner my_input=new Scanner(System.in);
// Taking String input
System.out.println("Enter name here: ");
String mrx_Str_name = my_input.nextLine();
// Taking byte input
System.out.println("Enter any Byte value here: ");
byte mrx_Byte_num=my_input.nextByte();
// Taking boolean input
System.out.println("Enter any Boolean value here: ");
boolean mrx_Bool_val=my_input.nextBoolean();
// Printing the values below:
System.out.println("\nThe values are: \n");
System.out.println("String name: "+mrx_Str_name);
System.out.println("Byte value: "+mrx_Byte_num);
System.out.println("Boolean Value: "+mrx_Bool_val);
}
// Outputs: The values are:
// Output 1: String name: James Gosling
// Output 2: Byte value: 76
// Output 3: Boolean Value: true
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Lembre-se: Você receberá uma mensagem de exceção/erro (como “ InputMismatchException ”) se inserir uma entrada incorreta (por exemplo, texto em uma entrada numérica).

A entrada de usuário Java agora é familiar para você e você sabe como usá-la – Mais informações sobre exceções e tratamento de erros podem ser encontradas em nosso próximo capítulo sobre Exceções .

Nós valorizamos o seu feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Assine a nossa newsletter
Digite seu e-mail para receber um resumo semanal de nossos melhores posts. Saber mais!
ícone