User input to populate an array one value at a time JAVA - java

I am trying to figure out how to take input from a user and store it into an array. I cannot use an arrayList (the easy way lol) but rather a standard array[5]. I have looked on here and on google and because of the sheer amount of questions and responses I have yet to find a good answer. Using scanner to get input is not a problem. Storing the input in an array is not the problem. What i am having trouble with is that I need to store one input at a time.
Currently I was using a for loop to gather information but it wants to gather the entire array at once.
for (int i=0;i<5;i++)
array[i] = input.nextInt();
for (int i=0;i<array.length;i++)
System.out.println(array[i]+" ");
I have been messing around with it, but if i remove the first for loop, im not sure what to put in the array[] brackets. BlueJ just says that "array[] is not a statement"
How can I accept just one value at a time and let the user determine if they want to do the next?
This is for a homework assignment, but the homework assignment is about creating a console with commands of strings and this is a concept that i need to understand to complete the rest of the project which is working fine.

boolean c = true;
Scanner sc=new Scanner(System.in);
int arr[] = new int[5];
int i =0;
int y = 1;
while(c){
System.out.println("Enter "+i+" index of array: ");
arr[i]=sc.nextInt();
i++;
System.out.println("Want to enter more if yes press 1 or press 2 ");
y = sc.nextInt();
if(y==1)c=true;
else c=false;
}

Use this as a reference implementation. General pointers on how a simple console program can be designed. I'm using JDK 6 at the moment. If you're on JDK 7 you can use switch case with strings instead of the if-else.
public class Stack {
int[] stack; // holds our list
int MAX_SIZE, size; /* size helps us print the current list avoiding to
print zer0es & the ints deleted from the list */
public Stack(int i) {
MAX_SIZE = i; // max size makes the length configurable
stack = new int[MAX_SIZE]; // intialize the list with zer0es
}
public static void main(String[] args) throws IOException {
new Stack(2).run(); // list of max length 2
}
private void run() {
Scanner scanner = new Scanner(System.in);
// enter an infinite loop
while (true) {
showMenu(); // show the menu/prompt after every operation
// scan user response; expect a 2nd parameter after a space " "
String[] resp = scanner.nextLine().split(" "); // like "add <n>"
// split the response so that resp[0] = add|list|delete|exit etc.
System.out.println(); // and resp[1] = <n> if provided
// process "add <n>"; check that "<n>" is provided
if ("add".equals(resp[0]) && resp.length == 2) {
if (size >= MAX_SIZE) { // if the list is full
System.out.print("Sorry, the list is full! ");
printList(); // print the list
continue; // skip the rest and show menu again
}
// throws exception if not an int; handle it
// if the list is NOT full; save resp[1] = <n>
// as int at "stack[size]" and do "size = size + 1"
stack[size++] = Integer.parseInt(resp[1]);
printList(); // print the list
// process "list"
} else if ("list".equals(resp[0])) {
printList(); // print the list
// process "delete"
} else if ("delete".equals(resp[0])) {
if (size == 0) { // if the list is empty
System.out.println("List is already empty!\n");
continue; // skip the rest and show menu again
}
// if the list is NOT empty just reduce the
size--; // size by 1 to delete the last element
printList(); // print the list
// process "exit"
} else if ("exit".equals(resp[0])) {
break; // from the loop; program ends
// if user types anything else
} else {
System.out.println("Invalid command!\n");
}
}
}
private void printList() {
System.out.print("List: {"); // print list prefix
// print only if any ints entered by user
if (size > 0) { // are available i.e. size > 0
int i = 0;
for (; i < size - 1; i++) {
System.out.print(stack[i] + ",");
}
System.out.print(stack[i]);
}
System.out.println("}\n"); // print list suffix
}
private void showMenu() {
System.out.println("Enter one of the following commands:");
// Check String#format() docs for how "%" format specifiers work
System.out.printf(" %-8s: %s\n", "add <n>", "to add n to the list");
System.out.printf(" %-8s: %s\n", "delete", "to delete the last number");
System.out.printf(" %-8s: %s\n", "list", "to list all the numbers");
System.out.printf(" %-8s: %s\n", "exit", "to terminate the program");
System.out.print("$ "); // acts as command prompt
}
}
Sample Run :
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ list
List: {}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ add 1
List: {1}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ add 2
List: {1,2}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ add 3
Sorry, the list is full! List: {1,2}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ delete
List: {1}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ delete
List: {}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ delete
List is already empty!
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ exit
(Truth be told: I was getting bored. So, I wrote it and thought might as well post it then.)

