0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PythonとJava】コードを書いて比べてみた!!

Last updated at Posted at 2024-01-18

実際に書いてみた!

PythonとJavaのコードの違いをまとめてみました!

問題①

Python

pythonで解いた場合は以下になる

N = int(input())  # 文字列を読み込み整数に変換する
ans = 'L'
for i in range(N):
    ans += 'o'
print(f'{ans}ng')

Java

Javaで解いた場合は以下になる

import java.util.Scanner;
public class Test {
        public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int num = input.nextInt(); // 整数を読み込む
        String ans = "L";
        for(int i = 0; i < num; i++){
            ans += "o";
        }
        System.out.println(ans + "ng");
        numIn.close();
    }
}

問題②

Python

S = input()
ans_lst = S.split('.') # 「.」で区切りリストに格納
print(ans_lst[-1])

Java

import java.util.Scanner;

public class Main {
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        
        String rep = str.replace(".", ",");
        String[] array01 = rep.split(",");
        
        int ans = array01.length - 1; // 配列の長さ-1を取得する。
        System.out.println(array01[ans]);
        sc.close();
    }
}

メモリの消費量はJavaが半分になっている。
実行時間はPythonが短い。

image.png

九九の表示

期待する出力
image.png

Python

for i in range(1, 10):
    for j in range(1, 10):
        value = i * j
        print(f"{value:2}", end=" ")
    print()  # 改行

Java

public class sample4 {
    public static void main(String[] args){
        for(int i = 1; i < 10; i++){
            for(int j = 1; j < 10; j++){
                int value = i * j;
                System.out.printf("%2d ", value);
            }
            System.out.println(); // 改行
        }
    }
}
0
1
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?