How do you put an array in reverse order? - java

I wrote this program in Java : Write a program that reads a list of integers and outputs those integers in reverse. The input begins with an integer indicating the number of integers that follow. For coding simplicity, follow each output integer by a comma, including the last one. Assume that the list will always contain fewer than 20 integers.
Ex: If the input is:
5 2 4 6 8 10
the output is:
10,8,6,4,2
As you can see, this is my expected out^ However, I got 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 8 6 4 2 as my output. What is wrong?
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] userList = new int[20]; // List of numElement integers specified by the user
int numElements; // Number of integers in user's list
int i;
numElements = scnr.nextInt(); // Input begins with number of integers that follow
for (i = 0; i < numElements; ++i) {
userList[i] = scnr.nextInt();
}
for (i = userList.length - 1; i >= 0; --i) {
System.out.print(userList[i] + " ");
}
System.out.println();
}
}
I tried to ask a good question and I expect an answer to my question.

Explanation
You are getting zero maybe due to the array size declaration. You created an array with 20 as the size. But assuming you set the numElements to 10, that means that the input iteration will only loop 10 times thus only loading 10 positions in your array.
As you had defined an array with 20 indexes, the rest are initiated with a zero during array declaration. So assuming the iterations goes 10 times that means only 10 indexes will be updated and the other 10/20 left with their initial zeros.
You have to re-declare your array after getting a value for the numElements and set the numElements as the new array size. The code would look similar to below
Scanner scanner = new Scanner(System.in); // Create Scanner object
int[] userList = new int[0]; // Create int array
int numElements = scanner.nextInt(); // Get number of elements
userList = new int[numElements]; // Re-declare array with new size
Solution
The full code in your approach is as below:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int numElements; // Number of integers in user's list int i;
System.out.println("Input length of the array");
numElements = scnr.nextInt(); // Input begins with number of integers that follow
int[] userList = new int[0];
// Check size value (number of elements)
if (numElements > 0) {
userList = new int[numElements]; // Re-Declare array giving it a new size
} else {
System.out.println("This array size cannot be less than 1");
}
System.out.println();
for(int i = 0; i < numElements; ++i) {
System.out.println("Input number at position " + i);
userList[i] = scnr.nextInt();
}
for (int i = userList.length -1; i >= 0; i--) {
//for (int i = userList.length-1; i >= 0; --i) {
System.out.print(userList[i] + " ");
}
System.out.println();
}

you have to create a list of size numElements,
int[] userList = new int[numElements];
for(i = 0;i < numElements; ++i) {
userList[i] = scnr.nextInt();
}
for (i = userList.length-1; i >= 0; --i) {
System.out.print(userList[i] + " ");
}
System.out.println();

Your code is fine but you just need to read the number of element before creating your userList :
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int numElements; // Number of integers in user's list
numElements = scnr.nextInt(); // Input begins with number of integers that follow
int[] userList = new int[numElements]; // List of numElement integers specified by the user
int i;
for (i = 0; i < numElements; ++i) {
userList[i] = scnr.nextInt();
}
for (i = userList.length - 1; i >= 0; --i) {
System.out.print(userList[i] + " ");
}
System.out.println();
}
}

Your array size is 20 and your are trying to print whole array in reverse order which includes unfilled indexes also. so try to make array size as numElements and print it will work

In order to reduce the lines of code and use streams, the following code would work -
Accept input numbers and store them in the array of size numElements. Use "ArrayUtils" to reverse the array. Details about the reverse() can be referred here.
Scanner scnr = new Scanner(System.in);
int numElements;
numElements = scnr.nextInt();
int[] userList = new int[numElements];
for (int i = 0; i < numElements; ++i)
userList[i] = scnr.nextInt();
ArrayUtils.reverse(userList);
Arrays.stream(userList).forEach(number -> System.out.print(number + " "));

Related

User input populating an array

