Output the array so that 10 elements per line are printed - java

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();
}
}
}
}

Related

Re-arranging array

I have an assignment they ask me to re-arrange an array from the even numbers to the odd numbers
like this:
Sample Output:
Please enter array of 5 integers:
1 2 5 6 4
the array after re-arranging:
2 6 4 1 5
I couldn't do it " I cant use methods" can anyone help me ?
this is my code:
public static void evenOdd(int[] arr){
int i=0;
int arr1[] = new int[5];
for (i=0;i<5;i++)
{
if (arr[i]%2==0)
arr1[i]=arr[i];
}
for (i=0;i<5;i++){
if(arr[i]%2!=0)
arr1[i]=arr[i];
}//end for
for(i=0;i<5;i++)
System.out.print(arr1[i]+" ");
System.out.println("");
}//end method
THANK YOU
The problem is when you add them into the new array you are putting them in the same position: i. Use a separate int to keep count of what part of the index you are on.
public static void evenOdd(int[] arr){
int i=0;
int count = 0;
int arr1[] = new int[5];
for (i=0;i<5;i++) {
if (arr[i]%2==0) {
arr1[count]=arr[i];
count++;
}
}
for (i=0;i<5;i++){
if(arr[i]%2!=0) {
arr1[count]=arr[i];
count++;
}
}//end for
for(i=0; i < 5; i++) {
System.out.print(arr1[i]+"\n");
}
}//end method

Loop for printing array values in two columns

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.

Unable to get a sorted array in ascending manner