How about this way?
Scanner sc=new Scanner(System.in);
int[] arr=new int[5];
int i=0;
while (i<arr.length){
System.out.println("Enter "+i+" index of array: ");
arr[i]=sc.nextInt();
i++;
}

Related

In IntelliJ IDEA, while taking input in an array from console, character of enter key is accepted as an element

I was seeing an example of linear search in an array in Java, and I wrote this code:
import java.util.*;
public class LinearSearch
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter no. of members: ");
int l=sc.nextInt();
String[] list=new String[l];
System.out.println("Enter the members: ");
for(int i=0;i<l;i++)
list[i]=sc.nextLine();
System.out.print("\nEnter the member you want to search for: ");
String ts=sc.nextLine();
for(int i=0;i<l;i++)
{
if(list[i].equalsIgnoreCase(ts))
{
System.out.println("The member is at index " + i);
break;
}
if(i==l-1)
System.out.println("There is no such member");
}
}
}
But while running this code, due to the System.out.println() at the 10th line, the carriage return (of the println() ) is taken as the element at index 0. Further, as I enter more elements, after each element I need to press Enter key to start the next iteration, but with that, the carriage return of the Enter key is taken as input too. This is the output:
Enter no. of members: 5
Enter the members:
a
b
c
Enter the member you want to search for: e
There is no such member
I did the following to prevent it:
System.out.println("Enter the members: ");
int j=0;
String in="";
while(list[l-1]==null)
{
in=sc.nextLine();
if(in.equals(String.valueOf((char)10))) //10 being the ASCII code of carriage return
continue;
else
{
list[j] = in;
j++;
}
}
But this doesn't work, it still takes carriage return as an element. Is there any way to fix this issue ?
You need to skip line after nextInt() call as in the answer mentioned by #user16320675 in the comment
But, there is another bug in Intellij IDEA console, refer answer which kind of skips alternative nextLine() input. Hence, your call ends even when you just enter 3 values in this case but your array size is 5.
Refer
Your program is still correct. Just test your code in other terminal instead of IDEA console

Adding user input in Arraylist

I am new to JAVA and this is what I have to do:
Accept a set of marks (out of 100). The user should press the Enter button after each mark is entered and the mark should then be added to an ArrayList of Integers.
This is what I have so far:
int score = Integer.parseInt(marksinput.getText());
ArrayList<Integer> marks = new ArrayList();
Collections.addAll(marks, score);
String out = "";
String Out = null;
int[] studentmarks = {score};
for (int item : studentmarks) {
marksoutput.setText(""+item);
}
if (score > 100) {
marksoutput.setText("Enter marks\n out of 100");
}
This only adds one mark in the arraylist and I need user to input as many marks he wants. I know that my arraylist is wrong, which is why it only takes 1 number but I do not know how to make all the input numbers go in arraylist. What I have is that it takes the number and if user inputs another number, it just replaces the older number. I want it to display both the numbers not just one. Any help is appreciated and thank you in advance!☻☻
(This is not a duplicate even though others have the same title)
In case what you are after is a program that adds any integer typed by the user into an ArrayList, what you would have to do is the following:
Scanner scanner = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
while(true)
ints.add(scanner.nextInt());
What this program will do, is let the user input any number and automatically puts it into an ArrayList for the user. These integers can then be accessed by using the get method from the ArrayList, like so:
ints.get(0);
Where the zero in the above code sample, indicates the index in the ArrayList from where you would like to retrieve an integer.
Since this website is not there to help people write entire programs, this is the very basics of the ArrayList I have given you.
The ArrayList is a subclass of List, which is why we can define the variable using List. The while loop in the above example will keep on going forever unless you add some logic to it. Should you want it to end after executing a certain amount of times, I would recommend using a for loop rather than a while loop.
Best regards,
Since it seems you are really new,
What you are looking for is a for-loop
From the Java documentation, he is the syntax of a for-loop in Java
for (initialization; termination; increment) {
statement(s)
}
Initialization: Obviously you want to start from 0
Termination: you want to stop after 100 inputs, so that's 99 (starting from zero)
Increment: you want to "count" one by one so count++
for(int counter = 0; counter < 100; counter++) {
//Ask user for input
//read and add to the ArrayList
}
So before you enter the for-loop you need to initialize the ArrayList, and a Scanner to read input:
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
for(int counter=0; counter < 100; counter++) {
System.out.println("please enter the " + counter + " number");
int x = sc.nextInt();
list.add(x);
}

