User input populating an array - java

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));
}

Related

How do you put an array in reverse order?

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 + " "));

Input array with scanner, now can't print array?

What I'm trying to achieve is:
Create an array, and define its length with user input (scanner). ✓
Loop through the array to fill in its values. ✓
After defining its length and filling in the values according to the length, printing the whole array. X
I wasn't able to achieve number 3. Can someone help me? I simply need to print the array.
This is my code:
package arrayinputoutput;
import java.util.Scanner;
public class ArrayInputOutput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x;
int[] test;
System.out.println("How long should the array be?");
x = input.nextInt();
for (int i = 0; i < x + 1; i++) {
input.nextLine();
System.out.println("Please fill in position " + i + ":");
i = input.nextInt();
}
//System.out.println(test[]);
}
}
after asking the size, yo have to create the array, with the size
you have to store the input in a box of the array myArray[i] = input.nextInt(); then skip a line
please use explicit name for variables
stop to size and not size+1 because indexes start to 0
So like this :
int size;
int[] myArray;
System.out.println("How long should the array be?");
size = input.nextInt();
input.nextLine();
myArray= new int[size]; //<- create array
for (int i = 0; i < size ; i++) { // <- '<size' and '<size+1'
System.out.println("Please fill in position " + i + ":");
myArray[i] = input.nextInt(); // <- store in a box of the array
input.nextLine();
}
To print the array, several options like :
System.out.println(Arrays.toString(myArray));
OR :
for (int i = 0; i < size ; i++) {
System.out.println("Value in position " + i + ":" + myArray[i]);
}
System.out.println(Arrays.toString(test));
Try using this to print the array.. Hope it works

How to insert an index of an array to another array through conditions in java

Write a java program that has 3 arrays. The first array will store lists of random integer values from 50 to 100. The program will identify passed and failed values. The second array will contain all passed values. And the third array will contain all the failed values. Required input includes size of array and passing grade. The outputs are the following: the original list, list of passed grades, and list of failed grades.
I know this is not the best code, but please do help me. I have done my research but this is all I've got.
import java.util.Arrays;
import java.util.Scanner;
public class array {
public static void main(String[] args) {
int size;
int passing;
Scanner input = new Scanner(System.in);
System.out.println("Size of Array: ");
size = input.nextInt();
System.out.println("Passing Grade: ");
passing = input.nextInt();
int [] score = new int [size];
int [] passed= new int [size];
int [] failed= new int [size];
int index = 0;
int max = 100;
int min = 50;
System.out.print("Original List:\n");
for(int a =0; a<=score.length; a++){
score[a] = min + (int)(Math.random() * ((max-min) + 1) );
System.out.print(score[a] + "\n");
}
System.out.print("Passed Values:\n");
for(int a=1; a<=score.length; a++){
if (score[a] >= passing){
int res = (passed[index++] = score[a]);
System.out.print(res + "\n");
}
}
System.out.print("Failed Values:\n");
for(int a=1; a<=score.length; a++){
if (score[a] <passing){
failed[index++] = score[a];
int res2 = (passed[index++] = score[a]);
System.out.print(res2 + "\n");
}
}
}
}
I found three main issues, for loop should check for a<score.length instead of a<=score.length. Second and third for loop initial condition should be a=0 instead of a=1. After execution of second for loop you should reset index variable to 0
public static void main(String[] args) {
int size;
int passing;
Scanner input = new Scanner(System.in);
System.out.println("Size of Array: ");
size = input.nextInt();
System.out.println("Passing Grade: ");
passing = input.nextInt();
int [] score = new int [size];
int [] passed= new int [size];
int [] failed= new int [size];
int index = 0;
int max = 100;
int min = 50;
System.out.print("Original List:\n");
for(int a =0; a<score.length; a++){
score[a] = min + (int)(Math.random() * ((max-min) + 1) );
System.out.print(score[a] + "\n");
}
System.out.print("Passed Values:\n");
for(int a=0; a<score.length; a++){
if (score[a] >= passing){
int res = (passed[index++] = score[a]);
System.out.print(res + "\n");
}
}
System.out.print("Failed Values:\n");
index = 0;
for(int a=0; a<score.length; a++){
if (score[a] <passing){
failed[index++] = score[a];
int res2 = (passed[index++] = score[a]);
System.out.print(res2 + "\n");
}
}
}

Main method not printing the number to be returned

