This block of code is supposed to sort the numbers in ascending order but it outputs vertically, how can I output them horizontally?
Example Output:
1st array: 1 2 3
2nd array: 3 4 5
3rd array: 3 4 6
int[] i1 = new int[]{3, 2, 1};
Arrays.sort(i1);
System.out.print("1st array : ");
for(int index=0; index < i1.length ; index++)
System.out.print(" " + i1[index]);
int[] i2 = new int[]{5, 4, 3};
Arrays.sort(i2);
System.out.println("2nd array : ");
for(int index=0; index < i2.length ; index++)
System.out.print(" " + i1[index]);
int[] i3 = new int[]{6, 3, 4};
Arrays.sort(i3);
System.out.print("3nd array : ");
for(int index=0; index < i3.length ; index++)
System.out.println(" " + i3[index]);
It is because you are using System.out.println. It means that it goes to the next line, it works like if you add a line break at the final of the String. Change it for System.out.print to print all your code in a line.
For example, using System.out.println:
Code
System.out.println("Hello");
System.out.println("World");
Output
Hello
World
Now using System.out.print:
Code
System.out.print("Hello");
System.out.print("World");
Output
HelloWorld
Finally using System.out.print and String with \n:
Code
String string = "Hello\nWorld";
System.out.print(string);
Output
Hello
World
Look that using \n and System.out.println have the same behaviour.
You should use System.out.print instead of System.out.println. The last one appends a line break at the end of the argument. The line break character(s) is(are) the one(s) that make a new line appears on your output.
Use StringBuilder to create a new "row" or System.out.print() to print to the same line
Something like this:
System.out.print("1st array : ");
for(int index=0; index < i1.length ; index++)
System.out.print(" " + i1[index]);
Related
I'm trying to print all the elements in an array in a new line.
however when I'm trying to print, it comes up like this: (example)
array = [1,2,3,4];
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
prints:
1,
1,2,
1,2,3,
1,2,3,4,
How do I fix it?
However when I'm trying to print, it comes up like this
No, it doesn't. Your code hardly matches the output you're giving. You make an array by [] instead of {}, and you're output gives a ,, which is nowhere to be seen in your code.
The Output you're mentioning is incorrect, the code runs as it should, producing output :
1
2
3
4
Runs here
User Arrays.toString
int[] array = {1,2,3,4};
System.out.println(Arrays.toString(array));
this answers your specific question:
int[] array = {1,2,3,4};
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
System.out.print(" ");
}
In my program, I want to display an array using Scanner, i.e the user enters the array values during runtime.
public class NameComparator {
public static void main(String args[]) {
Scanner sn = new Scanner(System.in);
int n = sn.nextInt();
System.out.println("the array size is" + n);
int[] a = new int[7];
for (int i = 0; i >= a.length; i++) {
a[i] = sn.nextInt();
System.out.println("the value of a[i]" + a[i]);
}
sn.close();
System.out.println("array values are");
}
}
Here, I have got the array size from Scanner and then using for loop to get each array value, but I don't know why the array block hasn't executed. JVM just skips the for loop. Scanner works well
This:
for(int i=0;i>=a.length;i++)
should be:
for (int i = 0; i < a.length; i++)
You want to loop as long as i is smaller than a.length (i.e. the size of the array).
The for loop will be exited (or skipped) if the termination condition returns false. Since you're initializing i with 0, i>=a.length (i.e. 0 >= 7) will be instantly false.
Please note, that I've wrote i < a.length and not i <= a.length. The array size is currently set to 7, therefore the valid indices are from 0 to 6. You'll get an ArrayIndexOutOfBoundsException if you try to access index 7.
And you forgot to use your variable n to set the array size:
int[] a= new int[n];
There are few issues:
int[] a= new int[7];//<-- why hard coded?
int[] a= new int[n];// try, you already have array size from user
for(int i=0;i>=a.length;i++)//<-- condition fails, i is 0 for the first time
for(int i=0; i < a.length; i++)//try this
Take a close look at your for loop.
for(int i=0;i>=a.length;i++)
Notice that you are using a greater than sign.
Since i equals 0, the length of a would have to be 0 for this loop to run, and we already know that you declared a with a length of 7.
I would do some searching around because there's plenty of questions similar to this.
Regardless, you have a couple things incorrect. You prompt the user for an array size but then throw it out and use 7 instead:
int[] a= new int[7];
So, this should be:
int[] a= new int[n];
Second, your loop condition:
for(int i=0;i>=a.length;i++)
will be true as long as i is greater than a, which will never happen as long as a is a positive integer (because i starts at zero). So, if we're using less than, we should also remember that arrays are zero indexed, so if you input a value of 3, you only want to populate indexes 0, 1 and 2.
So, this should instead be:
for(int i=0;i < a.length;i++)
Finally, remember to prompt the user, even if this is just a learning exercise it's good practice. Put that all together and you'll get something like this:
public static void main(String args[])
{
Scanner sn=new Scanner(System.in);
System.out.println("Please enter an array size:" );
int n=sn.nextInt();
System.out.println("the array size is "+ n);
int[] a= new int[n];
System.out.println("Please enter your " + n + "array values:");
for(int i=0;i < a.length;i++)
{
a[i]= sn.nextInt();
System.out.println("The value of a[" + i + "] is " + a[i]);
}
sn.close();
System.out.println("Array values are " );
for (int arrayValue : a)
System.out.println(" " + arrayValue);
}
change the below code
for(int i=0;i>=a.length;i++) with for(int i=0;i<a.length;i++)
the condition should be < instead of >=
also use sn.hasNext() can simplify the solution.
My programming assignment was to print an array with 10 random integers and then have 4 lines with different outputs (every even element, reverse order, etc.)
The code itself works fine (as far as I can tell) but one problem I'm having is that I had to put a System.out.println(""); before every line in order for the lines to look correct.
Initially, when I had it System.out.println("[LINE 1]....") *for loop * System.out.print("arr[i] + ", ") *close for loop * it printed each integer on a separate line instead of all on one line. Am I missing something here?? Can anyone help?
Here's my code:
import java.util.*;
public class RandomInteger {
public static void main(String[] args){
Random random = new Random();
int arr[]=new int[10];
System.out.print("The array of random numbers: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(50);
System.out.print(arr[i] + ", ");
}
System.out.println("");
System.out.print("[LINE 1] Elements at an even index: ");
for (int i = 0; i < arr.length; i++) {
if(i%2==0){
System.out.print(arr[i]+" (at index "+i + "), ");
}
}
System.out.println("");
System.out.print("[LINE 2] Every even element:");
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==0){
System.out.print(arr[i] + ", ");
}
}
System.out.println("");
System.out.print("[LINE 3] Elements in reverse order: ");
for(int i=arr.length-1;i>=0;i--){
System.out.print(arr[i] + ", ");
}
System.out.println("");
System.out.print("[LINE 4] First Element is: "+arr[0]+" and Last ELement is: "+arr[arr.length-1]);
}
}
All overloads of the println method append a newline following whatever you want to print; all overloads of the print method don't.
If all you want is a newline, then you don't even have to supply an argument -- call the no-argument println overload.
System.out.println();
Can you try with this exemple:
System.out.print("\n[LINE 2] Every even element:");
You have write \n because it is a simple way to introduce a newline although the right way isn't with system.out.print, the right way to this format is system.out.format like to c lenguage, but also used
I guess you want to remove the code System.out.println("").
use "\n"
You can change System.out.print("[LINE 1] Elements at an even index: ") to System.out.print("\n[LINE 1] Elements at an even index: ").
This question already has answers here:
Enhanced 'for' loop causes an ArrayIndexOutOfBoundsException
(2 answers)
Closed 5 years ago.
Created the below code whilst playing with loops. The code below stores the Fibonacci values into an array and then prints them using for loops.
int [] numbers;
numbers = new int[25];
numbers[0] = 1;
numbers[1] = 1;
System.out.println("Initializing the array values");
for(int i = 2; i < numbers.length; i++)
{
numbers[i] = numbers[i-1] + numbers[i-2];
}
System.out.println("Printing out Fibonacci values");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i] + ", ");
}
The above code works fine. The first time I threw it together though, I used an enhanced for loop to print out the values (the second for loop in the code). This compiles fine, but when I run it I get the following;
Initializing the array values
Printing out Fibonacci values
1, 1, 2, 3, 8, 34, 377, 17711, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 34
at ArrayDemo.main(ArrayDemo.java:21)
I don't get what went wrong. Changing the second loop shouldn't change the values (you'll notice the fibonacci values are wrong (ie missing values)). And I don't get why a simple enhanced for loop would skip indexes. Now, this isn't really a big deal because this isn't for a project or anything, it just bugs me that I can't figure out why it's doing it. Any clues?
The enhanced for loop just looked like this;
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
i here is the elements in the array, not the indexes. It could be bigger than numbers.length.
For example, if numbers = {1,2,3,9} then i will be 1, 2, 3, 9. But its length is 4, so when you loop on the elements inside it, you're trying to do numbers[9] which exceeds its size.
You probably want to System.out.print(i + ", ");
for(int i = 0; i <= numbers.length; i++) should be
for(int i = 0; i < numbers.length; i++)
In java, arrays are 0 based indexing. It means that your first element should be accessed at the index 0 and obviously the last at the length of your array minus 1.
int tab[] = new int[3]; //tab of length 3
tab[0] = 11;
tab[1] = 24;
tab[2] = 5;
Here you access the last element by calling tab[2] or tab[tab.length-1], which is equivalent.
Apologies, that was just a mistake in the code I put up in the
question.
The problem is that you should do : System.out.print(i + ", ");
You should read this and this about enhanced for loop.
The for statement also has another form designed for iteration through
Collections and arrays This form is sometimes referred to as the
enhanced for statement, and can be used to make your loops more
compact and easy to read. To demonstrate, consider the following
array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array.
So item holds the current value from the numbers array and not the current index. That's why you get an IOOBE.
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
should be
for(int i : numbers)
{
System.out.print(i + ", ");
}
You don't need to use indexes in enhanced for-loop.
I was wondering if there was a way to remove the default "0" value I get when I run the following code:
Scanner scan = new Scanner(System.in);
int [] x = new int[4];
for ( int i = 1; i < x.length; i++ )
{
System.out.println( "Enter number " + i + ": ");
x[i] = scan.nextInt();
}
Arrays.sort(x);
System.out.println(Arrays.toString(x));
}
The output is as follows
[0, i[1], i[2], i[3]]
Of course, all the array values here are actually the numbers entered into the console.
The code is WORKING. It successfully sorts any numbers into the correct order, however, there is always this nasty 0.
I'm not looking to remove ALL 0's (I want the user to be able to enter 0 and have it show up) - -I just don't want the default 0. Any ideas?
Array indexes in Java are 0-based, not 1-based. So start iterating from 0 instead of from 1 and you should be good:
for ( int i = 0; i < x.length; i++ )
for ( int i = 0; i < x.length; i++ )
When you allocate an array of size 4, you're allocating four ints: i[0],i[1],i[2], and i[3]. Because Java is fairly friendly, it sets all four of these to 0. So what you're seeing on the output is [i[0],i[1],i[2],i[3]] (in sorted order). The sort isn't adding the 0, it was already there. If you only want 3 numbers, then you should allocate an int[3] rather than an int[4]. And then, to go along with that, when you ask for number 1, store it in i[0]. The simplest change to do this would be to simply change the top line to
int [] x = new int[3];
and the later line to
x[i-1] = scan.nextInt();
The change suggested by other answers is the more common, one, though. Most programmers would have i go from 0 to 2 and then output i+1 when talking to the user.
The following code should work:
Scanner scan = new Scanner(System.in);
int[] x = new int[3];
for (int i = 0; i < x.length; i++)
{
System.out.println( "Enter number " + i + ": ");
x[i] = scan.nextInt();
}
Arrays.sort(x);
System.out.println(Arrays.toString(x));
The problem was, as others have pointed out, that your int i should start at 0, not 1.