Java Previous Array Values Set to 0 - java

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++;
}

Related

Why does this method only return values of 0 to a new array?

I am supposed to write a short program that takes 10 numbers, stores the values in an array, passes it to a method (eliminateDuplicates()) that creates a new array of only the unique values from the first array.
However, I am having trouble either initializing the output array, or making the eliminateDuplicates() method return the output array properly. The output array is always full of 0's and I cannot figure out why this is failing.
java.util.Arrays.parallelSort(inputNumbers); //sorts the array in ascending order
eliminateDuplicates(inputNumbers); //passes array to eliminateDuplicates method
//display each unique value in output array
System.out.print("The distinct numbers are ");
for(int i = 0; i < outputNumbers.length; i++)
System.out.print(outputNumbers[i] + " ");
}
public static int [] eliminateDuplicates(int[] list) {
int[] outputNumbers = new int [list.length];
int k = 0;
for (int i = 0; i < list.length; i++)
if(i == 0) //compares each array value against preceding value
outputNumbers[i] = list[i]; //only copies unique values to output array
else
if(list[i] != list [i-1]) {
outputNumbers[k] = list[i];
k++;
}
return outputNumbers;```
You have a local outputNumbers in eliminateDuplicates which you return. I assume you also have a redundant static outputNumbers. Option 1: Eliminate the local variable, change
int[] outputNumbers = new int [list.length];
to
outputNumbers = new int [list.length];
Option 2: Set outputNumbers on call (which is what I would likely do, and eliminate the static one)... Like,
int[] outputNumbers = eliminateDuplicates(inputNumbers);
Don't forget to remove the static one if you use option 2.
You are ignoring the array returned by your method.
Change
eliminateDuplicates(inputNumbers);
to
int[] outputNumbers = eliminateDuplicates(inputNumbers);
P.S. your output array has the same length as the input array. Therefore, since you are eliminating duplicates, it may have some 0s as its last elements. If that's not what you want, you should create the output array only after you find out how many unique numbers the input array has.

Storing a random number in an array with a loop

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];
}

Loop to keep asking for guesses when picking numbers in an array (java)

I am writing code to Generate an Array of 100 random numbers between 1 and 100 .
I then want to ask the user for a number and then search for that number in the array. If the number is present i want to remove it from the array and ask the user for another number. I want to repeat this until the user guesses
incorrectly. If the user guesses incorrectly, I want to output the remaining Array contents in reverse order.
I think I have everything written correctly, but here is my Question; I can't get my head around how to have the program keep asking if the guesses are correct.
Here is my code, I know it's just a well placed for loop that is needed,I just can't see where. I would really appreciate some help on this. Thank you! I'm not looking for someone to give me the code needed just a steer.
int[] randomArray = new int[10];
// For loop to fill the array with random elements from 1 to 100
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = (int) (Math.random() * 100);
// Print the array
System.out.print(randomArray[i] + ", ");
}
// Print a blank line
System.out.println();
Scanner input = new Scanner(System.in);
// Declare an int variable to hold the number
int searchNumber;
// Ask the user to enter a number
System.out.println("Please enter a number to search for between 1 and
100: ");
// Initialise the int variable with the number entered
searchNumber = input.nextInt();
// initialise boolean as false
boolean found = false;
// for loop to search the array for the value entered by the user
for (int i = 0; i < randomArray.length; i++) {
if (searchNumber == randomArray[i]) {
// If found then set boolean to true
found = true;
// If found print out the index where it was found and inform
the user that it
// will be removed from the array
System.out.println("Your number was found at index " + i + "
and will be deleted from the array:");
// create a new array which is one element shorter than the
original
int[] result = new int[randomArray.length - 1];
// Copy the the new array from the original array
System.arraycopy(randomArray, 0, result, 0, i); // i is the
element to be removed
System.arraycopy(randomArray, i + 1, result, i, result.length -
i);
// Print the new array without the element i
System.out.println(Arrays.toString(result));
}
}
// code to inform the user if their value was not found and print the
array in
// reverse
if (!found) {
// Print text telling the user that the number was found and the
array will be
// printed in reverse
System.out.println("Your number was not found, here is the array in
reverse");
// For loop to print the array in reverse
for (int k = randomArray.length - 1; k >= 0; k--)
System.out.print(randomArray[k] + ", ");
}
}
Question; I can't get my head around how to have the program keep asking if the guesses are correct.?
Then you should build your logic around some do while loop.
//Initialize random values here.
do{
//Get input & process.
//Do all Logics.
}while( exit condition based on your logic else process input again )
This should do it. I hope.

Storing contents of a webtable in a 2d matrix

I am trying to get the contents of a webtable using selenium and then store the contents in a 2d matrix.
Below is my code :
//Locate the webtable
WebElement reportTable = driver.findElement(By.xpath("//*[#id='pageContainer']/div/div[2]/table[2]"));
int rowCount = driver.findElements(By.xpath("//*[#id='pageContainer']/div/div[2]/table[2]/tbody/tr")).size(); //Get number of rows
System.out.println("Number of rows : " +rowCount);
String[][] reportMatrix = new String[rowCount-1][]; //Declare new 2d String array
//rowCount-1 because the first row is header which i don't need to store
int mainColCount = 0;
for(int i=2;i<=rowCount;i++) //Start count from second row, and loop till last row
{
int columnCount = driver.findElements(By.xpath("//*[#id='pageContainer']/div/div[2]/table[2]/tbody/tr["+i+"]/td")).size(); //Get number of columns
System.out.println("Number of columns : " +columnCount);
mainColCount = columnCount;
for(int j=1;j<=columnCount;j++) //Start count from first column and loop till last column
{
String text = driver.findElement(By.xpath("//*[#id='pageContainer']/div/div[2]/table[2]/tbody/tr["+i+"]/td["+j+"]/div")).getText(); //Get cell contents
System.out.println(i + " " + j + " " + text);
reportMatrix[i-2][j-1] = text; //Store cell contents in 2d array, adjust index values accordingly
}
}
//Print contents of 2d matrix
for(int i=0;i<rowCount-1;i++)
{
for(int j=0;j<mainColCount;j++)
{
System.out.print(reportMatrix[i][j] + " ");
}
System.out.println();
}
This gives me a Null Pointer Exception at "reportMatrix[i-2][j-1] = text".
I don't understand what I am doing wrong. Do I have to give even the second index when I declare the 2d array ?
Thanks in advance.
Unless you're a student who is studying multi-dimensional arrays, or you are otherwise constrained by an API you're required to use, just avoid arrays. You'll stay saner longer :)
If you HAVE to use a 2D array, it's wise to remember that you are not actually creating a matrix. You are creating a 1D array, and each element of this array is another 1D array. When you think of it that way, it becomes clear that you definitely have to initialize the "columns" arrays as well as the "rows" array.
This line:
String[][] reportMatrix = new String[rowCount-1][];
will initialize report matrix to have rowCount - 1 rows, and null for each and every set of columns.
Inside your first loop, after you have identified the number of columns, you want to do something like so:
reportMatrix[i] = new String[columnCount];
for(int j=1;j<=columnCount;j++) ...
This will allow you to have different number of columns in each row, if necessary.
Then, in your print loop, you should use the array lengths to print out the rows and columns. Remember to subtract 1 from the length attribute, since the this represents the number of elements in the array, and we almost always use zero-indexed for loops.
//Print contents of 2d matrix
for(int i=0; i < reportMatrix.length - 1; i++)
{
for(int j=0; j < reportMatrix[i].length - 1; j++)
{
System.out.print(reportMatrix[i][j] + " ");
}
System.out.println();
}

"java.lang.ArrayIndexOutOfBoundsException: 1" when the size of the array > the index

public static int[] allBetween()
{
Scanner input = new Scanner(System.in);
int first;
int last;
System.out.println("Enter the first number");
first = input.nextInt();
System.out.println("Enter the last number");
last = input.nextInt();
int[] between = {((last - first) + 1)};
for(int count = 0; count <= (last - first); count++)
{
between[count] = (first + count);
}
return between;
}
I'm a little rusty and I dont't see the issue here, I have tried manually assigning the size of the array to 100 and first and last to 1 and 5 but it still returns the same error.
any ideas?
this is my first post on stack over flow, Please correct me if I'm posting in an incorrect manner
The below statement:
int[] between = {((last - first) + 1)};
initializes the array with just a single element, with the value - last - first + 1
Change it to:
int size = last - first + 1;
int[] between = new int[size];
And then, you can change your loop to:
for(int count = 0; count < size; ++count)
Issue is:
int[] between = {((last - first) + 1)}; //initializes array with value
You have only one value in this array at index 0, and if last-first is greater than ZERO, you will end up having ArrayIndexOutOfBoundsException.
Read arrays tutorial for more information.
This line:
int[] between = {((last - first) + 1)};
creates an array with a single element whose value is equal to ((last - first) + 1.
Use:
int[] between = new int[(last-first)+1];
anyway, to iterate through it, you can use a nicer more readable/idiomatic construct:
for(int count = 0; count < between[length]; count++)
{
between[count] = (first + count);
}
Remember that arrays are addressed and dimensioned by brackets, created explicitly with braces.
Also, between[count] = (first + count); looks suspicious. Make sure that's really what you want it to do, namely to set the countth element of between to first+count. That would just make an array filled with first, first+1, ....
you should replace
int[] between = {((last - first) + 1)};
with
int[] between = new int[((last - first) + 1)];
because your version always creates an array of length 1. See this for example:
int[] foo = {22};
is an int[] of length 1 and foo[0] is 22. Whereas
int[] bar = new int[33];
createas an array of length 33 where each index stores the default value 0.

Categories