mardi 23 mars 2021

Java - get out of the do-while loop with an input of user

I am trying to write a program that allows generate random numbers inside a infinite loop. If the user press 'c' it will get out of loop. But the loop only starts when I press c, it should start before and it should stop when I press 'c'.

import java.util.Random;
import java.util.Scanner;

public class main{

    public static void main (String[] args) {

        Random rand = new Random();

        int[] randNumber = new int[100];

        Scanner scanner = new Scanner(System.in);
        char c = scanner.next().charAt(0);

        do {
            for (int i = 0; i <= 99; i++) {
                randNumber[i] = rand.nextInt(100);
            }

            for (int i = 0; i < 99; i++) {
                if (randNumber[i] < randNumber[i + 1]) {
                    System.out.println("Number " + randNumber[i] + " smaller than " + randNumber[i + 1]);
                } else if (randNumber[i] > randNumber[i + 1]) {
                    System.out.println("Number " + randNumber[i] + " greater than " + randNumber[i + 1]);
                } else if (randNumber[i] == randNumber[i + 1]) {
                    System.out.println("Number " + randNumber[i] + " equal to " + randNumber[i + 1]);
                } else {
                    System.out.println("Wrong!");
                }
            }
        } while (c == 'c');
    }
}

Also I would like to how can I do this program only using while loop instead of do-while loop. When I was doing with only while I started with while(1) then break the loop with if statements from input, but that didn't work neither. Inside still there is two for loops.

Many thanks




Aucun commentaire:

Enregistrer un commentaire