Q: Sorting of Numeric array in java - java

I am trying to sort a numeric array in ascending and descending order. I am beginner so using the following link Sort an array in Java . I am trying to get input from user as array's elements.
public class SortingofString {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int Array1[];
// String Array2[];
System.out.println("How many numaric elements: ");
int n = input.nextInt();
int[] array1 = new int[n];
int number=input.nextInt();
for(int i=0; i<n; i++){
System.out.println("Enter number:");
array1[i] = number;
System.out.println("Original numeric array : "+Arrays.toString(Array1));
Arrays.sort(Array1);
System.out.println("Sorted numeric array : "+Arrays.toString(Array1));
}
}
}
The error occurs when i pass my array_name Array1 in first toString function.System.out.println("Original numeric array : "+Arrays.toString(Array1));
Error says Initialize variable Array1 . How can i resolve this error?

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//int Array1[];
System.out.println("How many numaric elements: ");
int n = input.nextInt();
int arr[] = new int[n];// solve 1st problem
for (int i = 0; i < n; i++) {
System.out.println("Enter number: " +(i+1));
int number = input.nextInt();
arr[i]=number;//init array by user input data
}
System.out.println("Original numeric array : " + Arrays.toString(arr));
Arrays.sort(arr);
System.out.println("Sorted numeric array : " + Arrays.toString(arr));
}
you also need 2 import
import java.util.Arrays;
import java.util.Scanner;

Move (and rename) Array1 behind reading n:
System.out.println("How many numaric elements: ");
int n = input.nextInt();
int[] array1 = new int[n];
And maybe use the entered number:
int number = input.nextInt();
array1[i] = number;

Related

How would I make the application add all the values of the integers in the arraylist so I could find the median of each grade?

import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many grades do you want to input: ");
int amount = scanner.nextInt();
int i = 0;
ArrayList<Integer> myList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (i < amount) {
System.out.print("Enter a grade (between 0 and 100): ");
myList.add(sc.nextInt());
i++;
}
int highestNumber = Collections.max(myList);
int lowestNumber = Collections.min(myList);
System.out.println("The highest grade is: " + highestNumber);
System.out.println("The lowest grade is: " + lowestNumber);
}
}
your code already does that
you just have to add at the following at the end of your main to see your list
System.out.println(myList);
To find the median.
sort the array.
if the array contains an odd number of elements, take the middle value of the array.
if the array contains an even number, add the two values in the middle and divide by 2
So the median is the value such that there are just as many above it as below it.
a = {1,2,3,5,1000,2000,3000}
The median of the values in a is 5

Searching element in aray

I'm trying to create a program that asks the user the number of elements inside an array and prints its original list reverse list and assending. In, addition I'm also trying to find an element inside an array and print found and the index number if it is inside the array. So far here is my code:
public static void main(String[] args){
int n, y, z, temp=0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store here: ");
n = sc.nextInt();
int[] a = new int[10];
System.out.println("Enter elements here: ");
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
System.out.print("\nOriginal list: ");
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
System.out.print("\nReverse list: ");
for(int i=n-1;i>=0;i--){
System.out.print(a[i]+" ");
}
// it seems to copy the assending list. It should print the integers the way user entered it
System.out.print("\nOriginal list: ");
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
for(y=0;y<n;y++){
for(z=y+1;z<n;z++){
if(a[y]>a[z]){
temp=a[y];
a[y]=a[z];
a[z]=temp;
}
}
}
{System.out.print("\nAscending Order list: ");
for(y=0;y<n;y++){
System.out.print(""+a[y]+" ");
}}
System.out.print("\nEnter the element you want to search: ");
s = sc.nextInt();
for(y=0;y<n;y++)
{
if(a[y]==s)
{
System.out.println("Element "+s+" is in "+y+" index");
f=1;
}
}
if(f==0)
{
System.out.println("Element "+s+" is not found");
}
}
}
My problem is the last original list.
First of all, you are taking an array not a list. Here you were not taking the user-defined array size. Rather you were taking an array of 10 elemets. Then you were swapping the elements of the original array. This caused the array elements to be rearranged. So, the original array got changed while you were swapping elements. In this case, you should take a copy of the array. And finding index numbers is pretty easy. Just loop over the elements and you are good to go. Hope this helps:
public static void main(String[] args)
{
int n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store here: ");
n = sc.nextInt();
int[] a = new int[n]; //Number of array member should be declared here
System.out.println("Enter array elements here: ");
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.print("\nOriginal array: ");
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
System.out.print("\nReverse array: ");
for(int i=n-1; i>=0; i--)
{
System.out.print(a[i]+" ");
}
System.out.print("\nOriginal array: ");
for(int i=0; i<n; i++)
{
System.out.print(a[i]+" ");
}
//This is where you should make a copy of the original array. You are swapping variable. That's mean array is also getting swapped
System.out.print("\nAscending Order array: ");
int[] tempArray = a;
Arrays.sort(tempArray);
for (int j : tempArray)
{
System.out.print(j + " ");
}
System.out.println();
System.out.print("Enter the number you want to find: ");
int toFind = sc.nextInt();
boolean found = false;
for(int i=0; i<n; i++)
{
if(a[i] == toFind)
{
found = true;
}
}
if(found)
System.out.println(toFind + " is found.");
else
System.out.println(toFind + " is not found.");
}