Increase Array Size Based on Total Numbers Entered

I have an issue for creating an array based on the total amount of numbers entered into the array.
Essentially the program is expected to work as the following: the user is prompted for n numbers to enter into an array. So until the user types '000' as their input, the user will be prompted for a new number.
Note: for this array, I do not want the user to input the amount of numbers they want to enter for the array size. Instead, I want the user to continue inputting random numbers until '000' has been inputted, then, the total amount of numbers that has been entered into the array, is the size of such array.
For example: this would work if we have int array[] = {1, 2, 4, 6}, this will automatically set array size to 4, without actually explicitly declaring the array size as 4 elements. Similarly, with my code, I want it where the numbers that the user enters is added to the array, and then the array size is automatically given from the amount of numbers the user has entered like above.
It is important to note that we do not know the length of the array until the user has entered all n numbers.
I have attempted a skeleton, but it returns a cannot find symbol error:
Code:
//Array Code
import java.util.*;
class setArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int stopInput = 000;
int number;
System.out.print("Enter a number: ");
number = input.nextInt();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
int array[] = {number};
}
System.out.print("Array size: " + array.length);
} // Main brace
} // Class brace
setArray.java:19: error: cannot find symbol
System.out.print("Array Size: " + array.length);
symbol: variable array
location: class setArray
1 error
You have a few errors here. The first is understanding why you get your immediate error. The variable array is declared within the scope of the while loop. It can not be seen outside of this loop. That is why the compiler is complaining.
The second is that the size of the array (if declared outside of the loop) will always be 1. From my understanding of what you have written as an attempt to solve the problem you have describe shows that you are not tackling the problem correctly.
While you don't known the the final length of the array to be entered; you do need to store the values entered (my inference) to populate the final array. To store the value entered by the user you need a list that will grow with the input.
List<Integer> values = new ArrayList<>();
while (number != stopInput) {
System.out.print("Enter a number: ");
values.add(Integer.valueOf(input.nextInt()));
}
Integer[] array = values.toArray(new Integer[values.size()]);
Firstly, the compilation error is because the array variable is not visible from the System.out.println line. This is because it's declared inside the while loop, so is only visible inside the while loop.
To make it visible to the whole method, declare it before the while loop.
Secondly, arrays cannot be resized. You declare an array to be a certain size, and you cannot add or remove elements.
My suggestion would be to use an ArrayList. Declare one before your loop, and add the new number inside the loop. After the loop, the size should be how many numbers were entered.
Finally, there's no difference between 000 and 0. Is 0 a valid input number?
You can use
List<Integer> array=new ArrayList<Integer>();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
array.add(number);
}
This sounds like a job for java.util.ArrayList - this is the array that doesn't have a fixed size and is growing as you add values to it automatically under the covers.
The error is caused because you are creating the array only within the scope of the while loop. You need to create it outside the loop. Secondly, standard arrays are not dynamic, so you would need to either set the size and increase it as needed, or just simply use an ArrayList.
Psuedo:
ArrayList<Integer> list = new ArrayList<Integer>()
...
while(not stop number)
list.add(number)
...
print(list.size())
If you really want to use an Array, here is how you can do it
public static void main(String[] args){
STOP_ENTRY = "000";
scan = new Scanner(System.in);
entry = "";
while(true){
System.out.print("Enter #: ");
String tempS = scan.nextLine();
if(tempS.equals(STOP_ENTRY)) break;
else entry += tempS + ":";
}
String[] split = entry.split(":");
int[] intArray = new int[split.length];
System.out.println("Length of created intArray = " + intArray.length); //length of created array
for(int i = 0; i < intArray.length; i++){
intArray[i] = Integer.parseInt(split[i]);
System.out.println("intArray[" + i + "] => " + String.valueOf(intArray[i]));
}
}
I would recommend an ArrayList, as it dynamically changes is size when you add an element, but do whatever you'd like.
An important note, this does not handle any malicious entry that you might not want (characters, symbols), and will error if they are entered, something you can easily add if you need

