Sorting array in an ascending array - java

When I try to sort the array, the result that I get is:
The sorted array is [0, 0, 0, 0, 0, 0, 0, 0]
The user fills the array with 8 numbers that should be eventually sorted. But what I'm getting is a bunch of 0s.
Why am I getting 0s?
import java.util.Scanner;
import java.util.Arrays;
public class SortArray {
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int[] numbers = new int[8];
for(int i = 0; i < numbers.length; i++)
{
System.out.println("Enter the number for index " + i);
int number = kbd.nextInt();
}
for(int i = 0; i < numbers.length; i++)
for(int j = 1; j < numbers.length; j++)
{
if (numbers[i] > numbers[j])
{
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
System.out.println("The sorted array is " + Arrays.toString(numbers));
}
}

You are not assigning the user inputs to your array, which is why all the elements remain 0.
change
int number = kbd.nextInt();
to
numbers[i] = kbd.nextInt();

The issue is within these lines of code:
for(int i = 0; i < numbers.length; i++)
{
System.out.println("Enter the number for index " + i);
int number = kbd.nextInt();
}
Specifically int number = kbd.nextInt();
To add a little bit of explanation to Eran's answer, what you did in that line above is create a new variable number, and assign the value you get from the Scanner kbd. As you declare an int (meaning you write int on the left hand side) you're creating a variable that will hold an int value.
The main issue here is that right after you assign it to a variable called number, your loop closes and the variable is not used at all. It gets destroyed/removed/garbage-collected and the value is released. Next time you come around that loop again, a new variable called number is once again assigned with that value from the scanner.
Also notice now number and numbers are of different types, numbers is an array of ints, while number is just an int.
By changing int number to numbers[i], you're telling Java to assign the int received from the scanner kbd to the array numbers at position i. That way you don't lose the value and it gets saved inside the array, which is why when you print the array you no longer get all 0s. (the reason why you previously got all zeros is because you initialized an array of ints, but never given them values, so Java defaults to 0.

Related

Java: Print out each number in an array without printing its an repeats of that number?

Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}

Array- keep track of number of frequency from user input

I planned a simple program that would take 10 int from the user and if the user enters the same number, it would be added to a new array called Frequency.
For example, the user enters [1,5,2,1,5,7,8,4,5,9] , the frequency array would be [2,3,1,2,3,1,1,1,3,1].
Here's what I've tried so far but I am not succeeding to complete this.
int[] arr = new int [10];
Scanner s = new Scanner(System.in);
for(int i = 0; i< arr.length; i++)
{
System.out.println("Enter upto 10 numbers:");
arr[i] = s.nextInt();
}
int[] freq = new int[10];
for(int i=0; i< arr.length; i++)
{
//Frequency Method
}
public static int frequency(int[] total)
{
int count = 0;
// lost from here
}
return count;
}
Any help is appreciated. Thank you for your time and effort
In the static method, I would modify so that it takes an int[] total and int value and in the method, create a new int called counter that has value of 0 and make a for-loop that iterates through int[] total and compares if int[i] total == value and if it does, you increase the counter by one and return the counter.
Once you have frequency done, make another for loop to iterate through array with user input and in the for loop, add freq[i] = frequency(arr, arr[i]); which will add repetitive numbers in the frequency array.
Just for fun, here is the one-line solution using Java streams:
int[] freq = Arrays.stream(arr).map(x->(int)Arrays.stream(arr).filter(y->x==y).count()).toArray();

How to print out even-numbered indexes for arrays in Java?

I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}

How can I change the values exceeding the int data type to the long data type in this code?