I was trying to have my main method call on a non static array method. After calculating the minimum gap, that number is to be returned and printed by the main method, but nothing is happening after I enter the numbers for the array. Can someone tell me what is wrong?
public class Lab1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("How many elements would you like the array to have?");
Scanner input = new Scanner(System.in);
int arraySize = input.nextInt();
int value[] = new int[arraySize];
System.out.println("Enter numbers for the array.");
for (int i = 0; i < value.length; i++) {
value[i] = input.nextInt();
Lab1 lab1 = new Lab1();
lab1.minGap(value);
}
}
public int minGap(int[] value) {
if (value.length < 2)
return 0;
int minGap = value[1] - value[0];
for (int i = 2; i < value.length; i++) {
int gap = value[i] - value[i - 1];
if (gap < minGap)
minGap = gap;
}
return minGap;
}
}
You called the method for calculating the minimum number inside the for loop. But you will need the value returned by it. You will have to call that method and then print out the value returned by
that method.
Also you need to initialize the object outside the for loop.
This is how your main method code should look like :
public static void main(String[] args) {
System.out.println("How many elements would you like the array to have?");
Scanner input = new Scanner(System.in);
int arraySize = input.nextInt();
int value[] = new int[arraySize];
System.out.println("Enter numbers for the array.");
Lab1 lab1 = new Lab1();
for (int i = 0; i < value.length; i++) {
value[i] = input.nextInt();
}
System.out.println(lab1.minGap(value));
}
You are not ever printing your value. Output it to the console or application. It is returning but it does not become visible to end user unless you output it in some way.
System.out.println(ReturnedVal);

Creating an Array filled with Random doubles and finding the Maximum and Average

I need help with this program, I need to
Ask the user to input rows and column sizes using scanner
if the column size is greater than 4+5, they need to re-enter it
I need to fill all the array elements with doubles in range of 4.0, 11.0 by using random object
Find the above array and call two methods,
Method one, I need to find and print the largest sum of columns in the 2D array
Method two, I need to find the average of all elements in the array and return the average value.
Here's my code, it sort of accomplishes it, but it's also sort of messed up and I'm confused.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter row size");
int rows = input.nextInt();
System.out.println("Please enter column size");
int columns = input.nextInt();
double n = 4.0;
if (columns < n+5.0){
} else{
System.out.println("The column size is too large, please enter a smaller integer");
}
Random rand = new Random();
int[][] array = new int[rows][columns];
for(int a = 0; a<rows; a++)
for(int b = 0; b<columns; b++)
array[a][b] = rand.nextInt(11-4) + 4;
for(int i = 0; i<rows; i++){
double sum = 0;
int sum2 = 0;
for(int j = 0; j<columns; j++){
sum += array[j][i];
sum2 = sum2 + array[i][j];
System.out.println(Arrays.deepToString(array));
}
double average = sum/array.length;
System.out.println("largest sum of the columns is " + sum);
System.out.println("The average of all elements in the array is " + average);
}
}
}
You can use while loops to check if the input is even a valid integer and then if the columns count is larger than 4 + 5 ( i just assumed 9 ). I made the program flow a bit more structured and made a neat output. Basically you just would have to move the System.out.println out of the Loop like #Codebender pointed out.
package array;
import java.util.Random;
import java.util.Scanner;
public class ArrayUtil {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int columns;
int rows;
Scanner input = new Scanner(System.in);
System.out.println("Please enter row size :");
while (!input.hasNextInt()) {
System.out.println("That is not a valid Number! Try again.");
input.next();
}
rows = input.nextInt();
System.out.println("Please enter column size :");
while (!input.hasNextInt()) {
System.out.println("That is not a valid Number! Try again.");
input.next();
}
columns = input.nextInt();
while (columns > 9) {
System.out.println("The column size is too large, please enter a smaller integer!");
columns = input.nextInt();
}
Random rand = new Random();
int[][] array = new int[rows][columns];
for (int a = 0; a < rows; a++) {
for (int b = 0; b < columns; b++) {
array[a][b] = rand.nextInt(11 - 4) + 4;
}
}
for (int[] arr : array) {
StringBuilder sb = new StringBuilder();
for (int i : arr) {
sb.append("[");
sb.append(i);
sb.append("]");
}
System.out.println("Array :" + sb.toString());
System.out.println("Average : " + average(arr));
System.out.println("Max : " + max(arr));
}
}
public static double average(int[] values) {
double d = 0;
for (double value : values) {
d = value + d;
}
return (d / values.length);
}
public static double max(int[] values) {
double d = 0;
for (double value : values) {
if (value > d) {
d = value;
}
}
return d;
}
}

Categories

Resources