[伯俊]10871号:Xより小さい数字(JAVA)


質問する


N個の整数からなる数列Aと整数Xが与えられる.このとき、X未満の数字をすべてAに出力するプログラムを作成してください.

入力


第1行はNとXを与える.(1 ≤ N, X ≤ 10,000)
2行目には、数列Aを構成するN個の整数が与えられる.与えられた整数はいずれも1以上、10000以下である.

しゅつりょく


X未満の数字を入力順にスペースに分割して出力します.少なくとも1つのX未満の数が存在する.

入力例1


10 5 1 10 4 9 2 3 8 5 7 6

サンプル出力1


1 4 2 3

ソースコード

  • 第1の方法:for文
  • import java.util.*;
    public class Main {
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		int a = sc.nextInt();
    		int x = sc.nextInt();
    		for (int i = 0; i < a; i++) {
    			int n = sc.nextInt();
    			if (n < x) System.out.print(n + " ");
    		} sc.close();
    	}
    }
  • 第2の方法:while文
  • import java.util.*;
    public class Main {
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		int a = sc.nextInt();
    		int x = sc.nextInt();
    		int i = 0;
    		while (i < a) {
    			int n = sc.nextInt();
    			if (n < x) System.out.print(n + " ");
    			i++;
    		} sc.close();
    	}
    }
  • 第3の方法:do-while文
  • import java.util.*;
    public class Main {
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		int a = sc.nextInt();
    		int x = sc.nextInt();
    		int i = 0;
    		do {
    			int n = sc.nextInt();
    			if (n < x) System.out.print(n + " ");
    			i++;
    		} while (i < a);
    		sc.close();
    	}
    }
    [ショートカット]10871号:X未満の数字