ㅤㅤㅤ

Scanner 클래스 예제 본문

プログラミング/JAVA

Scanner 클래스 예제

ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ 2017. 6. 12. 17:49

cannerTest1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Scanner;
 
public class ScannerTest1 {
 public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  System.out.print("두 개의 숫자(정수)를 입력해 주세요 : ");
  int number1 = scanner.nextInt();
  int number2 = scanner.nextInt();
  System.out.println("합 : "+(number1+number2));
  System.out.print("두 개의 숫자(실수)를 입력해 주세요 : ");
  double number3 = scanner.nextDouble();
  double number4 = scanner.nextDouble();
  System.out.println("합 : "+(number3+number4));
  scanner.close();
 }
}


ScannerTest2.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Scanner;
 
public class ScannerTest2 {
 public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  String input = "";
  do{
   System.out.print("값을 입력하세요. 입력을 마치려면 Q를 입력하세요 : ");
   input = scan.nextLine();
   System.out.println("입력하신 값은 "+input+"입니다.");
  }while(!input.equalsIgnoreCase("q"));
   
  System.out.println("프로그램을 종료합니다.");
  scan.close();
 }
}


ScannerTest3.java

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
import java.io.File;
import java.util.Scanner;
 
public class ScannerTest3 {
 public static void main(String[] args) throws Exception{
  Scanner sc1 = new Scanner(new File("score.txt"));
  Scanner sc2 = null;
  int cnt = 0;
  int totalSum =0;
   
  while(sc1.hasNextLine()){
   String line=sc1.nextLine();
   sc2 = new Scanner(line).useDelimiter(",");
   int sum=0;
   while(sc2.hasNextInt()){
    sum+=sc2.nextInt();
   }
   System.out.println(line+" sum="+sum);
   totalSum+=sum;
   cnt++;
   sc2.close();
  }
  System.out.println("Line  : "+cnt+", Total : "+totalSum);
  sc1.close();
 }
}


Comments