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;
}
Related
So I am trying to loop through the rows of a 2d array to check the if the row matches the property of a method. How can I use an if to just check the row? This is my code
public void recordWhiplashPoints(ConnectionToClient client, int vote){
int[][] votecount = new int[game.getPlayers().length][0];
outside:
if(game.getRecordedAnswers() <= game.getPlayers().length){
for (int i = 0; i < game.getPlayers().length; i++) {
for (int q = 0; q < votecount.length; q++) {
if(votecount[q] == vote){
//do stuff
}
}
}
}
}
So where votecount[row] is. Can I compare that with the property vote some how?
So for two dimensional arrays, which is basically just an array of arrays, you get a member array using something like votecount[i], and you get a member of that array with votecount[i][q]. I think the following is the code you want:
int[][] votecount = new int[game.getPlayers().length][0];
outside:
if(game.getRecordedAnswers() <= game.getPlayers().length){
for (int i = 0; i < length; i++) {
// note that we need to compare against the array votecount[i]
for (int q = 0; q < votecount[i].length; q++) {
// here we access the actual element votecount[i][q]
if(votecount[i][q] == vote){
//do stuff
}
}
}
}
Not sure if this is what you're looking for, but one way to do so would be to use for-each loops
public void recordWhiplashPoints(ConnectionToClient client, int vote){
int[][] votecount = new int[game.getPlayers().length][0];
outside:
if(game.getRecordedAnswers() <= game.getPlayers().length){
for (int[] i : votecount) {
for (int q : i) {
if(q == vote){
//do stuff
}
}
}
}
}
Essentially the first for-each loop goes through each array the 2d votecount array, and then the second for-each loop goes through each of those 1D arrays. If you have any questions just ask.
However, I don't understand how your second if statement will be true, as you never change votecount from anything other that the default, which is a 2D array filled with 0's.
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.
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));
public void zero() {
int sum = 0;
for (int i = 0; i < mArray.length; ++i) {
sum += mArray[i].mSplat;
}
}
public void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i < len; ++i) {
sum += localArray[i].mSplat;
}
}
According to Android documentation, in above code, zero is slower. But I don't understand why ? well I haven't learn that much deep but as I know length is a field not method. So when loop retrieves its value, how its different from retrieving from local variable ? and array length is always fixed once initialized. What am I missing ?
Well I guess this is because at zero, he always needs to retrieve the information from mArray and in one, he has it accessible. This means, zero needs two "methods":
Access mArray
Access mArray.length
But one only needs one "methods":
Access len
In the first example, the JVM needs to first fetch the reference to the array and then access its length field.
In the second example, it only accesses one local variable.
On desktop JVMs this is generally optimised and the two methods are equivalent but it seems that Android's JVM does not do it... yet...
It is a matter of scope. Accessing an instance variable is slower than a method variable because it is not stored in the same memory places. (because method variables are likely to be accessed more often).
Same goes for len, but with an extra optimization. len cannot be changed from outside the method, and the compiler can see that it will never change. Therefore, its value is more predictable and the loop can be further optimized.
public void zero() {
int sum = 0;
for (int i = 0; i < mArray.length; ++i) {
sum += mArray[i].mSplat;
}
}
Here if you look at the for loop array length is calculated for every iteration, that degrades
the performance.
public void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i < len; ++i) {
sum += localArray[i].mSplat;
}
}
In this case the length is calculated before for loop and then used in the loop.
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]);
}