How can I create a 20-element integer array and let the user populate it?
I tried the following:
import java.util.*;
class Selection{
public static void main(String[] args){
int x = 0;
int y = 0;
int a [] = new int [x];
Scanner in = new Scanner (System.in);
while(a.length<21){
System.out.print("Enter element number " + (y+1) + " : ");
x = in.nextInt();
y++;
}
System.out.println(a);
}
}
You need to set the array to be size 20:
int[] a = new int[20];
Then, in a for loop based on the length of the array, let the user enter numbers:
for (int i = 0; i < a.length; i++) {
System.out.print("Enter element number " + i + " : ");
a[i] = in.nextInt();
}
Here is a revision of your class that shows how to properly declare, fill, and print the array:
import java.util.*;
public class Selection {
public static void main(String[] args) {
int[] a = new int[20];
Scanner in = new Scanner(System.in);
for (int i = 0; i < a.length; i++) {
System.out.print("Enter element number " + i + " : ");
a[i] = in.nextInt();
}
// if you want to display the array after filling, there are 2 standard ways
for (int element : a) {
System.out.println(element); // displays each on a new line
}
// or, using Arrays.toString() (from the java.util package)
System.out.println(Arrays.toString(a));
}
}
Before Populated array u have to set array size. in you case you need to set array set up to 20.
int[] a = new int[20];
There's a couple things you're missing. You want to initialize int[] a with a size of 20 like so int[] a = new int[20]. You need to place int a[] into your while loop so that you can store the integers.
Looks like you're iterating with y, so y will work as our element index into which we will store the int that the user inputs. Lastly, you can't print out int[] a like that, you need to either iterate through it and print each value at each index yourself, or use the Arrays.toString() utility which can be accessed by placing import java.util.Arrays; at the top of your file along with your other imports. Putting this all together, your main method should look like this:
public static void main(String[] args) {
int x = 0;
int y = 0;
int a[] = new int[20];
Scanner in = new Scanner(System.in);
while (y < a.length) {
System.out.print("Enter element number " + (y + 1) + " : ");
x = in.nextInt();
a[y] = x;
y++;
}
System.out.println(Arrays.toString(a));
}

How do I create a counter for each element in an array?

So I have to write a program that reads an arbitrary number of integers that are in the range 0 to 50 inclusive and counts how many occurrences of each are entered. Indicate the end of the input by a value outside of the range. After all input has been processed., print all of the values (with the number of occurrences) that were entered one or more time.
public class problem
{
public static void main(String[] args)
{
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int userInput = 0;
ArrayList<Integer> myList = new ArrayList<Integer>();
int index = -1;
for (int num = 0; num <= userInput ; num++)
{
System.out.println("Please enter a random number between 0 and 50, enter a negative number to end input: ");
num--;
if(userInput >= 0 || userInput <= 50)
{
userInput++;
userInput = scan.nextInt();
index++;
myList.add(userInput);
}
if (userInput < 0 || userInput > 50)
{
myList.remove(index);
index--;
break;
}
}
for (int num: myList)
System.out.print(num + " ");
}
}
This is what I have so far, but I am stuck as to how to count each integer occurrence in myList.
If I understand your question correctly, you can do something like this
public static void main(String[] args) {
int max = 200; // this is just for test
HashMap<Integer, Integer> counter = new HashMap<>();
for(int i = 0;i < max; i++){
int value = (int) (Math.random() * 50); // generate random numbers
if(counter.containsKey(value)){ // if map contains value, increment it's count
counter.put(value, counter.get(value)+1);
}else{
counter.put(value, 1); //put it and start from 1
}
}
System.out.println(counter);
}
}

How Can this code be adjusted to input and print a list of numbers?

I'm trying to create a program that allows the user to input numbers into a array called "numArray", however an exception is thrown once the user inputs numbers into array. How can this be fixed?
import java.util.Scanner;
class ArrayNumList
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.println("How many nums would you like to enter? ");
int n = in.nextInt();
System.out.println("Enter " + n + " nums");
int[] numArray = new int[n];
for(int i = 0; i <= n; i++)
{
int index = in.nextInt();
System.out.print(numArray[index]);
}
}
}
There is no index index if the user inserts a big enough number / negative number. Fix it by using the actual loop variable i like this:
for(int i = 0; i <= n; i++) {
numArray[i] = in.nextInt();
System.out.print(numArray[i]);
}
The problem is that you aren't storing your data anywhere in the array.
for(int i = 0; i <= n; i++)
{
int index = in.nextInt();
System.out.print(numArray[index]);
}
Every time you run through the array, you store your input into the variable index. From there, you try to display the value in your array at that index. This can lead to a few problems.
1) You haven't put your numbers into this array yet, so each value in the array is going to be 0. To fix this:
numArray[i] = in.nextInt();
2) If someone inputs a number that's bigger than the size of your array, you'll get an IndexOutOfBoundsException. I don't think you were trying to do it this way, but this is what your code is currently attempting to do.
There are 3 issues:-
1) Use i < n as you start from 0
2) Trying to add input value as index in the array.
3) Printing out the values while entering which create confusion for you better to do that in separate loop but I leave it to u or Better to use println instead of print
Try this:-
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
System.out.println("How many nums would you like to enter? ");
int n = in.nextInt();
System.out.println("Enter " + n + " nums");
int[] numArray = new int[n];
for(int i = 0; i < n; i++)
{
numArray[i] = in.nextInt();
System.out.println(numArray[i]);
}
}
Firstly it should be i<n and not i<=n because n means the array length and i means the array index. The index starts from 0. For eg an array holds the values 1234, so the length is 4 but the index are 0,1,2,3. So the index is always one less than the array length. Also you have to store the input with the array index.
for(int i = 0; i < n; i++)
{
numArray[i] = in.nextInt();
}
And then later print it
for(int i = 0; i < n; i++)
{
System.out.println(numArray[i]);
}

