Question

In: Computer Science

Java language Exercise #2: Design a Lotto class with one array instance variable to hold three...

Java language

Exercise #2:
Design a Lotto class with one array instance variable to hold three random integer values (from 1 to 9). Include a constructor that randomly populates the array for a lotto object. Also, include a method in the class to return the array.
Use this class in the driver class (LottoTest.java) to simulate a simple lotto game in which the user chooses a number between 3 and 27. The user runs the lotto up to 5 times ( by creating an object of Lotto class each time and with that three random integer values will be stored in objects’s array instance variable) and each time the sum of lotto numbers (sum of three random integers values) is calculated. If the number chosen by the user matches the sum, the user wins and the game ends. If the number does not match the sum within five rolls, the computer wins.


Exercise #3:
Write a Java class that implements a static method – SortNumbers(int… numbers) with variable number of arguments. The method should be called with different numbers of parameters and does arrange the numbers in descending order. Call the method within main method of the driver classand display the results.

Solutions

Expert Solution

Exercise 2#:

Screenshot of the code:

Sample Output:

Code to copy:

//Lotto.java:

//Import required packages.

import java.util.Random;

import java.util.Scanner;

//Define the class Lotto.

class Lotto

{

//Declare an instance variable for an array of

//integers.

private int[] randArr;

//Define the default constructor of the class Lotto.

public Lotto()

{

    //Create an array of 3 integers.

    randArr = new int[3];

    //Create an object of the class Random.

    Random ran = new Random();

    //Start a for loop till the size of the array.

    for(int i = 0; i < 3; i++)

    {

      //Generate a random number between 1 and 9 for

      //each array value.

      randArr[i] = ran.nextInt(9) + 1;

    }

}

//Define the function getRandArr().

public int[] getRandArr()

{

    //Return the array of 3 random integers between 1

    //and 9.

    return randArr;

}

}

//LottoTest.java:

//Define the class LottoTest.

class LottoTest

{

//Start the execution of the main() method.

public static void main(String[] args)

{

    //Create an object of the Scanner class.

    Scanner sc = new Scanner(System.in);

    //Declare and initialize required variables.

    int num, sumOfArrValues, isUserWin, index;

    isUserWin = 0;

    //Prompt the user to enter a number between 3 and

    //27.

    System.out.print("Choose a number between 3 and "

    + "27: ");

    num = sc.nextInt();

    //Start a while loop till the value entered by the

    //user is less than 3 or greater than 27.

    while(num < 3 || num > 27)

    {

      //Prompt the user to enter the number between 3

      //and 27 again.

      System.out.print("Please choose a valid number "

      + "between 3 and27: ");

      num = sc.nextInt();

    }

    //Start a for loop till the value of 5.

    for(index = 0; index < 5; index++)

    {

      //Create an object of the class Lotto.

      Lotto lottoObj = new Lotto();

      //Get the array from the function getRandArr() of

      //the Lotto class.

      int[] randArr = lottoObj.getRandArr();

     

      //Initialize the value of the variable

      //sumOfArrValues to 0.

      sumOfArrValues = 0;

      //Start another for loop till the size of the

      //array randArr.

      for(int i = 0; i < randArr.length; i++)

      {

        //Add array values to the variable

        //sumOfArrValues.

        sumOfArrValues = sumOfArrValues +

        randArr[i];

      }

      //If the value of the variable sumOfArrValues is

      //equal to the variable num, then display

      //message that user wins, set the value of the

      //variable isUserWin to 1 and break the loop.

      if(sumOfArrValues == num)

      {

        System.out.println("You win!");

        isUserWin = 1;

        break;

      }

    }

    //If the value of the variable isUserWin is still 0

    //and the value of the for loop index is 5, then

    //display the message computer wins.

    if(isUserWin == 0 && index == 5)

    {

      System.out.println("Computer wins!");

    }

}

}

Exercise 3#:

Note: The code for the required function SortNumbers() is highlighted in grey and bold in the code given below.

Screenshot of the code:

Sample Output:

Code to copy:

//Import the required package.

import java.util.Arrays;

//Define the class Main.

class Main

