I need to store a random number into an array and then be able to compare the array sums at a later time. So far I have this:
public class Die {
private int dieValue = 0;
private Random randomNumbers = new Random();
public Die() {
}
public void rollDie() {
dieValue = randomNumbers.nextInt(6*1);
}
public void displayDie() {
int[] die = new int[3];
for(int counter = 0; counter<die.length; counter++ ) {
rollDie();
die[counter] = dieValue;
}
System.out.print("Your Dies are: " + die[1] + " and " + die[2] + " and "
+ die[3]);
dieValue = die[1] + die[2] + die[3];
}
This gives me an error saying the array index is out of bounds, and i'm not sure how to properly code this.. any tips would be great!
In Java, arrays start at index 0, so an array of size 3 (like you've made) will have indices 0,1,2. The out of bounds is because you're trying to used indices 1,2,3 (3 does not exist).
Also, you're saying that you need to access the values at a later time, so you should probably declare the array outwith the method, so that it persists after the method finishes (just now, due to the scope of the variable, it will disappear after displayDie() finishes.)
When you are trying to access the first value stored in an array the index should be 0, in you code above you try to access the 3 values as die[1], die[2], and die[3], but you need to be accessing them as die[0], die[1], and die[2].
Indexes for the die array in the displayDie() method are off, array index in Java starts from 0. First value will be die[0] instead of die[1].
Last line you have
dieValue = die[1] + die[2] + die[3];
and suppose to be
dieValue = die[0] + die[1] + die[2];
because there's not die[3] that's why you get the error
What you can do and will be better to loop the array
for(int i=0; i< die.length; i++){
dieValue +=die[i];
}
Related
My issue is that the array called myMarks[]; gets placement (myMarks[increase]) values set through the integer increase and the number to be set to is myMark which is inputted by the user.
int increase = 0; //initializing var
int myMarks[];
private void ConfirmButtActionPerformed(ActionEvent evt) {
// setting the size of the array to never end (first loop is 0+1 then 1+1, etc.)
int myMarks[] = new int[increase + 1];
// showing the size of the array
System.out.println("Array length: " + myMarks.length);
// getting inputted mark
int myMark = Integer.parseInt(Mark.getText());
myMarks[increase] = myMark;
// checking value of increase each loop
System.out.println("Position: " + increase);
// so i can show the mathematically incorrect to user
int forCosmetic = increase + 1;
// sets next line of MarkShow to the new array value
MarkShow.append("Mark " + forCosmetic + ", " + myMarks[increase] + "\n");
// showing value of myMarks
System.out.println(myMarks[increase]);
//Updating each loop
increase++;
}
This is inside of a JFrame.
For example, if you the user inputted 50 for the array through the variable myMark, it would first show up in the array as: 50. The issue is when we continue the loop with the same value, the array myMarks is now: 0, 50. If we loop again it would be 0, 0, 50 and so on.
I think what you're trying to do is change the size of an array but you're not doing it correctly. Please add comments / questions if I misunderstood your question.
To copy change an existing array, you must first allocate a new temporary copy. Then you must copy all the elements of the old array into the new array (a shallow copy is almost always fine). Then you have to assign the new temporary copy to the old array.
(As Viswa commented, using List<Integer> would probably be better here. But if you must do this manually, this is the correct way to do it.)
int increase = 0; //initializing var
int myMarks[];
private void ConfirmButtActionPerformed(java.awt.event.ActionEvent evt) {
//setting the size of the NEW array to never end (first loop is 0+1 then 1+1, etc.)
int temp[] = new int[1+increase];
// IMPORTANT: must copy old array values
System.arraycopy( myMarks, 0, temp, 0, myMarks.length );
// now assign the temp copy so it replaces the original
myMarks = temp;
int myMark = Integer.parseInt(Mark.getText()); //getting inputted mark
myMarks[increase] = myMark;
int forCosmetic = increase + 1;
// ... other code...
//Updating each loop
increase++;
}
I want to get the minimum number of my array, but my "if" compare only checks the first and last positions of array.
Here is my code:
int[] randNumbers = new int[20]; //deklaracja nowej tablicy 20-elementowej
Random r = new Random(); // Dodana metoda random do losowania
for(int i=0; i<randNumbers.length; i++) {
randNumbers[i] = r.nextInt(101);
int min = randNumbers[0];
System.out.println("Number "+i+": " + randNumbers[i]);
if (randNumbers[i] < min) {
min = randNumbers[i];
}
if (i == randNumbers.length-1) {
System.out.println("Min number is: " + min);
}
}
You don't even need the array here. Just iterate from 0 to N and check each random number if it less than min:
Random r = new Random();
int min = 101; // assign max value 101 before loop
for(int i = 0; i < 20; i++) {
int number = r.nextInt(101);
System.out.println("Number " + i + ": " + number);
if (number < min) {
min = number;
}
}
System.out.println(min);
If you want use array, you could initialize it before. For example using Random.ints():
int[] randNumbers = new Random().ints(20, 0, 101).toArray();
And then use the same for-loop idea with randNumbers[i] instead of nextInt(101)
try this out, your int min = randNumbers[0]; resets the min value every time so move it out of the loop
int min = 100;
for(int i=0; i<randNumbers.length; i++) {
randNumbers[i] = r.nextInt(101);
System.out.println("Number "+i+": " + randNumbers[i]);
if (randNumbers[i] < min) {
min = randNumbers[i];
}
}
System.out.println("Min number is: " + min);
The issue is that you are not remembering the minimum number as the loop runs. If you make a variable outside of the loop, it won't get updated every single iteration. Your code might look something like this:
int[] randNumbers = new int[20]; //deklaracja nowej tablicy 20-elementowej
Random r = new Random(); // Dodana metoda random do losowania
int min = 0;
for(int i=0; i<randNumbers.length; i++) {
int number = r.nextInt(101);
if(i == 0) min = number;
randNumbers[i] = number;
System.out.println("Number "+i+": " + number);
min = Math.min(min, number);
}
System.out.println("Min number is: " + min);
A few things to notice:
The variable min was moved outside of the loop. This is to make sure it is persistent across the loop, and won't be updated every iteration of the loop.
A new variable number is introduced. This is to prevent you from constantly calling randNumbers[i], which looks nicer, and to my knowledge slightly speeds it up. It also make it easier to change the variable once, and have it effective everywhere it is needed.
The last S.O.P was moved outside of the loop. There is no point in checking if the loop is at the last element if you can just put the statement the line after the loop ends. It will work the same functionally, but this looks nicer.
Instead of using an if statement to set min, it uses the output of Math.min. This is just a cosmetic change, and behaves the exact same with an if statement.
Move min int outside loop with value 0 isn't working, because my result will be everytime because Not initialized array have only '0'
Move it with 100+ is good idea. It's working when we know maximum number.
#geneSummons "int min = Integer.MAX_INT"
This works very well with different range/scope of numbers:) Thanks
Btw. I still don't understand why it's compare only first and last number ;)
problem with Java code.
import java.util.Random;
public class arrayTable {
public static void main (String[] args) {
System.out.println("Index\t + Value");
int Array[] = new int[10];
Random Object = new Random();
int Values;
// Assigning random values to each element of array
for(int i=0; i<Array.length;i++) {
Values= (1+Object.nextInt(50));
Array[i] = Values;
}
for(int j=0;j<Array.length;j++) {
System.out.println(j + "\t" + Array[j]);
}
}
}
Here with this code i wrote (1+) next to the object so the index should start at 1, however when ever i run the code at always starts at index 0, and it does not matter if i type 2+ or 3+ pr whatever. Could anyone be helpful with pointing out the problem with the code.
thank you in advance.
i wrote (1+) next to the object so the index should start at 1
You wrote 1+ next to the value not the index!
So, what you were doing was:
array[0] = 50 + 1;
Instead of:
array[0 + 1] = 50;
If you wanted to start from index 1 you should write it here:
Array[i + 1] = Values;
However as you're inside a for loop, you could run into an ArrayIndexOutOfBoundsException, so, a better idea would be:
for(int i=1; i<Array.length;i++) { //Look the "i" was initialized with 1 and not with 0.
REMEMBER: ARRAYS START FROM 0 INDEX
If you want to "skip" the first element, then the above modification to for loop should work, but if you want it to run from 1 to 10 then it's a bad idea, because it should be from 0 to 9
You should also be careful to follow the Java naming conventions:
firstWordLowerCaseVariable
firstWordLowerCaseMethod()
FirstWordUpperCaseClass
ALL_WORDS_UPPER_CASE_CONSTANT
and use them consistently, this will make your code easier to read and understand for you and for us.
Also, try not to name your classes / variables as Java classes names:
Object or Array or List, etc might be wrong choices, also having object lowercase would be a bad idea as it's not descriptive either as suggested by #nicomp on the comments below
but when i type Array [i + 1] it still prints out from index 0, if for example i where to make i dice i would want it to start at index 1, is there no way to do this?
I think you didn't changed the for(int j=0;j<Array.length;j++) { loop, to start from 1
To make a dice I would:
Create the array with 6 slots (starting from 0)
Fill it (1 - 6) like below (inside a for loop):
dice[0] = 1;
dice[1] = 2;
...
dice[5] = 6;
//Example of for loop
for (int i = 0; i < dice.length; i++) {
dice[i] = i + 1;
}
Get a random number (between 0 - 5) called random
Get the value of the array at position random
For example:
random = 3;
//dice[random] = 4;
System.out.println(dice[random]);
I am not sure how print the values of arrays when called from methods, I have to solve these:
1- create an array consisting of 100 random integers in the range 100 to 500, including the end points. (This part i am OK, the next 2 points i am quite doubtful on how solve it)
2- make a method to print the array, 5 numbers per line, with a space between each. (I got almost everything right except I don't know how Return the value, I tried return System.outprint..... but didn't work either anyway the method has a void some made it worse)
3- make a method to print the smallest number in the array. (this i got no clue how to do it!)
make a method to print the sum of all numbers in the array. (This I don't quite see why the "return ad;" is not working as most of the code seems correct to me at least hehe)
This is my code so far:
package randomhundred;
import java.util.Arrays;
public class RandomHundred {
private static int[] rand;
public static void main(String[] args) {
// TODO code application logic here
//setting the 100 array
/* PART I*/
int rand [] = new int [100];
int numb;
for(int i=0; i<rand.length; i++){
numb = (int) (100 + (Math.random() * ( (500 - 100) + 1)));
numb = rand[i];
}
}
/* PART II */
public static void arai (){
for (int i=0; i<100; i++){
System.out.print(rand[i] + " ");
if( i%5 == 0){
System.out.println();
}
else{
System.out.print(rand[i] + " ");
}
}
/**
PART IV
*/
public static int suma(){
int ad;
for(int i=0; i<100; i++){
ad =+rand[i];
}
return ad;
}
}
}
Change:
ad =+rand[i];
to
ad += rand[i];
for part IV to work.
First of all, when setting your numbers, you need to set the array index... e.g.
rand[i] = (int) (100 + (Math.random() * 401)); // 100-500
Part 2 should read:
for (int i=0; i<rand.size(); i++){
if( i%5 == 4){
System.out.println(rand[i] + " ");
} else{
System.out.print(rand[i] + " ");
}
}
Part 3 should read:
int ad = 500;
for(int i=0; i<100; i++){
ad = Math.min(ad, rand[i]);
}
System.out.println("Smallest="+ad);
For part 3, you're going to want to
Create an integer and set it to the first variable in your array
Loop through all the variables in the array
For each variable, if it's smaller than the one we created in step 1, set the integer we created to the smaller variable
By the end of this loop the integer we created must be the smallest possible number, as we went through every possible variable to see if there was a smaller one. All you have to do now is print it out.
Also I don't know why you would want to return the values in part 2, a void function doesn't have to return anything and you can just print out the numbers straight from the function.
I have noticed when inputting an integer into an array that if the integer is larger than the arrays length it will throw an out of bounds exception. Why is this? Why can the array not accept any integer value? How can I correct this when I need to store integers larger than an arrays length.
Thank you!
Here is the code. When I enter an integer greater than 5 I get an out of bounds exception. If I enter integers less than 5 the code works perfectly.
public class NumOfOccur
{
static Scanner input = new Scanner(System.in);
static int[] cards = new int[5];
static int[] numOccurence = new int[5];
public static void main(String[] args)
{
System.out.println("Enter five values: ");
for (int i = 0; i < 5; i++)
{
System.out.print("Card " + (i + 1) + " : ");
cards[i] = input.nextInt();
}
containsPair(cards);
}
public static boolean containsPair(int hand[])
{
for (int i = 0; i < hand.length; i++)
numOccurence[hand[i]]++;
for (int i = 1; i < numOccurence.length; i++)
{
if (numOccurence[i] > 0)
System.out.println("The number " + i + " occurs " + numOccurence[i] + " times.");
}
return false;
}
}
What you are suggesting here is wrong. An array of integers can hold any integer. When you are storing an integer into an array (or any value for that matter) you have to make sure that the index you are inserting it into is valid.
For example
//perfectly valid
int[] foo = new int[1];
foo[0] = 500;
I suspect what you are doing is something like this.
//throws index out of bounds exception
int[] foo = new int[1];
foo[500] = 500;
Note the difference here. the number inside the [] on the left side of the assignment operator indicate the index you are working with.
Based on your now posted code, your problem is here:
for (int i = 0; i < hand.length; i++)
numOccurence[hand[i]]++;
To briefly explain what is going on.
1) you first initialize numOccurence to a length of 5 integers.
2) You are putting user input into the cards[] then you pass the cards array into into the function containsPair()
3) If the user enters a number greater than 5, lets say 7 the operation hands[i] would be 7. This would be the same as numOccurence[7] which is out of bounds
Without any code, I'm assuming you're just misunderstanding what you're doing with your array. You just have to make sure you're accessing a valid index. There's no restriction on what integer you can store in an integer array.
// Make an array of length ten
int[] myIntArray = new int[10];
System.out.println(myIntArray.length);
// Set the first value in the array to 99: perfectly legal
myIntArray[0] = 99;
System.out.println(myIntArray[0]);
// The following line throws ArrayIndexOutOfBoundsException
myIntArray[99] = 100; // The last index in the array is only 9, not 99!
System.out.println(myIntArray[99]); // This line would also crash, for the same reason
Having seen your code, I think the issue is with this:
First, your numOccurence array always has a length of 5, but in the line
numOccurence[hand[i]]++;
You will get the OutOfBoundsException if hand[i] is 5 or greater (meaning you typed in a value of 5 or greater).
To fix this you should either:
Put restrictions on what card values the user can enter
Make that line numOccurence[i]++ if you mean to keep track of the number of times each card position was drawn
Make numOccurence a longer array so it can store the number of times each possible card (e.g. 1 to 13 for Ace to King) has occured.
I'm definitely sure the question is wrong. You're saying this is not possible
int[] anArray = new int[10];
anArray[5] = 20;
Which is obviously not true.
If that's what you're saying, post your code, because you have a bug.
If you want to make your array larger or something, you should consider using an ArrayList or something similar. Post your code so we can help you.