0
1

【Java】Java備忘録①

Last updated at Posted at 2024-01-21

atcoderの問題をJavaで解いたのでその際に使用したJavaの知識を備忘録としてqiitaに残します。

問題①

解答

import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner numIn = new Scanner(System.in);
        int num = numIn.nextInt();
        String ans = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679";
        int index = num + 1;
        System.out.println(ans.substring(0, index + 1)); // 文字列の取り出し
        numIn.close();
    }
}

解説

substringを使用して文字列を取り出す。
substringの基本型は、インデックスによる範囲指定です。取得を開始するインデックスと、終了するインデックスを指定することで、その間にある文字列を取得します。

問題②

解答

import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt(); // int型に変換する。

        int x_value, y_value; // 受け取る二行目の数値
        
        int x = 0;
        int y = 0;
        for(int i = 0; i < num; i++){
            x_value = sc.nextInt();
            y_value = sc.nextInt();

            x += x_value;
            y += y_value;
        }
        sc.close();
        if(x == y){
            System.out.println("Draw");
        }else if(x > y){
            System.out.println("Takahashi");
        }else{
            System.out.println("Aoki");
        }
    }
}

問題③

解答

import java.util.Scanner;

public class Main {
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        // 答えを格納
        String ans = "";
        // ループする回数を決める。
        int roop = N + N + 2;
        
        for (int i = 1; i < roop; i++){
            if (i % 2 != 0){
                ans += "1";
            } else {
                ans += "0";
            }
        }
        System.out.println(ans);
        sc.close();
    }
}

問題④

解答

import java.util.Scanner;

public class Main {
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);

        int A = sc.nextInt(); // 初項
        int B = sc.nextInt(); // 末項
        int D = sc.nextInt(); // 公差

        int roop = (B - A) / D; // ループする回数を決める。
        // iが3までループして出力を行う
        for (int i = 0; i <= roop; i++){
            System.out.print(A + D * i + " ");
        }
        sc.close();
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1