How to change values of an array inside a class - java

I have a question about my code.
class Zillion
{
private int[] d;
public Zillion(int size)
{
d = new int[size];
}
public void timesTen()
{
for(int i = 0; i<d.length;i++)
{
d[i] = d[i + 1];
}
d[d.length]=0;
}
public String toString()
{
String num;
num= "";
for(int i = 0; i<d.length; i++)
{
num = num + d[i];
}
return num;
}
}
Here in my class Zillion, I am trying to multiply a number that is represent by an array by 10. So what I did was I move the elements at each index to the left and change the value at the last index to 0. For instance,
0 1 4 8 will be come 1 4 8 0.
I am not sure whether my logic will work but that was my first start.
First, I am trying to change the values at each index of the array with an assigned size and here is my driver file.
class Driver
{
public static void main(String[] args)
{
Zillion z = new Zillion(5);
System.out.println(z); // 00000
for (int j = 0; j <= 5; j += 1)
{
z[j]=j;
}
System.out.println(z);
}
}
However, Java throws me an error and says: "Error:(32, 14) java: array required, but Zillion found".
I took C++ and I believe I could change array values like z[j] = j but I guess it is different in Java.
Is there a way I can change the values of the specific index I want? The reason why I used the for loop is because I could not think of any method that I can use to assign the values at each index I want. Is that possible that in the Driver file I create an array, say, 0148 and call my "timesTen" method to give me what I want?
Thank you!

You need to expose the array d of zillion class using a gettor method.
public getArray(){ return d;}
Instead of z[j]=j; you need to use z.getArray()[j] = j
Also your timesTen method will cause arrayindex out of bounds exception in the line
d[d.length]=0;
Java array is not dynamically growing so, Index should be lesser than array size.

You can't index a class, only arrays.
Define a method in Zillion
class Zillion {
public void set(int index, int value) {
// TODO implement
}
}
In your loop, call z.set(j, j)
Note: j <= 5 will cause an out of bound exception

I believe I could change array values like z[j] = j
You could - if z would be an array! But, as the error message also states, it is an object of type Zillion:
Zillion z = new Zillion(5);

You are using instance z of Zillion class, use array instead of it.
//Create getter method in Zillion Class
public int[] getD() {
return d;
}
//And access that array in Driver Class
int[] array = z.getD();
for (int j = 0; j < 5; j += 1) {
array[j] = j;
}

Moreover, you are going to face an
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
because of the statement d[d.length] = 0; in your timesTen() implementation. You have to replace that line with:
d[d.length-1] = 0;
This is not an answer to your question, because you have already received valuable ones, but I hope it could help you.

Related

