How can I display an array from a void method? - java

I am a beginner with java and am trying to make a game of Yahtzee and am required to take a random dice roll as an array from a void method. Could someone explain to me why this wont work?
import java.util.Arrays;
public class YatzeeGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] diceRolls = new int[5];
diceRolls = throwDice(diceRolls);
System.out.println(display(diceRolls));
}
public static void throwDice(int [] dice) {
int [] roll = {(int)(Math.random()*6+1),
(int)(Math.random()*6+1),(int)(Math.random()*6+1),
(int)(Math.random()*6+1),(int)(Math.random()*6+1),
(int)(Math.random()*6+1)};
dice = roll;
}
public static String display(int [] dice) {
String str = Arrays.toString(dice);
str = str.replace("[", "");
str = str.replace("]", "");
str = str.replace("," , " ");
return str;
}

They want you to replace the array, which doesn't happen if you just assign it. Note that returning the array is still considered a better way. Extra tricky: in your existing code you make one array of size 5 and the other of size 6. Since you're calling it zahtzee we'll use 5.
public static void throwDice(int [] dice) {
for (int x = 0; x < 5; x++)
dice[x] = (int)(Math.random()*6+1);
}

There's quite a few things wrong in your code.
In the throwDice method, dice is a local variable, therefore changing it to roll, which is another local variable, doesn't affect anything outside that method.
Also your return type is void, so you cannot set any variable using the method.
You could have a method that returns an int[]:
public static int[] throwDice() {
int[] roll = new int[6];
for (int i = 0; i < 6; i++) {
roll[i] = (int) (Math.random() * 6) + 1;
}
return roll;
}
Then use it like:
int[] diceRolls = throwDice();

Explanation of why it's not working:
What you're trying to do: Change dice (the parameter you passed in) to equal to roll. Essentially, (if i'm not wrong here) you're trying to change diceRolls using throwDice.
What you're actually doing: You've passed in diceRolls and said "here, let's call it dice". Then, at the end of your function, you've essentially said "dice doesn't mean diceRolls anymore. dice now means roll". Which means that diceRolls still hasn't changed.
You need to change the actual values of dice instead of changing what dice is.
eg:
public static void throwDice(int[] dice) {
// change the actual values of dice, instead of changing dice
dice[0] = (int) (Math.random() * 6 + 1);
dice[1] = (int) (Math.random() * 6 + 1);
dice[2] = (int) (Math.random() * 6 + 1);
dice[3] = (int) (Math.random() * 6 + 1);
dice[4] = (int) (Math.random() * 6 + 1);
}

Related

How do I rerun a static integer array?

here's the array I want to rerun:
public static int[] rollDice(int dice[]) {
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}
If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.
There is no point in returning the array, since you already have a reference to the array when you call the method rollDice().
Arrays are sent by reference and not by value, which means you are not working with a copy like you do with ints, instead you are modifing the original array.
Change the return type to void and remove the return and your code should work as intended.
You can get every time a new dynamic length array with random numbers, and you can access by call rollDice(integer value).
public static int[] rollDice(int length) {
final int dice[] = new int [length];
// generate array with random values
for (int i = 0; i < length; i++) {
dice[i] = (int)(Math.random() * length + 1);
}
return dice;
}
You would have to have a class member like this:
public static final int[] dice = new int[5];
Then to roll/reroll the dice use your method, else just access dice.
public static void rollDice() {
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
}
Interesting fact: Java has no static function variables as C and C++ does. In those languages it could look like this:
(I wrote it like a java Function for you Java guys)
public static int[5] rollDice(boolean reroll) {
static final int[] dice = new int[5];
if (reroll) for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}
As you can see, static variables can be embedded into those functions. If you ask me, it's a huge minus, Java doesn't support this as I use it all the time to hide those from the class namespace.

Finding the occurrence of values within an array

