【白俊】10952号、10951号、1110号/Java、Python


Baekjoon Online Judge
algorithm practice
問題をちくじ解く
4.While文
Java/Python
1. A + B - 5
10952号
A+Bが0に出力される問題
  • Java
  • import java.util.Scanner;
     
    public class Main {
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
            
    		while(true){
    			int a = sc.nextInt();
    			int b = sc.nextInt();
    			if(a == 0 && b == 0){
    				break;
    			}
    			System.out.println(a+b);  
    		}
    		sc.close();
    	}
    }
  • Python
  • while(True):
        a, b = map(int,input().split())
        if a == 0 and b ==0:
            break
        print(a+b)
    2. A + B - 4
    10951号
    入力が完了する前にA+Bを出力する問題.EOFについて
    EOF:endoffile/file end=>計算では、ファイルの末尾にデータソースから読み込むデータがないことを示します.
  • Java
  • import java.util.Scanner;
     
    public class Main {
    	public static void main(String args[]){
    		
    		Scanner sc = new Scanner(System.in);
    			
    		while(sc.hasNextInt()){
    			int a = sc.nextInt();
    			int b = sc.nextInt();
    			System.out.println(a+b);
    		}	
    		sc.close();
    	}
    }
    Javaの場合はhasNextInt()が使用されています.hasNextInt()の場合、入力値が整数の場合はtrueを返します.入力値が整数でない場合は例外を即時に放出します.追加の入力を受け入れない場合はfalseを返し、繰り返し文は終了します.
  • Python
  • 方法.
    while True:
        try:
            a, b = map(int, input().split())
            print(a+b)
        except:
            break
    方法.
    try:
        while True:
            a,b = map(int, input().split())
            print(a+b)
    except:
        exit()
    Pythonではtry/exceptionを用いて異常処理を行った.
    2つの少し違う方法でコードを書きました...!
    3.プラス記号周期
    1110番
    元の数を返すまで演算を繰り返す問題
  • Java
  • import java.util.Scanner;
     
    public class Main {
    	public static void main(String args[]){
    		Scanner sc = new Scanner(System.in);
    		int num = sc.nextInt();
    		int count = 0;    
    		int N = num;	
    		while(true){
    			count = count + 1;
    			N = ( (N%10)*10 ) + ( ((N/10) + (N%10))%10 );
    			if(num == N){
    				break;
    			}
    		}	
    		System.out.println(count);
    		sc.close();
    	}
    }
  • Python
  • N = num = int(input())
    count = 0
    
    while True:
        ten = N // 10
        one = N % 10
        total = ten + one
        count = count + 1
        N = int(str(N % 10) + str(total % 10))
        if(num == N):
            break
            
    print(count)
    今日はWhile文の使用例について説明します!
    while文の場合、if文で条件を決定し、breakで問題を解決しようとしました.