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
Related
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 + " "));
For example (we are told we want to go up to 'X'):
Scanner scan = new Scanner(System.in);
for (int i; i <= X; i++)
{
System.out.println("Enter the value for value " + i)'
int valuei = scan.nextInt();
}
So instead of constantly reasssining a value to the one variable 'valuei',
our program would create X number of integer variables as well as assigning them the corresponding user input as values.
'value1' gets the value the user had input as an answer at index 1
'value2' gets the value the user had input as an answer at index 2
...
'valuei' gets the value the user inputs as an answer at index i
If not possible, what would be the most efficient way to accomplish the above?
Thanks
It looks like you are wanting to use arrays
Scanner scan = new Scanner(System.in);
int arr [] = new int [X];
for (int i = 0; i < X; i++)
{
System.out.println("Enter the value for value " + i)'
arr[i] = scan.nextInt();
}
If you are just reading it then you can just need to read the value from user and it should be i<x because index starts at 0.
`Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
for (int i=0; i < x; i++) {
System.out.println("Enter the value for value " + i);
int valuei = scan.nextInt();
}`
If you want to read that in an array :
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int[] arr = new int[x];
for (int i = 0; i < x; i++) {
System.out.println("Enter the value for value " + i);
arr[i] = scan.nextInt();
}
You can use an array
int []valuei = new int[X];
valuei [0] gets first input.
valuei [1] gets second input.
....
valuei [X-1] gets Xth input.
Scanner scan = new Scanner(System.in);
int []valuei = new int[X];
for (int i=0; i < X; i++)
{
System.out.println("Enter the value for value " + i);
valuei[i]=scan.nextInt();
}
Arrays.
An array is a container object that holds a fixed number of values of a single type
For example:
int[] value = new int[X];
for (int i=0; i < X; i++)
{
System.out.println("Enter the value for value " + i);
value[i] = scan.nextInt();
}
Also note how loop changed to int i=0; i < X; i++
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));
}
hi guys i've had some help with this program today, basically what i want is for an array of 1 - 200 to be held, then the user inputs a number between 1 and 200.
The ramaning numbers are then added together and the answer outputted.
e.g. user enters 100, numbers from 100-200 are then added together and answer is output.
With the code i have so far it is always outputting 0 as the answer. Any ideas?
thanks.
//Importing scanner
import java.util.Scanner;
//Class name
class programfive{
//Main method
public static void main (String[]args){
//declaring and inizialising scanner
Scanner input = new Scanner (System.in);
//Declaring and inizialising variables
int userInput = 0;
int sum = 0;
//Array initializer
int array[] = new int [201];
//Prompt for user input
System.out.print("Please enter a value between 1 and 200: ");
userInput = input.nextInt();
//For loop - starts at number user inputted, stops when reaches 200, increments by 1.
for (int i = userInput; i<=200; i++)
{
sum += array[i];
}
System.out.println(sum);
}//End of main method
}//End of class
Because you haven't put anything in your array, it contains the default int value at each index, and that is 0 .
You have to fill it with the values you want, so that array[0] contains 0, array[1] contains 1, etc..
int array[] = new int [201];
for(int i=0; i<array.length;i++)
array[i] = i;
Also, you could get rid of the array and get the same result :
for (int i = userInput; i<=200; i++)
{
sum += i;
}
you need to initialize the array first, or changing the sum loop to:
for (int i = userInput; i<=200; i++)
{
sum += i;
}
Untested but should work:
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
int userInput = 0;
int sum = 0;
System.out.print("Please enter a value between 1 and 200: ");
userInput = input.nextInt();
for (int i = userInput; i<=200; i++)
sum += i
userInput.close();
System.out.println(sum);
}
you forgot to populate your array with numbers currently all of your array elements are pointing to the default value of 0.
add this line of code after the array declaration and your good to go:
for(int i=0;i<array.length;i++)
array[i]=i;
System.out.println("Enter five numbers: ");
Scanner scanner = new Scanner(System.in);
int[] array = new int [5] ;
for (int i =0; i < array.length; i++){
array[i] = scanner.nextInt();
}
int sum = 0;
for (int i : array){
sum = sum +i;
}
System.out.println(sum);
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]);
}