Home>

<<<<<<<Probex5_1 Problem sentence>>>>>>>>
Create a program that generates a random number from 0 to 10 and displays the value as shown below, and when 0 appears, displays all the integers that have been input so far, divided into odd and even numbers. At this time, input odd and even values ​​should be stored in separate variable-length arrays created by ArrayList.

import java.util.ArrayList;
public class Probex5_1 {
        public static void main (String [] args) {
        ArrayList&lt;Number&gt;al = new ArrayList&lt;Number&gt;();
        al.add (new Number ("odd", 1, 3, 5, 7));
        al.add (new Number ("even", 2, 4, 6, 8));
        while (true) {
            int a = (int) (Math.random () * 10);
            System.out.println ("Output value from 0 to 10:" + a);
            if (a == 0) {
                break;
            }
        }
        System.out.println ("Exit" + "");
    }
}


I wrote like this. An error has not been taken.
Please tell me someone.

  • Answer # 1

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Random;
    public class Probex5_1 {
            public static void main (String [] args) {
            List<Integer>evens = new ArrayList<Integer>();
            List<Integer>odds = new ArrayList<Integer>();
            List [] lists = {evens, odds};
            while (true) {
                Random rnd = new Random ();
                int v = rnd.nextInt (10);
                System.out.println ("Output value from 0 to 10:" + v);
                if (v == 0) {
                    break;
                }
                lists [v% 2] .add (v);
            }
            System.out.println (Arrays.toString (odds.toArray ()));
            System.out.println (Arrays.toString (evens.toArray ()));
        }
    }


    Execution example:

    Addition:

    In the above code, a warnign appeared, so it was resolved.

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Random;
    public class Probex5_1 {
        public static void main (String [] args) {
            List<Integer>evens = new ArrayList<Integer>();
            List<Integer>odds = new ArrayList<Integer>();
            List<List<Integer>>lists = Arrays.asList (evens, odds);
            while (true) {
                Random rnd = new Random ();
                int v = rnd.nextInt (10);
                System.out.println ("Output value from 0 to 10:" + v);
                if (v == 0) {
                    break;
                }
                lists.get (v% 2) .add (v);
            }
            for (List<Integer>ls: lists) {
                System.out.println (Arrays.toString (ls.toArray ()));
            }
        }
    }

Related articles