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.
Related
I have created a program previously using the BubbleSort method that works to sort numbers in a list that already exists, however, I am having difficulty with trying to manipulate this program in order to allow a user to input the list of numbers to be sorted instead. So far I have:
import java.util.Scanner;
public class MedianValue {
public static void main(String[] args) {
//use scanner to input list of numbers to sort
Scanner scan = new Scanner(System.in);
int[] numbers = new int[] {scan.nextInt()};
//nested for loop
//outer loop just iterating
//inner loop going through and flipping
//checking if out of order (if statement)
int counter = 0;
//outer loop: keep doing this until it's sorted
for(int i = 0; i < numbers.length - 1; i = i + 1)
//put in a inner loop number.length times minus one because we don't want to swap the last element
for(counter = 0; counter < numbers.length - 1; counter = counter + 1)
{
if (numbers [counter] > numbers [counter + 1])
{
int temporary = numbers [counter];
numbers [counter] = numbers [counter + 1];
numbers [counter + 1] = temporary;
}
}
for(int i =0; i < numbers.length; i = i + 1)
{
System.out.print(numbers[i] + " ");
}
}
}
But, in this program, instead of sorting the inputted numbers, the program simply prints the first number that is inputted by the user. I am not sure if I need to move where my scanner function is placed, or add on to it within the loop for it to sort all of the numbers as I want it to do. I am lost on where to change the program if that is the case.
That's because int[] numbers = new int[] {scan.nextInt()}; is a single assigment. scan read a single input and assign to number[0].
You actually need to modify your code for scan to read n numbers and store in n-sized numbers.
something like.
int[] numbers = new int[scan.nextInt()];
for( int i = 0; i < numbers.length; i++)
numbers[i] = scan.nextInt();
The code int[] numbers = new int[] {scan.nextInt()}; will always create an array (not a List) of size 1.
Usually in these kinds of assignments you get n + 1 numbers, for example 5 3 6 2 4 1 would mean "I'm going to give you five numbers. Oh here they are: 3 6 2 4 and 1!"
You probably want something like int[] numbers = new int[scan.nextInt()]; - then loop from 0 to numbers.length to fill the array.
I am writing a program that will take user input for a random number and number of iterations. I am attempting to do a bubble sort on this (for my class I am required to do it with bubble and selection sorts). My initial code did fine till I worked to add in the portion to do iterations and then the selection sort. Now when I run my code, it will stop and give an error noted in the title of my post. The line it stops at is if randomArray[d]>randomArray[d+1] (the last line in the code below).
From what I have researched in my attempts to resolve this, it says the error is usually thrown when the array has been accessed by illegal index... or the index is negative or greater than the size of the array. I have attempted a few different things to fix this, but at the moment I am at a wall. If anyone can provide some direction, I would greatly appreciate it!
Thanks
Scanner input = new Scanner (System.in);
System.out.println("Enter a number please: ");
int n = input.nextInt();
//Get user input for number if iterations
System.out.println("Enter a number of iterations please: ");
int numIfor = input.nextInt();
//create array of random numbers
int[] randomArray = new int[n];
Random bubbleRandom = new Random();
//fill in the array of random numbers
for(int i=0; i < n; i++) {
randomArray[i] = bubbleRandom.nextInt(100);
}
//Printing the array before the sort
System.out.println("The numbers before the Bubble Sort: ");
for(int i=0; i < n; i++) {
System.out.print(randomArray[i] + " ");
}
System.out.println();
//Printing the array out after the Bubble Sort
int bubble = 0;
int sort = 0;
long startTime = System.currentTimeMillis();
for (int c=0; c < (numIfor - 1); c++)
{
for (int d=0; d < numIfor - c -1; d++)
{
if (randomArray[d]>randomArray[d+1])
{
bubble = randomArray[d];
randomArray[d] = randomArray[d+1];
randomArray[d+1] = bubble;
sort++;
}
}
}
long endTime = System.currentTimeMillis();
long runningTime = endTime-startTime;
System.out.println("The total number of iterations is: " + numIfor);
System.out.println("The total count of numbers sorted is: " + sort);
System.out.println("The total time elapsed was: " + runningTime);
System.out.println("The numbers after the Bubble Sort: ");
for(int i=0; i < n; i++){
System.out.print(randomArray[i] + " ");
}
}
}
What is probably happening is that d+1 is becoming larger than the last position of the array. You can make sure it only goes up to the end of the array by changing the last for loop as such:
The problem here is that you are looping to numIfor, which is a completely independent value from the length of the array (n). This means that if the user enters a numIfor and n, such that numIfor > n, then your code is bound to throw the exception.
The solution to this is using the actual length of the array as the limiter value instead, as such:
for (int c=0; c < randomArray.length-1; c++)
{
for (int d=0; d < randomArray.length-c-1; d++)
{
if (randomArray[d]>randomArray[d+1])
This is assuming that you want d to go through all the values of the array. But the real takeaway here is that you should always try to loop to less than the length of the array (the -1 is there because you are checking for array[d+1]). This works best if you are trying to reach all the values in the array because it guarantees that you don't go out of bounds.
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.
This is part of a larger assignment. Here, I basically need to accept user input until the user types 0. These doubles need to be added to an array. For some reason, they aren't being added to the array right now. Any help?
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
double[] inputArray = new double[3];
double input;
do{
input = scanner.nextDouble();
for(int i = 0; i < 3; i++){
inputArray[i] = input;
}
}
while(input != 0);
System.out.println("Element 0:" + inputArray[0]);
System.out.println("Element 1:" + inputArray[1]);
}
You're keeping on iterating until input is 0... so on the last iteration of the loop before it terminates, we know that input will be 0.
Now look at what you're doing in the while loop:
for(int i = 0; i < 3; i++){
inputArray[i] = input;
}
You're replacing all the elements in the array with the current value of input.
So by the time you exit the loop, you've just replaced all the elements with 0.
It would be much better to use a List<Double> with a suitable implementation (e.g. ArrayList<Double>) and just call list.add(input) within the while loop.
Then to print out every element of the list:
for (Double value : list) {
System.out.println(value);
}
Or if you really want the index:
for (int i = 0; list.size(); i++) {
System.out.println("Element " + i + ": " + list.get(i));
}
If you have to use an array, you should keep track of how many items you've already set (with a counter incremented in the while loop) and only set one value in the array for each iteration of the loop. Don't forget to terminate the loop if you run out of space in the array, too!
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.