In the last portion of this code (where the last for loop and if statements are), I'm trying to change the data type of the integers to long when they exceed the integer data type limit. What am I doing wrong in this code? When I run, I get the same values as before I even tried to change them to long (which are increasingly huge integers until they get negative).
public class UniqueElements {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int maxValue = 0;
int numElements = 0;
int programRuns = 12;
Scanner sc = new Scanner(System.in);
for (int newExecution = 0; newExecution <= programRuns; newExecution++ ) {
System.out.print("Enter the maximum value for an element: ");
//prompt user to enter the maximum value
maxValue = sc.nextInt(); //user input for max value
System.out.print("Enter the number of elements in the array: ");
numElements = sc.nextInt(); //number of elements in an array
int A[] = new int[numElements];
//array comprising of the number of elements chosen by the user
int totalComp = 0; //set total comparisons to 0
for (int runs = 1; runs <= 100; runs++) { //program runs 100 times
Random rand = new Random(System.nanoTime());
//initiate the random number generator
int numComp = 0; //set number of comparisons to 0
for (int index = 0; index < numElements; index++) {
A[index] = rand.nextInt(maxValue);
//length of array is the number of elements the user puts in
}
for (int i = 0; i < A.length; i++) { //for each integer in the array
for (int j = i + 1; j < A.length; j++) {
//for each integer following i
if (A[i] == A[j]) { //if the are equal to eachother
//end the if statement
break;
}
if (numComp == (int)numComp) {
numComp++;
}
else {
Long.valueOf(numComp);
numComp++;
}
}
}
totalComp+= numComp;
} //end 100 loops
if (totalComp == (int)totalComp)
System.out.println("Average number of comparisons: " + totalComp / 100);
else {
System.out.println("Average number of comparisons: " +
Long.valueOf(totalComp) / 100L);
}
}
}
}
update:
somehow.... changing the total number of runs to 2 and dividing the totalComp variable by 2 and 2L made it work. Anyone know how that changed it?
You can't change the type of a variable after it's already been declared. You can cast that variable to another type, or "interpret" it as another type (as in your Long.valueOf()), but the variable still remains whatever type you declared it as.
In your code, you've declared totalComp to be an int, which in Java means it holds 32 bits (one of which is a sign bit). There's no way to make Java store more than 32 bits in an int. If you continue to add beyond Integer.MAX_VALUE, or subtract below Integer.MIN_VALUE, the value in the variable will simply under/overflow. So this statement after your for loop isn't doing what you expect, and will always be true: if (totalComp == (int)totalComp)
In other words, you can't go "back in time" and re-declare your primitive int as a long because you found out at runtime that you need to store larger values. The easiest way to solve this problem would be to declare totalComp as a long. If for some reason you can't change the type of totalComp, it is possible to detect overflow/underflow before performing the calculation; see this answer for details.

How to get the largest number in an array?

I am trying to find the largest number in an array of 10 numbers. Here is my code:
public static void getNumber() {
int NumbersArray[] = new int[11];
int num1;
int num2;
int largestNumber = 0;
Scanner scanner = new Scanner(System.in);
for(int i=1; i<11; i++){
System.out.println("Enter number " + i );
int no1 = scanner.nextInt();
NumbersArray[i] = no1;
}
scanner.close();
for(int i=1; i<11; i++)
{
System.out.println(NumbersArray[i]);
num1 = NumbersArray[i];
for(int j=10; j>0; j--)
{
num2 = NumbersArray[j];
if(num1>num2){
largestNumber = num1;
}
}
}
System.out.println("the largest number is " + largestNumber);
}
I found a real simple soultion to this here.
But the reason I am posting this is to find out what mistake have I made.
The first portion gets 10 numbers from the users and the second portion is my code to find the largest number.
Going off Pshemo's suggestion, keep a record of the largest int as the user is typing. This reduces the size of your method by half and makes it much simpler and more readable.
Program with 0-based indexing. So use int NumbersArray[] = new int[10] instead of int NumbersArray[] = new int[11]. When you declare the size of your array, simply put your desired size, you don't have to worry about 0 indexing or anything. For your for-loop, start at int i=0 and end at i<10.
public static void getNumber(){
int NumbersArray[] = new int[10];
int largestNumber = 0;
Scanner scanner = new Scanner(System.in);
for(int i=0; i<10; i++){
System.out.println("Enter number " + i );
int no1 = scanner.nextInt();
NumbersArray[i] = no1;
if(no1 > largestNumber)
largestNumber = no1;
}
scanner.close();
System.out.println("The largest number is: " + largestNumber);
}
The problem is that you are iterating through the list twice (in a nested way). Let's say you have the following numbers: [5, 7, 3, 4]. As you go through the inner loop the first time you'll end up comparing numbers against 5. Only 7 is larger so largestNumber will be set to 7. Then you'll go through again, this time comparing against 7. Nothing is larger than 7, so it'll be left alone. Next you'll compare against 3. The last comparison there is 3 vs. 4, and since 4 is larger you end up setting largestNumber to 4, which is incorrect.
These lines:
for(int i=1; i<11; i++)
{
System.out.println(NumbersArray[i]);
num1 = NumbersArray[i];
for(int j=10; j>0; j--)
{
num2 = NumbersArray[j];
if(num1>num2){
largestNumber = num1;
}
}
}
Don't search for the largest number in the array, but simply search for any value in NumbersArray a value that is bigger than the current element. Thus largestNumber isn't the largest number in the array, but the last number in NumbersArray that is larger than the last element of NumbersArray, unless the last element of NumbersArray is the biggest element, in this case the largestNumber will be the last value in NumbersArray.
A working solution would be:
int max = Integer.MIN_VALUE;
for(int i : NumbersArray)
if(max < i)
max = i;
Though the most efficient solution would be to directly keep track of the currently largest input while reading the input.
And keep in mind that java-arrays are 0-based. This means that the first element is at NumbersArray[0], not NumbersArray[1], like in your code.
As far as I know you can use Java Math max() method to get largest number.
i.e. : dataType max(int number1, int number2), Math.max(number1, number2) gets the maximum between number 1 and 2.

Categories