[Java] Scanner and Input Validation

· Tech· Java
Java

Scanner statement


// System.in When inputting keyboard values

// System.out When outputting values to the monitor

When using the

Scanner statement, import java.util.Scanner; is required. Automatically added when creating scanner in Eclipse. 

Scanner variable name.nextLine();

Used when saving the input value (string).

For

.nextLine, the input value is a string, that is, includes spaces, and the terminator is the enter key. but .nextInt();  .nextDouble(); When receiving input in the form of an integer, real number, etc., both a space and the enter key can be used as the terminator. Therefore, when unnecessarily received data buffer occurs and it is deleted, is also used.

sc.close();

Must be closed to prevent data leak.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Scanner1Main {
public static void main(String[] args) {
          
        Scanner sc = n ew Scanner(System.in);
        System.out.print(Enter the sentence " => ");    
         String inputStr = sc.nextLine();
         System.out.println@@T199@ @("Input sentence => "+inputStr);
          
        System.out.println("Enter an integer => ");
int inputNum = sc.nextInt();   
        
sc.nextLine();
sc.close(); //sc close
{ }
}
cs

try - catch statement


plus, create a devide method and use it to calculate the input integer

In case of division, if the denominator is 0, the value Infinity is output. To prevent this, you must write an if-else statement within the method to prevent the denominator from being 0.

//You need to consider the number of possible cases while writing code.

try - Write error handling when an error occurs with a catch statement.

try { }

catch (Exception e) { }

*NumberFormatException: An error that occurs when a value outside the range of the specified int, short, etc. type is entered.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package my.day04.a.scanner;
 
public class Calculator {
 
        String plus(int num1, int num2) {    // plus(10, 20)
            
            return num1+ "+" +num2+ "=" +(num1+num2);
            // 10+20=30
        }
        
        String devide(float num1, int num2) { 
            if(num2 == 0) {
                   return "The denominator cannot contain 0!!";
{
return num1@ @T474@@+ "/" +@@T481 @@num2+ "=" +(num1/num2);    
                }
             }
{ }
cs

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
package my.day04.a.scanner;
import java.util.Scanner;
public class Scanner5Main {
public static void main(String[] args) {
        Scanner sc = n ew Scanner(System.in);
          
          System.out.prin tln("== Input two numbers and find out the calculation result ==");
           try {
              
|
                    inputStr = sc.nextLine();        
|   
                   inputStr = sc.nextLine();        
                 int num2 = Integer.parseInt(inputStr);   
                  //Converting a string to int type
                   Calculator calc = new Calculator();
|
             System.out.println(result);
… result = calc.devide(num1, num2);
System.out.println(result); //10/20=0.5
                
             } catch(NumberFormatException e) {
| +inputStr+" is not an integer. Enter only an integer!!");
             }
sc.close();        
{ }
}
cs

String ↔ Integer


Integer.toString( );

String.valueOf( );

//How to convert an integer to a string

Interger.parseInt( );

//How to convert a string to an integer

1
2
3
4
5
6
7
//The first way to convert an integer to a string
String str1 = Integer.toString(num1);  //"10"
          
//Second way to convert integer to string
String str2 = String.valueOf(num2);    //"20"
System.out.println(str1+str2);         //"1020"
cs

//Reducing overlapping code using method (cheakJumsu())

1
2
3
4
5
6
7
8
9
System.out.print("3. Korean: ");
Byte.parseByte(sc.nextLine());
               
// if(sj.kor < 0 || sj.kor > 100 )
if(!(0@@ T1049@@ < sj.kor &@ @T1057@@& sj.kor <= 100)) {
System.out.pri ntln(">> The score can only be entered between 0 and 100 <<");
sc.close();
return;
}
cs

1
2
3
4
5
6
7
8
9
System.out.print("3. Korean: ");
byte kor = Byte.parseByte(sc.nextLine());
if (!sj.cheakJumsu(kor)) { ​
sc.close();
return;
} else {
sj.kor = kor;
}
cs

Validation


When the error type is different and you want to output different sentences, set and use a random local variable called inputType for distinction.

int inputType = 0; inputType = 1 before the code in the try statement that initializes the value and receives input corresponding to the error. or inputType = 2; Divide as follows. Then, divide the catch statement into an if - else if statement to set the action value for the error. 

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
 
package my.day04.b.scanner;
 
import java.util.Scanner;
 
public class SungjulkMain4 {
 
    public static void main(String[] args) {
        
        Scanner sc = n ew Scanner(System.in);
        
        Sungjuk sj = new Sungjuk();
        
        int inputType = 0;
        
        try {
            
               System.out@@T1525 @@.print("1. Student number: ");
sj.hakbun = sc.nextLine();
               
               System.out@@T1543 @@.print("2. Name: ");
            sj.name = sc.nextLine();
              
//0~100
//byte: -128 ~ 127
              
// === *** Validation (checking whether the data is correct or incorrect) *** ===
                //Integer.parseInt(String str)
//Short.parseShort(String str)
              
                  inputType = 1//inputTye If the value is 1, it means that the national number is being input.
               
               System.out@@T1597 @@.print("3. Korean: ");
|
...
              
|
sc.close();
return;
{
sj.kor = kor;
                }
              
            System.out.print("4. 영어: ");
            byte eng = Byte.parseByte(sc.nextLine());
            if (!sj.cheakJumsu(eng)) {  
                sc.close();
                return;
            } else {
                sj.eng = eng;
            }
            
            
            System.out.print("5. 수학: ");
            byte math = Byte.parseByte(sc.nextLine());
            if (!sj.cheakJumsu(math)) { 
                sc.close();
                return;
            } else {
                sj.math = math;
            }
            
            inputType = 2//inputTye 값이 2이라면, 나이를 입력하는 중이다 라고 본다.
            
            System.out.print("6. 나이: ");
            short age = Short.parseShort(sc.nextLine());
| j.cheakAge(age)) { //if(false) {} ==> dead code
sc.close();
return;
{
sj.age = age;
                }
              
sj.showInfo();
               
/*
...
* 1. Student number: 091234
* 2. Name: Yi Sun-shin
* 3. Korean: 90
* 4. English: 80
* 5. Math: 78
* 6. Total score: 248
* 7. Average: 82.666666667
* 8. Grade: B
* 9. Age: 20
*/
              
              
           } catch (NumberFormatException e) {
| @== 1)
                  System.out.@@T1878@ @println("## The score can only be entered between 0 and 100 ##");
| 89@@== 2)
System.out.@@T1904@ @println("## Age input is only possible between 20 and 50 ##");
              
e.printStackTrace();
            }
          
           sc.close();
{ }
}
cs

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
60
package my.day04.b.scanner;
 
public class Sungjuk {
 
    String hakbun;
    String name;
    byte kor;     // -128 ~ 128      0 ~ 100
    byte eng;
    byte math;
    short age;    //-32768 ~ 32768      20 ~ 50
        
    // 기본생성자 생략 public Sungjuk() {}
    
    boolean cheakJumsu(byte jumsu) {
        if0 <= jumsu && jumsu <= 100 ) 
            return true;
        else {
            System.out.println(">> 점수는 입력은 0 이상 100 까지만 가능합니다 <<");
            return false;
        }
    }
            
    boolean cheakAge(short age) {
        if20 <= age && age <= 50 ) 
            return true;
        else {
            System.out.println("== 나이는 입력은 20 이상 50 까지만 가능합니다 ==");
            return false;
        }
            
    }
    
    
    void showInfo() {
        
        int total = (kor+eng+math);
        float avg = total/3.0F;
 
        String grade= "";
        if(avg >= 90)       grade = "A";
        else if (avg >= 80) grade = "B";
        else if (avg >= 70) grade = "C";
        else if (avg >= 60) grade = "D";
        else                 grade = "F";
        
        System.out.println("\n=== "+name+"의 성적결과 ===\n"
                + "1. 학번 : "@ @T2362@@+hakbun+"\n"
                + "2. 성명 : " +name+"\n"
                
           + "3. 국어 : "@@T2399@ @+kor+"\n"
           + "4. 영어 : "@@T2417@ @+eng+"\n"
                + "5. 수학 : " +math+"\n"
                + ”6. 총점 :” +total+"\n"
                + "7. 평균: "@@T2471@ @+avg+"\n"
| +grade+"\n"
 +age+"\n");
               
{ }
}
cs

e.printStackTrace();

You can check the error path in Eclipse.

/*

java.lang.NumberFormatException: Value out of range. Value:"88888888" Radix:10

at java.lang.Short.parseShort(Unknown Source)

at java.lang.Short.parseShort(Unknown Source)

at my.day04.b.scanner.SungjulkMain4.main(SungjulkMain4.java:59)

*/

Comments

No comments yet. Be the first!

    164 posts in 테크

    15 / 164