1
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?

More than 5 years have passed since last update.

初学者が最初にやったJava(while文)基本問題

Last updated at Posted at 2019-10-08

最初にやったJavaのwhile文問題のアウトプット

#問1

サイコロを2個ふるよぞろ目が何回目にでるかな?

###[実行例]

1回目(2,3) 2回目(3,2) 3回目(4,4) 3回目にぞろ目がでました!

[解答例]
import java.util.*;
public class Main{
    public static void main(String[] args){
        Random rand=new Random();
        int count=0;
        while(true){
            count++;
            int dice1=rand.nextInt(6)+1;
            int dice2=rand.nextInt(6)+1;
            System.out.printf("%d回目(%d,%d)%n",count,dice1,dice2);
            if(dice1 == dice2){
                break;
            }
        }
        System.out.println(count+"回目にぞろ目がでました!");
    }
}

#問2

以下の処理を実現せよ。

###[実行例]

9
8
7
6
5
4
3
2
1
発射!

[解答例]
import java.util.*;
public class Main{
    public static void main(String[] args){
        int n=9;
        while(n>0){
            System.out.println(n);
            n--;
        }
        System.out.println("発射!");
    }
}

#問3

1~999までの乱数を繰り返し生成し777が最初に出るまでの回数を表示せよ。

###[実行例]
1:34 2:432 3:321 ..... 1034:777 1034回目に777がでました!

[解答例]

import java.util.*;
public class Main{
    public static void main(String[] args){
        Random rand=new Random();
        int num=-1;
        int count=0;
        while(num !=777){
            count++;
            num=rand.nextInt(999)+1;
            System.out.printf("%d:%d%n",count,num);
        }
        System.out.println(count+"回目に777がでました!");
    }
}

#問4

[実行結果]
正の整数>20
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

[解答例]

import java.util.*;
public class Main{
public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        System.out.print("正の整数>");
        int max=sc.nextInt();
        int i=1;
        String ans;
        while(i<=max){
            if(i %3 == 0 && i % 5== 0){
                ans="FizzBuzz";
            }else if(i % 3==0){
                ans="Fizz";
            }else if(i % 5==0){
                ans="Buzz";
            }else{
                ans=i+"";
            }
            System.out.println(ans);
            i++;
        }
    }
}


って認識です。

1
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
1
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?