My question is how do I find the frequency of the numbers "8" and "88" in this array, using a method. It seems as what I put in the assessor method does not appear to work. For example, if "8" occurs three times in the array the output would be "3" and the same for "88".
If I am wrong please point me to the right direction. Any help with my question is greatly appreciate.
import java.util.Random;
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
public void printArray() {
for (int i = 0; i < MAX_ARRAY_SIZE; ++i)
System.out.println(arr[i]);
}
public int countFrequency(int value) {
for (int i: MAX_VALUE) {
if (i == 8)
i++;
}
public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();
System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");
System.out.println("The frequency of 8 is: " + ap.countFrequency(8));
System.out.println("The frequency of 88 is: " + ap.countFrequency(88));
}
}
}
You need to iterate over arr and increment a variable when an element matches value.
public int countFrequency(int value) {
int count = 0;
for (int num : arr) {
if (num == value) {
count++;
}
}
return count;
}
You have a hard-coded seed, so your random values won't be random on different runs. You are also hard-coding your frequency count against 8 (instead of value). But honestly, I suggest you revisit this code with lambdas (as of Java 8), they make it possible to write the array generation, the print and the count routines in much less code. Like,
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// randomly fill array with numbers
Random rand = new Random();
arr = IntStream.generate(() -> rand.nextInt(MAX_VALUE) + 1)
.limit(MAX_ARRAY_SIZE).toArray();
}
public void printArray() {
IntStream.of(arr).forEachOrdered(System.out::println);
}
public int countFrequency(int value) {
return (int) IntStream.of(arr).filter(i -> i == value).count();
}
}
You need to iterate over the array and increment a counter variable when an element matches i
what you are doing is increment i instead of a counter:
if (i == 8)
i++;
} // if i is 8 then i becomes 9
A working example:
public int countFrequency(int i) {
int count = 0;
for (int num : arr) {
if (num == i) {
count++;
}
}
return count;
}
Solution:
public int countFrequency(int value) {
int counter = 0; // here you will store counter of occurences of value passed as argument
for (int i : arr) { // for each int from arr (here was one of your errors)
if (i == value) // check if currently iterated int is equal to value passed as argument
counter++; // if it is equal, increment the counter value
}
return counter; // return the result value stored in counter
}
Explanation:
Main problem in your code was countFrequency() method, there are few bugs that you need to change if you want to make it work correctly:
You passed value as argument and you didn't even use it in the body of method.
for (int i : MAX_VALUE ) - you meant to iterate over elements of arr array, (You can read it then as: For each int from arr array do the following: {...}.
if (i == 8) i++ - here you said something like this: Check if the current element from array (assuming that you meant MAX_VALUE is an array) is equal to 8, and if it is - increment this value by 1 (so if it were 8, now it's 9). Your intention here was to increment counter that counts occurences of 8.
You might want to consider making these improvements to countFrequency() method, to make it work properly.

How to store array values into a new array (JAVA) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Issue: I've completed steps 1-4 of this assignment. However, I'm currently stuck on steps 5 and 6 of this assignment, so I'm at a loss on how to combine my fizz and buzz String arrays into a separate fizzbuzz String array.
TL;DR I don't know how to do steps five and six.
Assignment:
You can do this all in the main method. This is using a game called
Fizz-Buzz, an ancient programmer’s game.
Start by initializing some variables to set the maximum and minimum value of a random number and for the capacity of an array.
(20/100)
Initialize three new arrays, one for a list of random numbers (as integers) and two for String arrays called ‘fizz’ and
‘buzz’.(20/100)
You’ll also need an integer for counting.
Write a for loop that generates a random number for each position in the array. Remember that the range for this will be set by
the two variables initialized at the beginning of the file. There are
multiple ways to create a random number, just find one that works for
you. (20/100)
Using the count of the arrays, create another array that will store all of the fizzes and buzzes without any extra space leftover in
the array. (20/100)
Use a for each loop to iterate the array and print all of the fizzes and buzzes, with no other output. (20/100)
What I've accomplished thus far:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Random;
/**
*
* #author
*/
public class FizzBuzz {
//2a. Initialize one int array for a list of random numbers.
private static int[] anArray;
private static final int size = 10;
//2b. Initialize two String arrays called 'fizz' and 'buzz.'
public static String[] fizz;
public static String[] buzz;
public static String[] fizzbuzz;
public static Random rand = new Random();
//1. Set the maximum and minimum value of a random number.
private static final int min = 0;
private static final int max = 5;
private static int count = 0;
public static int[] list() {
anArray = new int[size];
//3. Make an integer for counting("counter" in the for loop)
//4. Write a for loop that generates a random number for
// each position in the array.
for(count = 0; count < anArray.length; count++) {
anArray[count] = randomFill();
}
return anArray;
}
public static void print() {
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray[i] + ": " + fizz[i] + buzz[i]);
}
}
public static int randomFill() {
return rand.nextInt((max - min) + 1) + min;
}
public static String[] getF() {
fizz = new String[size];
int x = 0;
int counter;
for(counter = 0; counter < fizz.length; counter++) {
if(anArray[counter] % 3 == 0) {
fizz[counter] = "fizz";
} else {
fizz[counter] = "";
}
}
return fizz;
}
public static String[] getB() {
buzz = new String[size];
int x = 0;
int counter;
for(counter = 0; counter < buzz.length; counter++) {
if(anArray[counter] % 5 == 0) {
buzz[counter] = "buzz";
} else {
buzz[counter] = "";
}
}
return buzz;
}
public static String[] getFB() {
fizzbuzz = new String[size];
return fizzbuzz;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
list();
getF();
getB();
print();
}
}
First of all:
How Random works
Your implementation of Random won't quite work for simple reason:
If you call the default-constructor, the seed of the PRNG will be the current time, thus you're quite likely starting multiple PRNGs with the same seed and thus receive the same random-value multiple times. Use a single Random-instance instead:
private Random rnd = new Random();
public static int randomFill() {
return rnd.nextInt((max - min) + 1) + min;
}
This should help in understanding the issue better.
General implementation
Try to stick as close to the given task as possible. E.g. the problem explicitly states that you should use a variable to specify the length of the arrays, while you're using a fixed magic-number. The task explicitly states to use two arrays fizz and buzz, you're using one array called fizzbuzz.
Inside GetFizzBuff, you probably meant x = 2; instead of x = x + 2;. Apart from that this part is fine.
Output
As above: try to stick to the given task. It's explicitly stated to only output the fizzes and buzzes, not any integers. Or at least try to print a value and the corresponding fizzes and buzzes in the same line, to produce readable output.