Using variables with parseInt in Java

So i'm supposed to collect data from user inputs for a game
int[] player1 = new int[4];
try {
player1[4] = Integer.parseInt(keyin.nextLine());
}
catch(NumberFormatException e) {
System.out.println("Player 2 : "); }
The try-catch is to skip to the next player when player1 presses Enter, but the problem I'm getting is I can't seem to find a way to use the variables the player1 has inputted. I need those values to compare with another, but using int player1[0] does not work.
Where can I find the values the person has entered?
An example of the program running:
Player 1: 12 1 5 // these numbers are user inputted
Player 2: 12 4 3
[...]
You need to setup a loop to both read in the inputs, as well as to display those inputs.
Your code below does not work; you are trying to access data that is beyond the bounds of your array.
player1[4] = Integer.parseInt(keyin.nextLine());
If you declare you array like this: int[] player1 = new int[4];
Then you have the following indexes to use:
| 0 | 1 | 2 | 3 |` //This gives you 4 indexes! But player1[3] is the last usable index
Remember that when you are trying to access elements of arrays or any element in programming, computers begin numbering at zero! Any attempt to access data beyond this can result in undesired behavior, casuing the program to terminate abruptly.
I encourage you to examine the following resources:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
http://www.tutorialspoint.com/java/java_loop_control.htm
http://www.programmingsimplified.com/java/tutorial/java-while-loop
Scanner input = new Scanner(System.in);
System.out.println("Input an integer");
while ((n = input.nextInt()) != 0) {
System.out.println("You entered " + n);
System.out.println("Input an integer");
}
System.out.println("Out of loop");
}
String string = keyin.nextLine();
String[] parts = string.split("[ ]+");
Then check the size of parts and loop through that.

Retrieves and display endless amount of numbers in an array

I"m trying to make a program that retrieves an endless amount of numbers that user inputs until the user quits and display the numbers .Here is the code I have so far.After entering the first and second number it shows an exception at the line array1[i]=s1
import java.util.Scanner;
public class Program_2 {
public static void main(String[] args) {
int a=1,i;
Scanner sn = new Scanner(System.in);
String[] array1= new String[a];
for(i=0;i<a;i++)
{
System.out.println("Enter Value Number "+ (i+1));
System.out.println("Press Q or q to Exit");
String s1=sn.next();
if(s1.equalsIgnoreCase("q"))
{
for(i=0;i<a;i++)
{
System.out.println("Value of Number "+(i+1)+" is "+ array1[i]);
}
a=0;
}
else
{
array1[i]=s1;
a=(i+2);
}
}
}
}
Your array is of size 1 (a is 1 at the beginning of your code).
The first input works because i is 0 and array1[0] exists. The second input crashes because array1[1] does not exist.
You need to increase your array. That can be done by copying the array into a larger one and using the result of the copy, but that is clumsy.
Better way to do it is to use an ArrayList instead of a simple array and you do not have to worry about the size as it is managed automatically.
For one, a is only incremented when they press q, when you go to the else statement. So the the for loop is going to end after a couple of iterations.
You also set a to 0 in the inside for loop, making sure it won't run more.
Also, your quit code doesn't quit.

Categories