Java arrays how to save it in the array

How do I save it actually in the Array?
With this code it doesn't save anything in the array
I hope you can tell me more ways how to do it and explain in detail, thank you very much
import java.util.Scanner;
public class CountArray
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
int countPOZ = 0;
int countP5 = 0;
int countNONE = 0;
System.out.println();
System.out.print("Type elements: ");
int[] x = new int [scan.nextInt()];
for(int i = 0; i < x.length; i++)
{
System.out.print("Type numbers: ");
int numrat = scan.nextInt();
if(numrat > 0)
countPOZ++;
else if (numrat % 5 == 0)
countP5++;
else
countNONE++;
}
System.out.println();
System.out.println(x[1]); //here it will display 0 because nothing is saved.. in the array
System.out.println("Positive: "+countPOZ);
System.out.println("Div.. with 5: "+countP5);
System.out.println("Others: "+countNONE);
}
}
You store a value in the ith position of your x array with:
x[i] = someValue;
In the context of your loop :
for(int i = 0; i < x.length; i++)
{
System.out.print("Type numbers: ");
int numrat = scan.nextInt();
if(numrat > 0)
countPOZ++;
else if (numrat % 5 == 0)
countP5++;
else
countNONE++;
x[i] = numrat;
}
This stores the user's input in order.
x[i] = scan.nextInt();
Remove the local numrat and use x[i]. And please use braces, something like
x[i] = scan.nextInt();
if(x[i] > 0) {
countPOZ++;
} else if (x[i] % 5 == 0) {
countP5++;
} else {
countNONE++;
}
This is covered in and an example to JLS-10.4 - Array Access.
A component of an array is accessed by an array access expression (ยง15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
Try, add values in array then use array for business logic.
int[] x = new int [scan.nextInt()];
for(int i = 0; i < x.length; i++){
System.out.print("Type numbers: ");
x[i] = scan.nextInt();
if(x[i] > 0)
countPOZ++;
else if (x[i] % 5 == 0)
countP5++;
else
countNONE++;
}
But you missing something int[] x = new int [scan.nextInt()] as per your code you are not passing only one element and add that element to your array.
I assist pass multiple elements as comma separated list 1,2,3,4,5,6,7 then in your code you can create array list int x[] = scan.nextInt().split(",") then use it.
in your code
int[] x = new int [scan.nextInt()];
you are defining the size of an array. you are not storing any elements in here.
So define any elements in an array you have to access it's index and store your value in that specific index
x[1] = scan.nextInt()
can store the values in specific index

User input arrays

I am trying to create a program that sorts user inputted integers from greatest to least. Also I need to find a way to print the maximum and minimum numbers. The code was sorting fine when I had defined values but now that I have switched it to user input it sends back "0"s for some reason. This is my code
import java.util.Scanner;
public class SortInteger {
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i>number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length-1; i++){ //outputs the array to user
System.out.println(number[i]);
}
}
}
you have taken only one number
int num = input.nextInt();
and you are using it for array size :
int number [] = new int [num];
but in rest of the code you haven't taken any input so your array is empty.
Code::
import java.util.*;
class test{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int number [] = {num1,num2,num3}; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i<number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length; i++){ //outputs the array to user
System.out.println(number[i]);
}
}}
Output::
Please input three numbers
1
5
4
1
4
5
you are only initializing your array. you never initialized your array with elements, thus your array elements get default values.
System.out.println("Please enter size");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
for(int i=0; i<number.length; i++){
System.out.println("Please enter element at index " + i);
number[i] = input.nextInt()
}
As others pointed out you need to populate your array with multiple values, currently you are requesting only one int.
Also, are you sure that works? Should't your first for loop read:
for(int i = 0; i<number.length-1; i++ )
Instead of:
for(int i = 0; i>number.length-1; i++ )
On a side note, it looks to me that your sorting algorithm is O(n2) you may want to look into mergesort and quicksort.

Categories

Resources