Implentation of a Selection Shuffle in Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
public static void selectionShuffle(int[] values) {
Random rand = new Random();
for(int i = values.length; i > 0; i--) {
int r = rand.nextInt(i);
swap(values, r, i);
}
//updated answer to include below method
public static void swap(int[]a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
I am writing a card game and need to randomly sort the cards in place, I got an ArrayOutOfBoundsException when I ran the above code, with the compiler complaining particularly about the reassignment from values[i] = values[r] . To be clear, this is , not intended to be a selection sort but instead a selection shuffle. Any help is appreciated!
Alternatively, you may try Collections.shuffle() but it would be more handy if you have to use the wrapper class Integer instead of the primitive type intat first.
Integer[] version:
public static void selectionShuffle(Integer[] values) {
Collections.shuffle(Arrays.asList(values));
}
int[] version:
public static void selectionShuffle(int[] values) {
Integer[] boxedArr = Arrays.stream(values).boxed().toArray( Integer[]::new );
Collections.shuffle(Arrays.asList(boxedArr));
for(int i=0 ; i<values.length ; i++){
values[i] = boxedArr[i];
}
}
Your start condition needs to be values.length-1, as Java arrays are 0 to length-1.
Also the test should be >=0, since as you wrote it'll only go down to index 1.
for(int i = values.length - 1; i >= 0; i--) {
Or as pointed out by Iłya Bursov, you could compare at index i-1 and leave your for loop conditions as you have them. Not sure what's the best form I always do it as in my example above.
Also, you aren't shuffling. You set the value at index i to the one at r, but you lost the value that was previously at i. You need a temp variable to swap the values.
tmp = values[i];
values[i] = values[r];
values[r] = tmp;

Java method to multiply an ArrayList of decimal values by an array of doubles to get an array of ints?

Help! I have this school assignment that wants me to write a method to find the area of rectangles (an array of ints) by multiplying width (an ArrayList) by length (an array of doubles). I'm very very new to coding; I've tried for over five hours to get this working, but I keep doing things wrong and I simply can't get it right. This is the code for the method that I've written:
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
double temp = length[index];
for(index = 0; index < length.length; index++)
{
for(index = 0; index < width.size(); index++)
{
Object widthObj = (int)width.get(index);
area[index] = temp * widthObj;
}
}
}
The full starter code we were given is here, if you need more context (it's commented): http://pastie.org/pastes/916496
Thank you so much for any help you can give me in writing this method. I've been working for hours and I just can't get it...
The length of the array and size of the arraylist should be same , And you have to change the method logic a bit, Have a look at the below code snippet
public static int[] calcRectangleArea(List<Double> width, double[] length)
{
int[] area=new int[length.length];
for(int index = 0; index < length.length; index++)
{
area[index] = (int) (length[index]*width.get(index));
}
return area;
}
Call this method passing width arraylist and length array. It will return area array of ints
You dont really need two loops here. Assuming that width[1] correlates to length[1] you can just loop through both collections at the same time in the same loop.
This should work (i haven't written a line of java in ~2 years so it may not be 100%)
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
//assuming length.length == width.size
for(index = 0; index < length.length; index++)
{
int anArea = (int)(width.get(index) * length[index]);
area[index]=anArea;
}
}
again the code above assumes the size of the collections are the same.
Firstly, you don't need to assign temporary variables:
double temp = length[index];
...
Object widthObj = (int)width.get(index);
Since you will only reference them once. Reference them directly instead:
area[index] = length[index] * (int)width.get(index);
Secondly, your for loops are unneeded, and they are declared wrong. You're trying to increment the index (and twice nonetheless) that was passed to the function which will cause problems. If you were to use nested for loops, you would declare a new iterator variable for each of them:
for (int i = 0; i < something; i++) {
for (int j = 0; j < somethingElse; j++) {
doSomething();
}
}
However in this case you don't even need them.
In addition, you should not have created an Object when you wanted to cast an int:
Object widthObj = (int)width.get(index);
should have been
int width = (int)width.get(index);
However again, this line is unnecessary, and you shouldn't be casting to int this early.
Ultimately, all you need to do is the one line:
area[index] = (int)(length[index] * width.get(index));

Count characters in a multidimensional array, Java

Below is my code:
public int maxTurns = 0;
public String[][] bombBoard = new String[9][9];
...
public void loadBombs()
{
//loadArray();
Random randomGen = new Random();
for (int u=1; u<=9; u++)
{
int randomRow = randomGen.nextInt(9);
int randomCol= randomGen.nextInt(9);
bombBoard[randomRow][randomCol] = "#";
}
//counting #'s -- setting variable
for (int d = 0; d < bombBoard[bombRow].length; d++)
{
for (int e = 0; e < bombBoard[bombCol].length; e++)
{
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
{
maxTurns++;
}
}
}
All I want to do is count the amount of (#)'s in the multidimensional array and assign it to a variable called maxTurns.
Probably very simple, just having a super hard time with it tonight. Too much time away from Java >.<
This line is equating the character # with the entire dth row or eth row. Does not make sense really because an array row cannot equal to a single character.
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
Instead, access a single cell like this
if (bombBoard[d][e].equals("#"))
And initialize maxTurns before counting i.e. before your for loop:
maxTurns = 0;
You need to change the if codition
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
to
if (bombBoard[d][e].equals("#"))
You are using 2D Array, and do array[i][j] can populate its value for a gavin position.
do you want to count from the whole array or certain parts of the array only?
From the code snippet you gave above, I can't really tell how you iterate the array since I'm not sure what is
bombBoard[bombRow].length and bombBoard[bombCol].length
But if you want to iterate the whole array, think you should just use:
for (int d = 0; d < 9; d++) // as you declared earlier, the size of array is 9
{
for (int e = 0; e < 9; e++) // as you declared earlier, the size of array is 9
{
if (bombBoard[d][e].equals("#"))
{
maxTurns++;
}
}
}

copying integer parameter into an array element

Write a method called fillIntArray that takes two parameters – an integer array and an integer. The method must copy the integer parameter into each element of the integer array. The method does not have a return value.
Below is my current code, the test method applies random array lengths and variables for the integer, but I'm struggling with the concept of inputting data into an array. I understand pulling info but unsure of how to write the code to input it.
Can someone please indicate effective ways of writing this code?
public class Q8 {
void fillIntArray(int [] array, int x) {
for(int i = 0; i < x; ++i) {
array[i] = +x;
}
}
}
That code demonstrates knowledge of how to insert data into an array. But a few hints:
Your loop should go from 0 to array.length, not 0 to x.
It's a good idea to use x in the assignment statement, not +x. This makes the code more clear, and prevents bozos like me from thinking it will make the code not work.
Try following code. You should iterate over the whole array and put value x in each location.
public class Q8 {
void fillIntArray(int [] array, int x) {
for(int i = 0; i < array.length; ++i) {
array[i] = x;
}
}
}
The fasted way:
void fillIntArray(int[] array, int val) {
for (int i = 0, len = array.length; i < len; i++)
array[i] = val;
}

What does this java output mean?

public class Arrys {
private int[] nums;
//Step 3
public Arrys (int arrySize) {
nums = new int[arrySize];
}
public int [] getNums (){
return nums;
}
}
Test class:
public class TestArrys
{
public static void main(String args[])
{
//Step 4
Arrys arry = new Arrys(10);
System.out.println("\nStep4 ");
for(int index = 0; index < arry.getNums().length; index++) {
System.out.print(arry.getNums());
}
}
}
It's incredibly simple, that is why I think I'm doing something fundamentally wrong. All I want is to display the value of the array.
This is what I get back. I am totally lost, there is nothing in my book that explains this nor does googling it help.
Step4
[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440[I#1ac88440
You're trying to print the array itself out several times. This code:
for(int index = 0; index < arry.getNums().length; index++) {
System.out.print(arry.getNums());
}
should (potentially) be this:
for(int index = 0; index < arry.getNums().length; index++) {
// println instead of print to get one value per line
// Note the [index] bit to get a single value
System.out.println(arry.getNums()[index]);
}
Or rather more simply:
for (int value : arry.getNums()) {
System.out.println(value);
}
When you call toString() on an array, it returns something like [I#1ac88440 where the [ indicates that it's an array, I indicates the array element type is int, and #xxxxxxxx is the address in memory. It's diagnostic, but not really helpful in most cases.
Use Arrays.toString to get a more useful representation.
Try
System.out.println(java.util.Arrays.toString(arry.getNums()));
instead of the loop.
By default, printing out an array will not give you a very useful string. To get the kind of output you're hoping for, you could loop through the array and print out each element yourself... or you could let java.util.Arrays do the dirty work.
It returns array:
public int [] getNums ()
This loop prints array reference getNums().length times...
for(int index = 0; index < arry.getNums().length; index++) {
System.out.print(arry.getNums());
}
Try this:
int [] nums = arry.getNums();
for(int index = 0; index < nums.length; index++) {
System.out.print(arry.nums[index]);
}

Categories