I created a Java program that takes the user's choice and creates an int array of that size. Then the array is sorted and displayed and a number is asked to search in the array. I'm trying to use the bubble sort technique, however, the result always turns out to be a descending array rather than an ascending one.
import java.util.*;
class mt {
int i,M=0;
public void main() {
Scanner sc=new Scanner(System.in);
System.out.println("enter the size of array");
int sizeOfArray=sc.nextInt();
int arr[]= new int [sizeOfArray];
int temp;
System.out.println("enter the numbers");
for (i=0; i<sizeOfArray; i++) {
arr[i]=sc.nextInt();
}
System.out.println("the sorted array is below :");
for ( i=0; i<sizeOfArray-1; i++){
for (int j=0; j<sizeOfArray-2; j++) {
if (arr[j]>arr[j+1]) {
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for (i=0; i<sizeOfArray; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.println("enter number to search");
int srch=sc.nextInt();
for (i=0; i<sizeOfArray; i++) {
if (arr[i]==srch)
{
System.out.println("found at "+i);
M++;
break;
}
else if (M==0&&i==sizeOfArray-1)
{
System.out.println("number not found");
}
}
}
}
Change your loops and condition as below
for ( i=0; i<arr.length - 1; i++){
for (int j=i+1; j<arr.length; j++) {
if (arr[i]>arr[j]) {
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
So you get resulting array in ascending order. In your case, you are missing elements as you are iterating over from 0 - array.length - 2.
Firstly the code mentioned above had lot of silly mistakes which need to be corrected:
1. "String args[]" need to be added in the main() method.
2. For all the for loops where "i" is the variable, it need to be defined as an "int".
3. the variable "M" need to be defined too.
Now when I did a dry run of this code, the result produced was also not proper.
Input given was as follows:
enter the size of array
5
enter the numbers
12
10
34
2
6
Output received was as below:
the sorted array is below :
2 10 12 34 6
enter number to search
Now the output was incorrect.
Although it was in ascending order... still the last element would get missed. The twin for loops that are used need to be used in a different way. Please find the code that should be present in that section:
for (int i=0; i<=sizeArr; i++){
for (int j=0; j<sizeArr-1; j++) {
if (arr[j]>arr[j+1]) {
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
I hope that this works for you now.

loop is cut one element of the array

The problem is :
Write a program that reads a number n and then declares an array of n elements. The program then fills the array with the first n numbers, where each number is two to the power of the previous. Finally, display array’s contents.
My code :
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-1 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
The error is :
----jGRASP exec: java Q1
Enter a number :
4
4
16
65536
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Q1.main(Q1.java:16)
----jGRASP wedge2: exit code for process is 1.
why it says that?
And the number by user printed twice!
a[i+1] = Math.pow(2,a[i]); // issue here
When i=a.length-1, i+1 is a.length. So there is no index value match in this array.
Suggestion:
Create an array witch has lenght= a.length+1
double powArray[] =new double[a.length+1];
Now
powArray[0]=a[0];
for(int i=1;i<powArray.length;i++){
powArray[i]=Math.pow(2,a[i-1]);
}
Issue is on line.16 as per compiler : a[i+1] = Math.pow(2,a[i]); The problem is indexes are not properly matched here.So it gives ArrayIndexOutOfBound Exception.Here i=a.length-1, i+1=a.length.So it is giving ArrayIndexOutOfBound Exception.
You should check that your index is not negative and not higher than the array length before accessing an array item.
Refer this : Avoiding index out of bounds exceptions
Concentrate on below portion of your code, its easy and you'll feel good if you figure out yourself:
for ( ;i<=a.length-1 ; i++) // check from where i starts and where it ends
{
a[i+1] = Math.pow(2,a[i]); // check what value of i would be here on each iteration
System.out.println((int)(a[i]) );
}
Also you could use a debugger and check every iteration
Few things to look upon here.
You have written a[0]= num ; which means the first value in the array is the same as the number entered by the user. Thus, you can see the number printed again. Thus,
a[0] = 1; // initial value has to be 1, contrary to what you've used
Next, your loop to generate the array values needs to be fixed. When you have i+1, the array index goes out of bounds in the last iteration, where your i is a.length - 1. Thus change your loop to something like this
for (int i = 1; i < a.length; i++) {
a[i] = Math.pow(2, a[i-1]);
}
Now, print the array values in a separate loop, as the previous loop won't print the value of the first index of the array.
for (int i = 0; i < a.length; i++) {
System.out.println((int)a[i]);
}
Change the upper limit to a.length-2 .Rest code remain same
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ;
for ( ;i<=a.length-2 ; i++) {
a[i+1] = Math.pow(2,a[i]);
System.out.println((int)(a[i]) );
}
}
}
int num ;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
a[0]= num ; //Assign First Element To Array
double prev = a[0];
for(int i=1;i<a.length;i++){
a[i] = Math.pow(2,prev);
prev = a[i];
}
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
Output
Enter a number :
3
3.0
8.0
256.0
Just change the loop to :
for(;i < a.length-1;i++)
since when you assign 4 as a length for a[]..
you have a[0],a[1],a[2],a[3]... 4 slots.
Now a.length gives 4.
so for your a[i+1] for i=a.length-1 (i.e 3 ) .. a[i+1] = a[4]... which is out of the array bound for you array.
import java.util.*;
public class Q1 {
static Scanner scan = new Scanner (System.in);
public static void main(String args [] ) {
int num;
int i = 0;
System.out.println("Enter a number :");
num = scan.nextInt();
double [] a=new double[num];
for ( ;i<a.length ; i++) {
a[i] = Math.pow(2,i);
System.out.pri``nt((int)a[i]+ " ");
}
}
}

How do I reverse the integers in one array using another array?

I have gotten 10 values from the user, and I am suppose to put that into an array and call it into a method, and then call another method which contains an array that reverses the integers of the first array without using global variables. For example, the user gives me values 1,2,3, etc.. and I store that in the first array, then in the second array I output 3,2,1.
I have part of the code that gets the integers from the user, but I don't know how to reverse the array without using global variables. The code doesn't run when it gets to the second method at values[i];
Here is what I have so far:
public static void main(String[] args) {
getInput();
reverseInput();
System.exit(0);
}
public static void getInput() {
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers.");
for (int i = 0; i<values.length; i++) {//for loop to display the values entered
values[i] = keyboard.nextInt();
System.out.println("Value" + (i +1) + " is " + values[i]);
}
}
public static void reverseInput() {
System.out.println("Now we are going to reverse the numbers.");
Scanner keyboard = new Scanner(System.in);
int [] values;
values = new int[10];
for (int i = (values.length -1); i>= 0; i--) {//for loop to display integers in reversed order
values[i];
System.out.println(values[i]);
}
}
First, if you are not going to be using global variables, then you will need to pass the array from the get input method to the reverseInput method. Something like this:
int[] values = getInput();
reverseInput(values);
Then to output the array in your reverseInput method, it would have to look like this:
public static void reverseInput(int[] values) {
for(int i = (values.length - 1); i >= 0; i--){
System.out.println(values[i]);
}
}
You can use the ArrayUtils.reverse from Commons Lang:
ArrayUtils.reverse(values);
Ok, you understand how to display the elements in reference order. As you wrote:
for (int i = (values.length - 1); i >= 0; i--) {
System.out.println(values[i]);
}
So given that, how would you put the elements of values (say it has 5 elements) in another array (call it reversedValues) such that values[4] was put into reversedValues[0] and so on up to values[0] being put into reversedValues[4]?
use the "getInput" as basis to get the 10 numbers, then after the "for" loop, just do another for loop in reverse
public static void reverseInput()
{
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers, we are going to reverse the numbers");
for (int i = 0; i<values.length; i++) //for loop to display the values entered
{
values[i] = keyboard.nextInt();
};
int[] revValues;
revValues = new int[10];
for (int i = (values.length -1); i>= 0; i--) //for loop to display integers in reversed order
{
revValues[ revValues.length -1 -i ] = values[ i ];
System.out.println( revValues[ i ] );
}
}

Categories

Resources