How to display the value of an array by the index number?

The user enters 10 numbers. After that, the program asks the user to enter the index number they want to retrieve like the example below.
How do I ask the user to input an index number and print the array in that specific index number?
This is my code so far
public class ArrayElement {
public static void main(String[] args) {
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i<10; i++){
Array[i] = input.nextInt();
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
}
}
public static void main(String[] args) {
int [] Array = new int[10];
int index;
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 elements:");
for (int i = 0; i<10; i++){
Array[i] = input.nextInt();
}
System.out.print("Enter an index you want to retrieve: ");
index = input.nextInt();
System.out.print("Element at index "+index+" is "+Array[index]);
}
Output : Element at index 6 is 42
you can get the element of a particular index of an array as follows
int element = Array[index];

In Java how to calculate a series of numbers to find the product, that is passed to a method that uses a variable-length argument list

This program is supposed to take a series of numbers, that is put into an array by the user. Not sure on how to do the calculation correctly when using the elements from the array inside of the method that I had made.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//****Sentinel****
int s;
//****Do...While Statement****
do{
//****User Input****
System.out.println("Welcome! Please enter a 1 to continue, or 2 to exit.");
s = sc.nextInt();
System.out.println();
switch(s){
case 1:
//****Array****
ArrayList<Integer> nums;
nums = new ArrayList<>();
//****User Input****
System.out.println("Please enter 4 integers: ");
System.out.println("*************************************************");
for(int i = 0; i < 4; i++){
nums.add(sc.nextInt());//****User adds to Array****
}
System.out.println("*************************************************");
//****Call Method****
Product();
break;
}
}while(s != 2);//****end Do...While****
}
//****Product Method****
public static void Product(int... nums){
//****variables****
int result;
int sum = 0;
//****iterate through array****
for(int n : nums){
sum += n;
}
//****Multiply****
int product = (sum * nums.length);
result = product;
//****User Output****
System.out.println("The product of the numbers is: " + result);
System.out.println();
System.out.println("*************************************************");
}
The only thing I get for output is a 0.
You are not passing the array to your method.
//****Call Method****
Product();
You should be passing the array there.

Java User Input array is only capturing 3 integers instead of five

This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0" which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[i]);
++j;
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[i] + " ");
}
}
}
You need to work more about on for loops and study how to iterate values in for loop, the problem in your i,j variables.
Here I fix your code.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
//for 5 inputs you need loop
for(;i<NUM_VALS;i++){
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
}
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[j]);
//++j; //no need to increment as you already did in for loop
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[j] + " ");// userNum[0] = your last value which you reverse
}
}
}
Here is a solution using the collections framework:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final List<Integer> numbers = new ArrayList<>();
System.out.println("Enter any number of integers. (whitespace delimited. enter a non-integer to quit.): ");
while (scnr.hasNextBigInteger()) {
final int n = scnr.nextInt();
System.out.println("Parsed: " + n);
numbers.add(n);
}
System.out.println("Done reading user input.");
System.out.println("Your input: " + numbers);
Collections.reverse(numbers);
System.out.println("Your input reversed: " + numbers);
}
}
I have provided you with a solution. This is a clean way of doing it.
nextInt() reads the next integer that the user inputs. Notice that this will throw a InputMismatchExceptionif the user does not input a integer as value.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> input = new ArrayList<Integer>();
//Simple loop that will read 5 user inputs
//and add them to the input list
for(int i = 0; i < 5; i++){
input.add(scanner.nextInt());
}
//print the 5 values
for(Integer val : input){
System.out.println(val);
}
//reverse the 5 values
Collections.reverse(input);
//print the 5 values again, but they are now reversed
for(Integer val : input){
System.out.println(val);
}
}

Categories