How to shuffle a String array without using library and sort method?

I'm writing a deck with 52 cards. Everything is perfect but I can't figure out how to shuffle it without using any library from java and using the sort method built into java. Here is my code. I been trying to figure something out for a while and so far I'm unable to.
String [] deck2=new String [52];
String[] deck=new String [52];
String suits[]={"Spades","Hearts","Diamonds","Clubs"};
String rank[]={"2","3","4","5","6","7","8","9","10","Jack","King","Queen","Ace"};
for(int i=0;i<deck.length;i++){
deck[i]=rank[i%13]+" "+"of "+suits[i/13];
deck2[i]=deck[i];
System.out.println(deck[i]);
}}}
Of course it's possible. After all, a library is nothing more than some code you could as well write yourself. You'll have to write your own random number generator. This is one simple example:
private static long x = System.currentTimeMillis();
public static long rndNumber() {
x ^= (x << 21);
x ^= (x >>> 35);
x ^= (x << 4);
return x < 0 ? -x : x;
}
public static void shuffle(int a[]) {
for (int i = a.length - 1; i > 0; i--) {
int pos = (int) (rndNumber() % a.length);
int temp = a[i];
a[i] = a[pos];
a[pos] = temp;
}
}
public static void main(String[] args) {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println(Arrays.toString(a));
shuffle(a);
System.out.println(Arrays.toString(a));
}
for (int i = 0; i < 500; i++) {
int from = (int) (Math.random() * array.length); //The place to get the first from
int to = (int) (Math.random() * array.length); // The place to get the second from
String perm = array[from]; // Store the "from" value
array[from] = array[to]; // Set the first value to the second
array[to] = perm; // Set the second value to the first
}
I don't know, why you don't want to use a java built-in library, they are there for a reason.
To create a random number without any built in methods is hard. I found a way long time ago, using float, and making it overflow
float random = 1 << 32 + 1256224; //Have a random number here, it doesn't matter
I didn't tested it, this may not work.
float random = 1 << 32 + 1256224;
String [] deck2=new String [52];
String[] deck=new String [52];
String suits[]={"Spades","Hearts","Diamonds","Clubs"};
String rank[]={"2","3","4","5","6","7","8","9","10","Jack","King","Queen","Ace"};
for(int i=0;i<deck.length;i++){
deck[i]=rank[i%13]+" "+"of "+suits[i/13];
deck2[i]=deck[i];
System.out.println(deck[i]);
}
for (int i = 0; i < 500; i++) {
int from = (int) (Math.random() * array.length); //The place to get the first from
int to = (int) (Math.random() * array.length); // The place to get the second from
String perm = array[from]; // Store the "from" value
array[from] = array[to]; // Set the first value to the second
array[to] = perm; // Set the second value to the first
}
}}

how to assign random number with range to 2D array dimensions

In main, assign 2 random numbers (ints between 3 and 10) for the first dimension and the second dimension
I had this but the Math.random() method doesn;t work
import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
double doubMatrix1[][] = (int) (Math.random()*(10-3+1)+3);
double doubMatrix2[][];
double doubMatrix3[][];
}
}
The problem in your code is that you are trying to initialize a matrix of double with an int
Types must be equals!
Here are your code fixed.
import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
int d1 = (int) (Math.random()*(10-3+1)+3);
int d2 = (int) (Math.random()*(10-3+1)+3);
double doubMatrix1[][] = new double[d1][d2];
double doubMatrix2[][];
double doubMatrix3[][];
}
}
hope this help
To create a multidimensional array in Java, use new <type>[dim1][dim2], as in the following code:
Random rand = new Random();
int r1 = rand.nextInt(8) + 3;
int r2 = rand.nextInt(8) + 3;
double doubMatrix[][] = new double[r1][r2];
Math.random() returns fraction between 0.0 and 1.0. So with (int) (Math.random()*(10-3+1)+3) you are getting only one random number between 3 and 10 inclusive. But you are assigning it to double doubMatrix1[][]. So probably you are calling constructor in wrong way. You are supposed to generate two distinct random number r1, r2 according to the method taught by your teacher then call constructor like double doubMatrix1[][] = double[r1][r2]
check this out, this might be helpful:
// DMA of 2D array in C++
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int x = 3, y = 3;
int **ptr = new int *[x];
for(int i = 0; i<y; i++)
{
ptr[i] = new int[y];
}
srand(time(0));
for(int j = 0; j<x; j++)
{
for(int k = 0; k<y; k++)
{
int a = rand()%5;
ptr[j][k] = a;
cout<<ptr[j][k]<<" ";
}
cout<<endl;
}
}
we used a pointer and deal it just like 2D array here, use % for limit

Categories

Resources