Java SlotMachine class - java

I am writing a slot machine class that generates 3 arrays of 3 random numbers and checks if all of the numbers match, if so they are declared a winner. I have written another program to run 1000 slot machines and count the winners. The problem I am facing is that it always gives me 0 winners. Any help? Here is the code for each:
the SlotMachine class
import java.util.*;
public class SlotMachine{
private int[] row1 = new int[3];
private int[] row2 = new int[3];
private int[] row3 = new int[3];
public SlotMachine() {
playMachine();
}
public void playMachine() {
Random rand = new Random();
for (int counter = 0; counter < 3; counter++) {
row1[counter] = rand.nextInt(10);
}
for (int counter = 0; counter < 3; counter++) {
row2[counter] = rand.nextInt(10);
}
for (int counter = 0; counter < 3; counter++) {
row3[counter] = rand.nextInt(10);
}
}
public boolean isWinner() {
if (row1[0] == row1[1]) {
if (row1[0] == row1[2]) {
return true;
}
}
if (row2[0] == row2[1]) {
if (row2[0] == row2[2]) {
return true;
}
}
if (row3[0] == row3[1]) {
if (row3[0] == row3[2]) {
return true;
}
}
return false;
}
}
The win counter:
import java.util.*;
public class Play1000SlotMachines {
public static void main(String[] args) {
SlotMachine slotMachine = new SlotMachine();
int count = 0;
for (int i = 0; i < 1000; i++) {
if (slotMachine.isWinner() == true) {
count = count + 1;
}
}
System.out.println("From 1000 slot machines, " + count + " were winners.");
}
}

You never re-roll the slot machine. I also changed the name of the method, to reflect this implementation. If you would rather play 1000 different slot machines, move the declaration of a new slot machine into the for loop. This will create 1000 different instances of the slot machine class, rather than the below implementation where a single instance of a slot machine is created which is then played 1000 times. An important distinction.
public class PlaySlotMachine1000Times {
public static void main(String[] args) {
SlotMachine slotMachine = new SlotMachine();
int count = 0;
for (int i = 0; i < 1000; i++) {
slotMachine.playMachine();
if (slotMachine.isWinner())
count++;
}
System.out.println("From 1000 slot machines, " + count + " were winners.");
}
}

Related

Connecting a variable in the main method with another method Java

The method should return true if the argument is even, or
false otherwise. The program’s main method should use a loop to generate 100 random integers. It should use the isEven method to determine whether each random number is even, or odd. All this is done!!!
This is the part where I can't figure it out!
When the loop is finished, the program should display the number of even numbers that were generated, and the number of odd numbers.
This is my code:
import java.util.Random;
public class EvenOdd
{
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
EvenOdd(randomInteger);
}
}
public static void EvenOdd(int x)
{
int oddNumbers = 0;
int evenNumbers = 0;
if ((x % 2) == 0)
{
System.out.println("Even");
evenNumbers++;
}
else
{
System.out.println("Odd");
oddNumbers++;
}
}
}
Try with this:
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
int oddNumbers = 0;
int evenNumbers = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
if(evenOdd(randomInteger)) evenNumbers++;
else oddNumbers++;
}
System.out.printf("Even numbers: %d - Odd numbers: %d", evenNumbers, oddNumbers);
}
public static boolean evenOdd(int x)
{
if ((x % 2) == 0)
{
System.out.println("Even");
return true;
}
else
{
System.out.println("Odd");
return false;
}
}
Your original approach doesn't work because you initialize to 0 the oddNumbers and evenNumbers variables everytime you call the method.
Define oddNumbers, evenNumbers variables as static class variables and after the loop you can print these 2 value.
Java is not JavaScript. Also, it does not have the ability of C++ as "Static variables in functions".
Variables declared inside a method are local. Variables initialization occurs every time your code reaches a variable definition inside the method and destroyed after exiting from the method.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
So you have such variants:
1) Count numbers inside your main method and return indicator from the utility method.
1.1) boolean
public static boolean isEven(int x){
return (x % 2) == 0;
};
1.2) enum
private enum NumberType {
EVEN,
ODD
}
public static NumberType getNumberType (int x) {
if ((x % 2) == 0) {
return NumberType.EVEN;
} else {
return NumberType.ODD;
}
};
2) Make your variables static:
public class EvenOdd {
private static int evenNumbersCount = 0;
private static int oddNumbersCount = 0;
public static void main(String[] args) {
// your code
}
public static void countNumberType (int x) {
if ((x % 2) == 0) {
++evenNumbersCount;
} else {
++oddNumbersCount;
}
}
}
3) In some sophisticated situations you will need to pass container to your method:
public class EvenOdd {
private static final String EVEN = "even";
private static final String ODD = "odd";
public static void main(String[] args) {
// initialize container
Map<String, Integer> evenOddCounts = new HashMap<>(2, 1);
evenOddCounts.put(EVEN, 0);
evenOddCounts.put(ODD, 0);
Random random = new Random();
int randomInteger = 0;
for (int i = 0; i < 100; i++) {
randomInteger = random.nextInt();
countNumberType(evenOddCounts, randomInteger);
}
System.out.println(evenOddCounts.toString());
}
public static void countNumberType(Map<String, Integer> counts, int x) {
if ((x % 2) == 0) {
counts.compute(EVEN, (numberType, count) -> ++count);
} else {
counts.compute(ODD, (numberType, count) -> ++count);
}
}
}

How to fill a multidimensional array dependant on variables

The program I am working on is a simple shipping program. What I am having difficulty with is populating a multidimensional array factoring in certain variables.
Example
320 items need to be shipped out to 1 receiver using different box sizes.
XL can hold 50 items
LG can hold 20 items
MD can hold 5 items
SM can hold 1 items
Use the least number of boxes so far.
Code
This is my code so far.
import java.util.Scanner;
public class Shipping {
public static void main(String [] args) {
Scanner kbd = new Scanner(System.in);
final int EXTRA_LARGE = 50;
final int LARGE = 20;
final int MEDIUM = 5;
final int SMALL = 1;
String sBusinessName = "";
int iNumberOfGPS = 0;
int iShipmentCount = 0;
displayHeading(kbd);
iShipmentCount = enterShipments(kbd);
int[][] ai_NumberOfShipments = new int [iShipmentCount][4];
String[] as_BusinessNames = new String [iShipmentCount];
for (int iStepper = 0; iStepper < iShipmentCount; iStepper++) {
sBusinessName = varifyBusinessName(kbd);
as_BusinessNames[iStepper] = sBusinessName;
iNumberOfGPS = varifyGPS(kbd);
calculateBoxes(ai_NumberOfShipments[iStepper],iNumberOfGPS, EXTRA_LARGE, LARGE, MEDIUM, SMALL);
}
//showArray(as_BusinessNames);
}
public static void displayHeading(Scanner kbd) {
System.out.println("Red River Electronics");
System.out.println("Shipping System");
System.out.println("---------------");
return;
}
public static int enterShipments(Scanner kbd) {
int iShipmentCount = 0;
boolean bError = false;
do {
bError = false;
System.out.print("How many shipments to enter? ");
iShipmentCount = Integer.parseInt(kbd.nextLine());
if (iShipmentCount < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
bError = true;
}
} while (bError == true);
return iShipmentCount;
}
public static String varifyBusinessName(Scanner kbd) {
String sBusinessName = "", sValidName = "";
do {
System.out.print("Business Name: ");
sBusinessName = kbd.nextLine();
if (sBusinessName.length() == 0) {
System.out.println("");
System.out.println("**Error** - Name is required\n");
} else if (sBusinessName.length() >= 1) {
sValidName = sBusinessName;
}
} while (sValidName == "");
return sValidName;
}
public static int varifyGPS(Scanner kbd) {
int iCheckGPS = 0;
int iValidGPS = 0;
do {
System.out.print("Enter the number of GPS receivers to ship: ");
iCheckGPS = Integer.parseInt(kbd.nextLine());
if (iCheckGPS < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
} else if (iCheckGPS >= 1) {
iValidGPS = iCheckGPS;
}
} while(iCheckGPS < 1);
return iValidGPS;
}
public static void calculateBoxes(int[] ai_ToFill, int iNumberOfGPS) {
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++)
}
//public static void showArray( String[] ai_ToShow) {
// for (int iStepper = 0; iStepper < ai_ToShow.length; iStepper++) {
// System.out.println("Integer at position " + iStepper + " is " + ai_ToShow[iStepper]);
// }
//}
}
Change your definition of calculateBoxes() to also take an array that represents the volume of each of the boxes (in your case this will be {50, 20, 5, 1}:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
// while the remaining items to pack is greater than the current box size
while(iNumberOfGPS >= boxVolumes[iStepper]) {
// increment the current box type
ai_ToFill[iStepper]++;
// subtract the items that just got packed
iNumberOfGPS -= boxVolumes[iStepper];
}
}
}
Another way of calculating this (using / and % instead of a while loop) would be:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
if(iNumberOfGPS >= boxVolumes[iStepper]) {
// calculate the number of boxes that could be filled by the items
ai_ToFill[iStepper] = iNumberOfGPS/boxVolumes[iStepper];
// reset the count of items to the remainder
iNumberOfGPS = iNumberOfGPS%boxVolumes[iStepper];
}
}
}

How to count the occurrences of random instances

For example I have a programming assignment that wants me to make a coin class and a driver class that randomly flips a coin 40 times and then counts at the very end how many times it ends up heads and tails. Well I got the entire code so far it being:
public class driver {
public static void main(String[] args) {
coin myCoin = new coin();
System.out.println("Coin initially is " + myCoin.getSideUp());
for (int i = 0; i < 40; i++) {
myCoin.toss();
System.out.println("Coin is now " + myCoin.getSideUp());
}
}
}
public class coin {
protected String sideUp;
public coin() {
if (Math.random() < 0.5)
this.sideUp = "heads";
else
this.sideUp = "tails";
}
public void toss() {
if (Math.random() < 0.5)
this.sideUp = "heads";
else
this.sideUp = "tails";
}
public String getSideUp() {
return this.sideUp;
}
}
That's all done, but how do I count the instances of each heads or tails?
Count them as the tosses are made instead of at the end. If the assignment prohibits this, save the results to an array and count the results from the array at the end.
Just check and see if your coin is head or tail after each toss.
You could keep the counter for each status(head/tail) in an array like below:
Coin myCoin = new Coin();
System.out.println("Coin initially is " + myCoin.getSideUp());
int[] coinCount = new int[2];
for (int i = 0; i < 40; i++) {
myCoin.toss();
System.out.println("Coin is now " + myCoin.getSideUp());
if(myCoin.getSideUp().equals("heads")){
coinCount[0]++;
} else {
coinCount[1]++;
}
}
System.out.println("Heads: "+coinCount[0]);
System.out.println("Tails: "+coinCount[1]);

How to run one Java class and then another Java class in Eclipse?

I know it may be weird question but I'm really stuck. I have simple program with two classes. I need pass array from class A to class B. I did it but I cannot test it because I have no idea how to run program. When I click on the run then only one class started. I wanted test whole program and cannot find anything how to do it. Is there any command or something which say run class A and then class B? Without it I cannot test class B because values from Array (class A) are not loaded :/ Hope you understand what I mean.
I'm using eclipse.
Thanks!
Class MarkCalculator
import java.util.Scanner;
public class MarkCalculator {
public static int[] exam_grade = new int[6];
public static int[] coursework_grade = new int[6];
public static int[] coursework_weight = new int[2];
public static int[] module_points = new int[6];
public static String module_grade, holder;
public static int counter1 = 0, counter2 = 0;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
for (int i=0; i<3; i++){
System.out.printf(i+1+". Modelue"+" Enter grade of exam:");
while (!input.hasNextInt() ){
System.out.printf("Enter only numbers! Enter grade of your exam: ");
input.next();
}
exam_grade[i]=input.nextInt();
System.out.printf(i+1+". Modelue"+" Enter grade of coursework:");
while (!input.hasNextInt()){
System.out.printf("Enter only numbers! Enter grade of your coursework: ");
input.next();
}
coursework_grade[i]=input.nextInt();
}
computeMark(coursework_grade, exam_grade, module_points);
// calculate module grade
for(int i = 0 ;i < 3; i++){
if (module_points[i] < 35){
System.out.println(i+1+".Module: Fail");
}
else if (module_points[i] >= 35 && module_points[i] <= 40){
System.out.println(i+1+".Module: Pass by compensation");
counter1++;
}
else {
System.out.println(i+1+".Module: Pass");
counter2++;
}
}
holder = computeResult(module_points, counter1,counter2, module_grade);
System.out.println("Your stage result is: "+ holder);
input.close();
}
public static int[] computeMark (int coursework_grade[], int exam_grade[], int module_points[]){
coursework_weight[0]= 50;
coursework_weight[1]= 50;
for(int i=0;i<3;i++)
{
if (coursework_grade[i] < 35 || exam_grade[i] < 35){
module_points[i]=(coursework_grade[i]*coursework_weight[0] + (exam_grade[i]*(100-coursework_weight[1])))/100;
if (module_points[i] > 35){
module_points[i] = 35; }
else {
module_points[i] = 0;
}
}
else {
module_points[i]=((coursework_grade[i]*coursework_weight[0] + (exam_grade[i]*(100-coursework_weight[1])))/100); }
}
return module_points;
}
public static String computeResult (int module_points[], int counter1, int counter2, String module_grade ){
int sum = 0;
double average = 0;
for (int i = 0; i < 3; i++){
sum = sum + module_points[i];
average = sum / 3;
}
for (int i = 0; i < 3; i++){
if (counter2 == 3){
module_grade = "Pass";
}
else if (average >= 40 && counter1 <= 2) {
module_grade = "Pass by compensation";
}
else {
module_grade = "Fail";
}
}
return module_grade;
}
}
Class StudentChart
public class StudentChart {
public static void main(String[] args) {
for (int i = 0; i < 3; i++){
System.out.println(MarkCalculator.coursework_weight);
}
}
}
You only need one main method.
class A {
String s;
public A(String s){
this.s = s;
}
}
public class B {
public static void main(String[] args){
A a = new A("Hello");
System.out.println(a.s + " world!");
}
}
class B will be the application program, the one with the main method. It will get values from class A. class A does not need to run for class B app to work, even though it uses values from class A.
You can have a method with a different name in another class, and call that method from your main method.
Do not call it public static void main though - that should only be used for standalone programs. If the method requires some other code to be run prior to it, it should not be the main method of a Java program.

