I've been trying to make the following for loops to print the original and modified values of an array in two columns, separated by \t\t. Here is my code:
public class Main {
public static void main(String[] args) {
int jay[] = {1,2,3,4,5,6};
System.out.println("Original\tAfter");
for(int y: jay) {
System.out.println(y);
}
multiplyByTen(jay);
for(int z: jay) {
System.out.println("\t"+ z);
}
}
public static void multiplyByTen(int x[]) {
for(int counter = 0; counter<x.length;counter++) {
x[counter] *= 10;
}
}
}
This is the result so far:
Original After
1
2
3
4
5
6
10
20
30
40
50
60
So my question is how to align the value 10 to 1, and 20 to 2 and so on?
This is the solution of your problem, but i don't know if this is exuctly what you want, but it gives you the wished result
public class Main {
public static void main(String[] args){
int jay[] = {1,2,3,4,5,6};
int jay2[] = jay.clone();
multiplyByTen(jay);
for(int i = 0; i < jay.length;i++) {
System.out.println(jay2[i]"\t"+ jay[i]);
}
}
public static void multiplyByTen(int x[]){
for(int counter = 0; counter<x.length;counter++) {
x[counter] *= 10;
}
}
}
This example is from thenewboston java series, I just modified it a bit to see if I can print an original and after arrays side by side.
There is no way to print it side by side with your current construct because array gets manipulated and changed when passed into the method. One of the only ways would be making a copy of the original and print both original and after in the same line.
If your multiplyByTen method accepts a single int value you can do it as:
for(int y : jay)
System.out.println(y + "\t" + mutiplyByTen(y));
If your multiplyByTen method returns an int array, you can do it as:
int[] arr = mutiplyByTen(jay);
for(int x=0; x<jay.length; x++)
System.out.println(jay[x] + "\t" + arr[x]);
But with the current method signature, you need to make another copy of the original array.
My solution using a single array:
public class Main
{
public static void main(String[] args)
{
int jay[] = { 1, 2, 3, 4, 5, 6 };
System.out.println("Original\tAfter");
multiplyByTen(jay);
// To verify values in the original array (you can remove this loop)
for (int z : jay)
{
System.out.println(z);
}
}
public static void multiplyByTen(int x[])
{
for (int counter = 0; counter < x.length; counter++)
{
System.out.print(x[counter] + "\t\t");
x[counter] *= 10;
System.out.println(x[counter]);
}
}
}
OUTPUT
Original After
1 10
2 20
3 30
4 40
5 50
6 60
If you were to use a enhanced loop inside the multiplyByTen(int x[]) method, you would only be changing the local value and not the value in the array. So, if you were to print out the values in the original array, they would remain the same as the original. This way, the values in the array are permanently modified. So, printing the values after the method will show the multiplied values.
Lastly, I would not use print() or println() methods for this. I would use printf() to print out a formatted output. You will find that tabbing will eventually result in misaligned columns (when the number of digits gets larger). You would not run into this issue when using printf().
Keep it simple.
Why not simply do
for(int y : jay) {
System.out.println(y + "\t" + y*10);
}
It is far better to use Arrays.copyOf(...) when you think of using .clone()1:
int jay[] = {1,2,3,4,5,6};
int jay2[] = Arrays.copyOf(jay,jay.length);
System.out.println("Original\tAfter");
multiplyByTen(jay2);
for (int i = 0; i < jay.length; i++) {
System.out.println(jay[i]+"\t\t"+jay2[i]);
}
This way, you print table rows and not columns.
1Why you should never use .clone() for defensive copying.
Related
The Return type is void
No input parameters
Print out the numbers calculated results separated by a space using current number add the next number from 0 to (a+b).
An example would be if the numbers for the for loop are 0,1,2,3,4,5,6 then it would add 0+1, 1+2, 2+3, 3+4, 4+5, 5+6 and print out those values just like 0,1,2,3,4,5,6.
I honestly have no clue how to do this so I'm not going to lie about it so can someone help me code it and explain or just help me with it.
public class ForFogMe
{
public int a, b;
public String str;
public void addUp(){
for(a = 0; a <= 6; a ++){
System.out.print(a);
}
String s = Integer.toString(a);
System.out.println();
System.out.print(s.substring(0,2) );
}
public static void main(String args[]){
ForFogMe me = new ForFogMe();
me.addUp();
}
}
If you only want to print sum of the numbers from 0 to 6 you would do it simply like this:
public void addUp() {
for(a = 0; a < 6; a++) {
System.out.print(a+(a+1) + ",");
}
System.out.print("\b"); // to delete last comma
}
In first iteration a is 0 a+1 is 1 so you print their sum like (a+(a+1) + ",") which outputs "1,". It repeats until it reaches 6. At the end we have 1,3,5,7,9,11, so I used System.out.print("\b"); to delete last char, so we get 1,3,5,7,9,11
I believe this should do the trick:
public static void addUp(){
final int[] array = {0,1,2,3,4,5,6};
int[] result = new int[array.length-1];
for(int i = 0; i < array.length-1; i++) {
result[i]=array[i]+array[i+1];
}
result[3]=array[array.length-1];
for(int i = 0; i < result.length; i++) {
System.out.print(result[i]+" ");
}
}
Test case (array):
0,1,2,3,4,5,6
Outputs:
1 3 5 6 9 11
Note: The array size does not matter.
I'm very new to java (like a month old). This week we have a programming problem that I'm having difficulty with. We are asked to write a program that declares an array "alpha" of 50 elements of type "double". Initialize the array so that the first 25 elements are equal to the square of the index variable and the last 25 elements are equal to three times the index variable. Output the array so that 10 elements per line are printed. I've gotten the output right so far, but it's still only printing 1 value per line, here's what I have so far, what am I doing wrong? Any help is super appreciated!!
import java.util.*;
public class progprblm5{
public static void main(String[] args){
double alpha[] = new double[50];
for(int i =0;i<25;i++)
{alpha[i]= i*i;}
for(int i = 25;i<50;i++)
{alpha[i]= i*i*i;}
System.out.println( "The values are: ");
for(int i=0;i<50;i++)
System.out.println(alpha[i]);
}
void print(double array[])
{
for(int i=1; i <= array.length; i++)
{
System.out.print(array[i+1]+ " , ");
if(i%10==0)
System.out.print("\n");
}
}
}
You have not called print method from main method. One more mistake is in your code that, you mentioned about 3 times of index variable and in your code you are taking cube of index variable.
public class progprblm5{
public static void main(String []args){
double alpha[] = new double[50];
for(int i =0;i<25;i++){
alpha[i]= i*i;
}
for(int i = 25;i<50;i++){
alpha[i]= 3*i; // 3 times of index
}
System.out.println( "The values are: ");
new progprblm5().print(alpha); // method call
}
void print(double array[]){
for(int i=0; i < array.length; i++){ //iterate array from 0 index
System.out.print(array[i]+ " , "); // print ith element
if(i%10==0){
System.out.println();
}
}
}
}
Was doing some Java practices and I got stuck at this particular question, I am given the following code:
public class DistanceSeparator {
public static void main(String[] args) {
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
public static void printSeparatorSequence(int numberOfElements) {
for () {
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
And I am supposed to modify the code using A SINGLE FOR LOOP to show that:
If numberOfElements = 5
1 3 7 13 21
If numberOfElements = 7
1 3 7 13 21 31 43
Each showing an increment of + 2, +4, +6, +8, +10 and +12
The final output is to be this:
1 3 7
1 3 7 13 21
1 3 7 13 21 31 43 57
I just can't seem to get my head around how to get that outcome, and this is after 2hours of trying (yes I am that bad). Any help, please?
edit This was what I had, before deciding to seek help, it's obviously not working.
int j = 0;
for (int i = 1; i <= numberOfElements; i++) {
j = i * 2; // + by how much
int z = i + j; //sum
System.out.print(z + "");
}
edit 2 now I get it, oh my, to think I was so close. Guess I was too cluttered after being stuck for some time. Thanks a ton!
Here is the code to accomplish result you expected.
int current = 1;
for(int i = 0; i < numberOfElements; i++) {
current += i*2;
System.out.print(current + " ");
}
You just need to keep another variable to keep track of the difference (the change), and then constantly update it by the power of 2 of the iteration, i.e. for the first loop only increase it by 2^1, then by 2^2, then 2^3 and so on).
An example of how to achieve that:
for (int i = 0, diff = 0; i < numberOfElements; i++, diff += 2*i) {
System.out.print((1 + diff) + " ");
}
UPDATE: After you've edited your question with your code segment, you can see your problem was with this line:
int z = i + j; //sum
Since both i and j advance with each iteration, you lose your offset (you constantly reset it). You need to keep it static (like in my example: 1), and only update j by 2*i each iteration, otherwise your "base" for calculation is constantly changing and the formula doesn't hold anymore.
In your case, you are regenerating int z everytime the loop is called,
All you have to do is define z outside the loop and instantiate z as 1 and also, you are not retaining the previous values of z so that's why it wasn't working. So it should be z = z + j and put this line below the print statement and you are done.
Here is an snippet of code which would help you my way:
int j = 1;
for(int i=1; i<=numberOfElements; i++) {
System.out.println(j);
j = j + 2*i;
}
And, here is an snippet of code which would help you your way:
int j = 0;
int z = 1;
for (int i = 1; i <= numberOfElements; i++)
{
j = i * 2; // + by how much
System.out.print(z + " ");
z = z + j; //sum
}
Note the trend.
You are adding a multiple of 2 to the previous number to get the next number. The multiple of 2 to be added depends upon the position of the number. For example, to get the 1st number, you add 2 x 0 to 1. To get the 2nd number, you add 2 x 1 to the previous number (that gives 3). To get the 3rd number, you add 2 x 2 to the previous number (that gives 7). To get the 4th number, you add 2 x 3 to the previous number (that gives 13).
To get the number at nth position, you add 2 x (n-1) to the previous number.
Now take a look at the example below, keeping the above explanation in mind.
public static void printSeparatorSequence(int numberOfElements) {
int number = 1;
for (int i = 0; i<numberOfElements;i++) {
number = number + 2 * i;
System.out.print(number);
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
This is the solution of your problem. I have discussed the code by the comment lines given within the code.
public class DistanceSeparator
{
/* Main Method */
public static void main(String[] args)
{
/* printSeparatorSequence Function is Called */
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
/* printSeparatorSequence Function Definition */
public static void printSeparatorSequence(int NumberOfElements)
{
/* variable j is used to get the multiples of
2 by multiplying with variable i within the for loop
and variable sum is used to get the total value */
int j=2,sum=1;
for(int i=0;i<NumberOfElements;i++)
{
sum=sum+(j*i);
/* Here total sum is printed with a space */
System.out.print(sum+" ");
}
/* It is used for new line */
System.out.println();
}
}
Just playing around with displaying values in a two dimensional array and noticed my code prints some hashcodes and then the values. But I am not printing the array object itself (as done in the post here) or at least explicitly calling the toString or hashcode method of the array object. Instead, I'm directly accessing and printing the values in the array using arrayObj[i] and arrayObj[i][j].
Here's my code:
class PrintTwoDimArray {
public int [][] createArray () {
int counter = 0;
int[][] intArray = new int [2][4];
for (int i = 0; i < intArray.length; i++) {
for (int j = 0; j < intArray[i].length; j++) {
intArray[i][j] = ++counter;
}
}
return intArray;
}
public void printArray ( int [][] arrayObj ) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.print(arrayObj[i] + " ");
for (int j = 0; j < arrayObj[i].length; j++) {
System.out.print(arrayObj[i][j] + " ");
}
System.out.println();
}
}
}
class TestPrintTwoDimArray {
public static void main (String[] args) {
PrintTwoDimArray twoDim = new PrintTwoDimArray();
int [][] multiArray = new int [2][4];
multiArray = twoDim.createArray();
twoDim.printArray(multiArray);
}
}
My output is as follows:
It seems that my code is somehow calling the toString or hashcode method of the array. Thoughts? How can I modify to print just the values?
javac and java version 1.8.0
A two dimensional array is an array of arrays. The array you create (int[2][4]) looks like this
[ 0 ] -> [ 1, 2, 3, 4 ]
[ 1 ] -> [ 5, 6, 7, 8 ]
So when you only access the first dimension you will get the array that holds the second dimension.
int[][] arr = createArray();
System.out.println(arr[0]);
will output something like
[I#1db9742
To print an array's values you can use Arrays.toString(arr). In this case you can omit the inner loop, because Arrays.toString() will do it for you.
public void printArray ( int [][] arrayObj ) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.println(Arrays.toString(arrayObj[i]));
}
}
The hash values come from your first System.print sentence.
System.out.print(arrayObj[i] + " ");
With this sentence you are printing an Object (an array) and therefore Java is invoking the default toString method.
When you print
arrayObj[i]
you get the default Object toString() from an array. You could use Arrays.toString(int[]) to make that a String like
System.out.println(Arrays.toString(arrayObj[i]));
Alternatively, you can use Arrays.deepToString(Object[]) to print your multi-dimensional array without a loop
System.out.println(Arrays.deepToString(arrayObj));
Edit
You could use formatted output to build your table.
public static void printArray(int[][] arrayObj) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.printf("%03d: ", i + 1);
for (int val : arrayObj[i]) {
System.out.printf("% 4d ", val);
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] table = { { 3, 1, 2 }, { 5, 1, 4 }, { 100, 200, 300 } };
printArray(table);
}
Output is
001: 3 1 2
002: 5 1 4
003: 100 200 300
What I have to do is to create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int parameter should display the Spanish word for the number passed. A loop structure in the main() method should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are...
1 uno 2 dos, 3 tres, 4 cuatro, 5 cinco, 6 seis, 7 siete, 8 ocho, 9 nueve, 10 diez.
I do not know why am I getting this error below
http://i.stack.imgur.com/HLIiI.png
Thanks in advanced!
import java.util.Scanner;
public class SpanishNumberss {
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
}
public static void main(String args[]) {
for (int i = 1; i <= 10; i++)
spanishNumbers(i);
}
}
In Java, indexes of an array start with 0, not 1, and run through length - 1, not length.
Adjust your for loop condition in main as follows:
for (int i = 0; i < numbers.length; i++)
You'll need to adjust your other for loop similarly.
Arrays indexes are 0 based (starts from 0 not from 1) . Also you are declaring your array numbers inside the method each time is called just declare as a class variable. So take care that in your example index 0 refers to 1 (uno) and so on.
I made you an example and add 0,"cero"
public class SpanishNumberss {
private static final String[] numbers = {"cero","uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
public static void spanishNumbers(int num) {
//loop here is unnecesary
System.out.println(numbers[num]);
}
public static void main(String args[]) {
//and here in main i call them from 1 to 10
for (int i = 1; i < 11; i++){
spanishNumbers(i);
}
}
}
ArrayIndexOutOfBounds means you have gone out of the boundaries of your array (in your case numbers). What you have to realize is array's are 0 index-based. So in your for loop, you really 0 - 9, not 1-10.
And an even better solution, as #rgettman has posted is to use the length property of the array. So you are not hard-coding in those magic numbers.
Arrays go from 0 to N-1
That's why you're getting that error, change your for cycle to:
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
Your problem is here:
for (int i = 1; i <= num; i++)
Arrays in Java are 0-based. So the valid indices run from 0 to array.length - 1. So an array of length 5 would have the valid indices 0, 1, 2, 3, and 4. Change your loop to the following:
for (int i = 0; i < num; i++)
This will ensure that in your loop i will only have the values from 0 to 9.
your loop should only have the values from 0 to 9:
for (int i = 0; i < num; i++)
first of all i don't think you need a loop in the spanishnumber method...
cos you already know the index of what you are looking...// that's if i understand you
so the only place you need the loop is in the main method...so your code should look like dis
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
spanishNumbers(6);
}
}
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
System.out.println(numbers[num -1]);
}