{

//Define the static method SortNumbers() having a

//variable number of arguments.

public static void SortNumbers(int... numbers)

{

    //Declare and initialize the required variables.

    int index, temp;

    index = temp = 0;

    //Create an integer array of size equal to the

    //length of the given parameter of the function

    //numbers.

    int[] integerArr = new int[numbers.length];

   

    //Start a for each loop over numbers.

    for(int num : numbers)

    {

      //Assign num to the current array value.

      integerArr[index++] = num;

    }

    //Traverse the array using nested for loops.

    for(int i = 0; i < integerArr.length; i++)

    {

      for(int j = i + 1; j < integerArr.length; j++)

      {

        //If the value of the array at index i is less

        //than the value of the array integerArr at

        //index j.

        if(integerArr[i] < integerArr[j])

        {

          //Swap both values using a third variable

          //temp.

          temp = integerArr[i];

          integerArr[i] = integerArr[j];

          integerArr[j] = temp;

        }

      }

    }

    //Display array values after sorting using a for

    //loop.

    System.out.println("Array after sorting:");

    System.out.print("[");

    for(int arr_index = 0; arr_index <

    integerArr.length; arr_index++)

    {

      if(arr_index != (integerArr.length - 1))

      {

        System.out.print(integerArr[arr_index]

        + ", ");

      }

      else

      {

        System.out.println(integerArr[arr_index]

        + "]");

      }

    }

}

//Start the execution of the main() method.

public static void main(String[] args)

{

    //Call the function SortNumbers() using variable

    //number of arguments.

    SortNumbers(1, 2, 5, 10, 4, 6);

    System.out.println();

    //Call the function SortNumbers() using variable

    //number of arguments.

    SortNumbers(7, 12, 8, 11);

}

}


Related Solutions

swift language declare a Swift array variable that can hold instances of any class type
swift language declare a Swift array variable that can hold instances of any class type
Language: Java Question:Using your Circle class (or the one provided below), create a Circle array of...
Language: Java Question:Using your Circle class (or the one provided below), create a Circle array of size 4 in a driver class using the following statement: Circle circleArr[] = new Circle[4]; Populate the array with four different radiuses and then, using a for loop from 0 to one less then the length of the array, print the area and the diameter of each of the four circles Circle Class: import java.text.DecimalFormat; public class Circle {    DecimalFormat dec = new...
in bluej java Write an application with two classes. Class NumberUtility has one instance variable n...
in bluej java Write an application with two classes. Class NumberUtility has one instance variable n of type int. Constructor initializes instance variable n by using input parameter n. public NumberUtility(int n) Class also has the following methods:   public int getN()                              // Returns instance variable n public boolean isOdd()                  // Returns true if number n is odd and returns false otherwise. public boolean isEven()               // Returns true if number n is even and returns false if it is odd.      // Implement method by...
Question(Design Java Method). There is a java code what created a "Student" class and hold all...
Question(Design Java Method). There is a java code what created a "Student" class and hold all the books owned by the student in the inner class "Book". Please propose a new method for the Student class so that given a Student object "student", a program can find out the title of a book for which student.hasBook(isbn) returns true. Show the method code and the calls to it from a test program. The Student class is following: import java.lang.Integer; import java.util.ArrayList;...
In java beginner coding language ,Write a class called Sphere that contains instance data that represents...
In java beginner coding language ,Write a class called Sphere that contains instance data that represents the sphere’s diameter. Define the Sphere constructor to accept and initialize the diameter, and include getter and setter methods for the diameter. Include methods that calculate and return the volume and surface area of the sphere. Include a toString method that returns a one-line description of the sphere. Create a driver class called MultiSphere, whose main method instantiates and updates several Sphere objects.
PUT IN JAVA PROGRAMMING LANGUAGE The Rectangle class: Design a class named Rectangle to represent a...
PUT IN JAVA PROGRAMMING LANGUAGE The Rectangle class: Design a class named Rectangle to represent a rectangle. The class contains: • Two double data fields named width and height that specify the width and height of a rectangle. The default values are 1 for both width and height. • A no-arg (default) constructor that creates a default rectangle. • A constructor that creates a rectangle with the specified width and height. • A method named findArea() that finds the area...
(JAVA) Referencing the class Oven, complete the Constructor and set method for the instance variable temp....
(JAVA) Referencing the class Oven, complete the Constructor and set method for the instance variable temp. Constructor checks if the temperature is between 0 and 500. If the temperature does not fit the requirement, then set the temperature to be zero. Otherwise, set it to be the value passed to the constructor. Set the power to be off. Set the String to be the color passed to the constructor. Use the same requirement for the constructor for the set temperature...
Part A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array...
Part A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array of integers, the length of the array, and an integer, say, removeItem. The method should find and delete the first occurrence of removeItem in the array. If the value does not exist or the array is empty, output an appropriate message. (Note that after deleting the element, the array size is reduced by 1.) Here you assume the array is not sorted. Do not...
art A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array...
art A) Java Programming Exercise #2: Write a method, remove, that takes three parameters: an array of integers, the length of the array, and an integer, say, removeItem. The method should find and delete the first occurrence of removeItem in the array. If the value does not exist or the array is empty, output an appropriate message. (Note that after deleting the element, the array size is reduced by 1.) Here you assume the array is not sorted. Do not...
true or false give reason language in java 1.A static inner class can access the instance...
true or false give reason language in java 1.A static inner class can access the instance variables and methods of its outer non-static class 2.executeQuery from statement may return more than one resultset object 3.Connection is java.sql interface that establishes a session with a specific database 4.Writable is an interface in Hadoop that acts as a wrapper class to almost all the primitive data type 5.Text is the wrapper class of string in Hadoop
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT