Removing the 0 value from a sorted Array? - java

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.

Related

Variable decremantation of a Math.random ensuring non-rrepetitiveness?

I understand this is probably a noobie's question, but I can't wrap my head around it for like 30 minutes now.
I do not understand how this code manages to exclude the possibility of repeating a Math.random result.
This part:
chosenNumbers[rundom] = chosenNumbers[biggestNumber - 1];
biggestNumber--;
Somehow ensures that no number will be repeated. Can someone tell me how does it work? Does it change the value of "biggestNumber" for each every loop? And if so, Math.random can still draw a number that even multiplied by a decremented "biggestNumber" will be the exact same number that was drawn before, by multiplying by initially larger "biggestNumber".
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers do you need to draw?");
int numbersToDraw = sc.nextInt();
System.out.println("What is the biggest number?");
int biggestNumber = sc.nextInt();
int[] chosenNumbers = new int[biggestNumber];
for (int i = 0; i < chosenNumbers.length; i++){
chosenNumbers[i] = i + 1;
}
int[] result = new int[numbersToDraw];
for(int i = 0; i < result.length; i++){
int rundom = (int) (Math.random() * biggestNumber);
result[i] = chosenNumbers[rundom];
chosenNumbers[rundom] = chosenNumbers[biggestNumber - 1];
biggestNumber--;
}
Arrays.sort(result);
System.out.println("Choose the following numbers to get so really rich.");
for(int r : result){
System.out.println(r);
}
The code keeps an array of possible values -- chosenNumbers -- and uses a random number as an index into the array. Once the value is used, it removes it from the list. Even if you get the same random number again, the value at that spot will now be from that spot + 1.
For instance, if biggestNumber is 10, the array contains the values {1, 2, 3, ..., 10}.
Say you get random number 2. chosenNumbers[2] is actually 3 (because arrays index at 0), so you add 3 to the output. But then the code shifts chosenNumbers[3] -> [2], [4] -> [3], etc. So the 3 that used to be in [2] is now gone and can't be selected again.

Can someone explain me this code? About user input, scanner etc

Can someone explain to me how this code works?
It lets the user input numbers up until 1000, then it prints the original inputted numbers, the even and the odd, all in a separate array. But I just don't understand the parts where there is gem++ and gem1++ when it outputs the even and odd not the number of the even and odd numbers.
And after putting this
double even[] = new double[gem];
double odd[] = new double [gem1];
why does it need to repeat gem=0 and gem1=0 again? I'm so sorry if I ask too many question, I'm just confused, I just learned java last week.
public class wutt {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array : ");
int n = s.nextInt();
if (1 <= n && n <= 1000) {
double a[] = new double[n];
int gem = 0, gem1 = 0;
System.out.println("Enter all the elements : ");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
if (a[i] % 2 == 0)
gem++;
else
gem1++;
}
double even[] = new double[gem];
double odd[] = new double[gem1];
gem = 0;
gem1 = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
even[gem] = a[i];
gem++;
} else {
odd[gem1] = a[i];
gem1++;
}
}
System.out.println("Original: " + Arrays.toString(a));
System.out.println("Odd: " + Arrays.toString(odd));
System.out.println("Even: " + Arrays.toString(even));
} else
System.out.print("Invalid input");
}
}
If you want the program stops after the user enters a number greater than 1000 o less than 0 you need to add the break statement in your if condition.
if (size < 0 || size > 1000) {
System.out.println("Size must be between 0 and 1000");
break;
}
the code before double even[] = new double[gem];
double odd[] = new double [gem1]; is trying to get the number of odds occurred and the number of even occurred and put all inputted elements in array a.
after all that ,now what we got is a array of numbers called a containing all the inputted elements. and two numbers called gem and gem1, which contains the number of odds occurred and the number of even occurred.
so
we get gem(numberOfEvens), gem1(numberOfOdds) and list a
next, we need to put all odds from a to a new array called odd[] with size gem1, and
put all evens from a to a new array called even[] with size gem. at this point, the duty of variable gem1 and gem is done. they become useless.
now we need to go through the list and pick the odd and even out and put them in the array one by one in a sequential way. that's why we need two new variables with 0 initialized.
in this case, because gem and gem1 are useless aready, they are reassigned to help manipulate the tree arrays a , odd[] and even[]
So the user inputs the number of elements he/she wants in the array (n)
double a[] = new double[n]; // a is the array that is initialised to accommodate n elements
int gem = 0, gem1 = 0; // gem is the counter for "even" numbers and "gem1" the counter for odd numbers, and like every good counter, they start at 0
System.out.println("Enter all the elements : ");
for (int i = 0; i < n; i++) { // so we ask the user to input n elements
a[i] = s.nextInt(); // here we read every input and put it in the a array
if (a[i] % 2 == 0) // if the new number is even
gem++; // we increase the even counter "gem"
else // otherwise, when it is an odd number
gem1++; // we increase the odd counter
}
double even[] = new double[gem]; // now we create a new array where we want to hold all the even numbers, we do that by telling it how many even numbers we have counted before (gem)
double odd[] = new double[gem1]; // and a new array for all odd numbers (gem1 was our counter)
gem = 0; // now we reinitialise the counters, because we want to start from the beginning
gem1 = 0;
for (int i = 0; i < a.length; i++) { // in order to copy all numbers from the a array into the two other arrays for even and odd numbers, we iterate over the whole length of the a array. i is the index for the "a" array
if (a[i] % 2 == 0) { // ever even number we encounter
even[gem] = a[i]; // we put in the even array
gem++; // while gem, the "even numbers counter" is our index for the "even" array
} else {
odd[gem1] = a[i]; // odd numbers are for the odd array
gem1++; // while the former "odd numbers counter" now serves as our "odd" array index
}
}
and that's pretty much it. First the user inputs all numbers in a single array and simply counts how many odd and how many even numbers where inputted,
then two new arrays are created, one for the even and one for the odd numbers and since we counted them, we know how big these two new arrays have to be.
And finally all numbers are again iterated over and put in their according array.
At the end you have 3 array, one that holds all numbers, one that holds the even numbers and one with only the odd numbers.
EDIT
here are a few minor changes you could make without changing the nature of that method:
double allNumbers[] = new double[n]; // "allNumbers" is way more specific than "a"
int oddCounter = 0; // "oddCounter" instead of "gem"
int evenCounter = 0; // numbers in variables like "gem1" is really bad practice, because numbers don't say anything about the nature of the variable
System.out.println("Enter all the elements : ");
for (int i = 0; i < n; i++) {
allNumbers[i] = s.nextInt();
if (allNumbers[i] % 2 == 0) {
evenCounter++;
} else {
oddCounter++;
}
}
// until here nothing changes but the names
double even[] = new double[evenCounter];
double odd[] = new double[oddCounter];
int oddIndex = 0; // and here we create new variables, instead of reusing old ones
int evenIndex = 0; // there is absolutely no performance gain in reusing primitives like this - it's just confusing
for (int i = 0; i < allNumbers.length; i++) {
if (allNumbers[i] % 2 == 0) {
even[evenIndex++] = allNumbers[i]; // the "++" can be done directly in the first expression. that's just to make it shorter.
} else {
odd[oddIndex++] = allNumbers[i]; // it is not more performant nor easier to read - just shorter
}
}
EDIT (again)
This is how the arrays look like, say when you enter 4 numbers:
gem = 0
gem1 = 0
n = 4 // user said 4
a = [ , , , ] // array a is empty but holds the space for 4 numbers
a = [1, , , ] // user enters 1
^
i=0
gem1 = 1 // 1 is an odd number -> gem1++
a = [1,4, , ] // user entered "4"
^
i=1
gem = 1 // 4 is an even number -> gem++
a = [1,4,2, ] // user entered "2"
^
i=2
gem = 2 // 24 is an even number -> gem++
a = [1,4,2,7] // user entered "7"
^
i=3
gem1 = 2 // 7 is an odd number -> gem1++
then we fill the other arrays
even = [ , ] // gem is 2, so we have 2 even numbers
odd = [ , ] // gem1 is 2, so we have 2 odd numbers
a = [1,4,2,7]
^
i=0
odd[1, ] // for i=0, a[i] is 1, which is an odd number
a = [1,4,2,7]
^
i=1
even = [4, ] // for i=1, a[i] is 4, which is an even number
a = [1,4,2,7]
^
i=2
even = [4,2] // for i=2, a[i] is 2, which is an even number
a = [1,4,2,7]
^
i=3
odd = [1,7] // for i=3, a[i] is 7, which is an odd number
and in the end you have
a = [1,4,2,7]
even = [4,2]
odd = [1,7]

Modification of Bubblesort program with user input

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.

Inputing strings into an array

I'm a beginning programmer with the assignment to create a program that prompts the user to enter the number of elements that will then be stored into a String array. The second part of the assignment is to then list the array in ascending order. But I'm kind of stuck of the first part. If the user enters that there will be 3 elements after the 3rd string is entered I get an out of bounds exception. Below is the code.
import java.util.*;
public class arrays
{
public static void main(String[]arg)
{
Scanner input = new Scanner(System.in);
//Read user input.
System.out.print("How many Elements? ");
int num = input.nextInt();
String array[]= new String[num];
for (int i = 1 ; i <= num; i++ )
{
System.out.print("Enter element "+ i +": ");
array[i] = input.next();
}
System.out.println(array);
}
}
The array index starts at 0 so your loop should look like this:
for (int i = 0 ; i < num; i++ )
{
System.out.print("Enter element "+ (i+1) +": ");
array[i] = input.next();
}
Note that I also added +1 in the System.out.print to show "user friendly" output (e.g. "Enter element 1:" instead of "Enter element 0:" for the first element).
Another option would be to subtract 1 while accessing the array, which would allow you to keep the existing System.out.print line:
for (int i = 1 ; i <= num; i++ )
{
System.out.print("Enter element "+ i +": ");
array[i - 1] = input.next();
}
Although I feel that this is slightly less common practice.
Arrays in Java are numbered starting with zero, which means, your array of length 3 has this valid indices:
array[0]
array[1]
array[2]
I guess that's enough to send you on the right track ;-)
Start with i = 0 and go up to i < num, because in the example with three your array starts at 0 and goes up to 2, so it's no wonder that there's an out of bounds exception. That should fix the error.
you get the error because array index starts with 0. You should change your loop into this:
for (int i = 0 ; i < num; i++ )
change to array[i-1] = input.next();

java array using scanner

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.

Categories

Resources