First time working with arrays, trying to create frequency table

I can't see where I'm going wrong with this one, I want it to display the frequencies of the survey's result but all I get is zeros, for example if I enter 1,1,2,2,5 I want it to output:
Displaying response frequencies...
1 2
2 2
3 0
4 0
5 1
but instead I get this:
Displaying response frequencies...
1 0
2 0
3 0
4 0
5 0
here is my main method:
import java.util.Scanner;
public class SurveyTester {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many people took the survey?");
int numPeople = input.nextInt();
Survey s = new Survey(numPeople);
int nextResponse;
for (int i = 0; i < numPeople; i++)
{
System.out.print("Input the next survey response (values 1-5):");
nextResponse = input.nextInt();
s.addResponse(nextResponse);
}
System.out.println("Displaying all responses...");
s.displayAllResponses();
System.out.println("Displaying response frequencies...");
s.displayResponseFrequencies();
}
}
here is my class:
public class Survey
{
private int numResponses;
private int maxResponses;
private int[] responses;
private int[] frequencies;
private final int NUM_RESPONSES = 5;
public Survey(int nResponses)
{
maxResponses = nResponses;
numResponses = 0;
responses = new int[nResponses];
frequencies = new int[NUM_RESPONSES]; // There are 5 possible responses to the survey
}
public void addResponse(int response)
{
// This method stores the response
// passed in the parameter 'response'
// to the next free space in the array
{
responses[numResponses]= response;
}
numResponses++;
}
public void displayAllResponses()
{
// This method displays on the screen
// all the responses to the survey
for (int i=0; i<maxResponses; i++)
{
System.out.print(responses[i] + " ");
}
System.out.println("");
}
public void calculateResponseFrequencies()
{
// This method calculates the number of
// responses for each possible answer
// to the survey, 1, 2, 3, 4 or 5
// It stores the frequencies in the
// array 'frequencies'
for (int i=1; i<=maxResponses; i++)
{
if (responses[i] == 1)
{
frequencies[1]++;
}
else if (responses[i] == 2)
{
frequencies[2]++;
}
else if (responses[i] == 3)
{
frequencies[3]++;
}
else if (responses[i] == 4)
{
frequencies[4]++;
}
else if (responses[i] == 5)
{
frequencies[5]++;
}
}
}
public void displayResponseFrequencies()
{
// This method displays the response
// frequences for each of the possible
// response, 1, 2, 3, 4 or 5
for (int i=0; i<frequencies.length; i++)
{
System.out.println((i+1) + "\t" + frequencies[i]);
}
}
}
You are not doing anything with your frequencies array. In you your addResponse method, you need to get the appropriate value and increment it. Add a statement like
frequencies[response-1] = frequencies[response-1] + 1;
Note you can do this with 2 arrays, as you are, especially for learning, but a lot of Java developers would use a Map implementation for this sort of thing, where the keys are the entered values and the values are the frequencies. Keeps all the data in one data structure.
public class DuplicatesInArray {
public static void main(String[] args) {
int count = 0;
int[] arr = new int[6];
int[] frequencyArr = new int[6];
arr[0] = 4;
arr[1] = 1;
arr[2] = 1;
arr[3] = 1;
arr[4] = 5;
arr[5] = 4;
for(int i = 0;i < arr.length;i++){
frequencyArr[arr[i]] = frequencyArr[arr[i]] + 1;
}
for(int x = 0;x<frequencyArr.length;x++){
if(frequencyArr[x] > 0){
System.out.println(x + " " + frequencyArr[x] + " times." );
}
}
}
}
Default value in an integer array will be zero. We increment it by one for every occurrence.
Example:If integer 4 occurs 2 times,4th index at the frequencyArr is incremented twice.

Categories

Resources