I am trying to use user input in an arraylist - java

I was going all over the internet looking for something to help me with this problem. I learned how to make an arrayList, but i want to know how to make it acceptable user input. What i mean by that is that i want the user to input his number.
Here is what i have:
public class MyClass {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
ArrayList<Integer> myList=new ArrayList<Integer>(10);
System.out.println("Enter your number:");
myList.add(416355);
myList.add(21212);
for(int x : myList)
System.out.println(x);
System.out.println("Size="+myList.size());
}
}
What i have now is the numbers i have put in there. Any help is greatly appreciated.
Thanks in advance.

These two lines of code are necessary to get the user input into the ArrayList:
int n = input.nextInt();
myList.add(n);
So the full code would read:
public class MyClass {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
ArrayList<Integer> myList=new ArrayList<Integer>(10);
System.out.println("Enter your number:");
int n = input.nextInt();
myList.add(n);
myList.add(416355);
myList.add(21212);
for(int x : myList)
System.out.println(x);
System.out.println("Size="+myList.size());
}
}
You might find this helpful: How can I get the user input in Java?

public class MyClass {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
ArrayList<Integer> myList=new ArrayList<Integer>(10);
System.out.println("Enter your number:");
int totalNumbers = 2;
for (int i = 0; i < totalNumber; i++) {
myList.add(input.nextInt());
}
for(int x : myList)
System.out.println(x);
System.out.println("Size="+myList.size());
}
}

import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> myList = new ArrayList<Integer>(10);
int totalNumbers = 10;
for (int i = 0; i < totalNumbers; i++) {
System.out.println("ENTER Element to add into list");
Scanner element = new Scanner(System.in);
int ele = (element .nextInt());
myList.add(ele);
}
for (int x : myList)
System.out.println(x);
System.out.println("Size=" + myList.size());
}
}
So the full code would read:

As I understood you want to capture user data and save it into an array;for each input element you need to create a variable:
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
ArrayList<Integer> myList=new ArrayList<Integer>(10); enter code here
System.out.println("Enter your number:");
Scanner input=new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
myList.add(a);
myList.add(b);
for(int x : myList)
System.out.println(x);
System.out.println("Size="+myList.size());
}
}

import java.util.ArrayList;
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
ArrayList<Double> numbers = new ArrayList<Double>();
Scanner in = new Scanner(System.in);
System.out.println("Please enter a list of numbers: ");
while (in.hasNextDouble())
{
double input = in.nextDouble();
numbers.add(input);
}
if (numbers.size() == 0)
{
System.out.println("No average.");
}
else
{
double total = 0;
for (double element : numbers)
{
total = total + element;
}
double average = total / numbers.size();
System.out.println("The average is: " + average);
}
}

Related

read multiple inputs from same line in java

Here is my code snippet
public void m1(int a) // a value passed from main
{
for(int i=0;i<a;i++)
{
// Read "a" inputs from the user one by one
}
}
public static void main(String[] args)
{
int a;
// read value of a from user
m1(a)
}
Can U please tell me how to give this input in one line.
Like in the same line we need to provide the value of a and also should take a values from user.
eg:enter code here
a=6. 6 values from user
6 22 33 44 55 66
6 and the 6 inputs from the user should be in the same line (given by the user at the same time).
You could go this way:
public class Number {
static Scanner sc = new Scanner(System.in);
static int arr[];
public static void read(int a)
{
arr = new int[a];
for (int i = 0; i < a; i++) {
arr[i] = sc.nextInt();
}
}
public static void main(String args[]) {
System.out.print("Enter numbers here : ");
int a = sc.nextInt();
read(a);
// printing the array
for (int i = 0; i < a; i++) {
System.out.print(arr[i]+" ");
}
System.out.println("");
}
}
But better and cleaner way will be returning the array from read method:
public class Number {
static Scanner sc = new Scanner(System.in);
public static int[] read(int a)
{
int arr[] = new int[a];
for (int i = 0; i < a; i++) {
arr[i] = sc.nextInt();
}
return arr;
}
public static void main(String args[]) {
System.out.print("Enter numbers here : ");
int a = sc.nextInt();
int numbers[] = read(a);
// printing the numbers array
for (int i = 0; i < a; i++) {
System.out.print(numbers[i]+" ");
}
System.out.println("");
}
}
Input:
Enter numbers here : 4 1 2 3 4
Output:
1 2 3 4
Solve that your problem? I haven't understand exactly what you want, but with this you can do anything, or not?
public static void m1(String[] a) // a value passed from main
{
for (int i = 1; i < a.length; i++) {
// Read "a" inputs from the user one by one
System.out.println(a[i]);
}
}
public static void main(String[] args) {
m1(args);
}
public static void m1(int a) // a value passed from main
{
Scanner scan = new Scanner(System.in);
int arr[] = new int[a];
for(int i=0;i<a;i++)
{
arr[i]=scan.nextInt();
}
}
public static void main(String[] args)
{
int a=(int) 6.6;
// read value of a from user
m1(a);
}
Input:
1 -2 "nonumber" 34
Output:
1
-2
34
Code:
String line = scanner.nextLine();
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(line);
while (m.find()) {
System.out.println(m.group());
}
First, a couple of quick pointers:
- Name your methods something more practical than m1()
- Make sure you end your statements with a semi-colon ( e.g m1() )
- You need to define m1() as static, or otherwise instantiate the class which contains m1()
- Learn about Scanners and Arrays; you must import a library to use a Scanner object. ( import java.util.Scanner; )
public static void storeIntegers(int a){
//This is how you declare an array.
int[] someIntArray = new int[a];
//You must create a Scanner object to take in user input.
Scanner userInput = new Scanner(System.in);
for(int i = 0; i < a; i++){
someIntArray[i] = userInput.nextInt();
}
// Just to make sure it worked.
for(int e = 0; e < someIntArray.length; e++){
System.out.println(someIntArray[e]);
}
}// End storeIntegers()
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
System.out.println("How many numbers?");
int a = userInput.nextInt();
storeIntegers(a);
}// End main()

ArrayIndexOutOfBoundsException exception which I just cant figure out

I simply cant figure out why I keep getting an indexoutofboundserror. I believe its pop up in the line
profits[i] = storeDays
The code is:
import java.util.Arrays;
import java.util.Scanner;
class Business
{
public static void main(String[] args) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("Welcome to the profit-calculation program.");
System.out.println("how many days of data do you have?");
int n = Integer.parseInt (inputScanner.nextLine());
//call upon a function to store the profits into an array for further use.
double[] dayProfitList = inputProfit(n);
//call upon a function to calculate average profit and its standard devation
//calcAverageProfit(dayProfitList);
}
public static double[] inputProfit(int days) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("input the profit on..");
double[] profits = new double [days];
for(int i = 1; i<days +1; i++) {
System.out.println("day " + i + "?");
double storedDays = Double.parseDouble(inputScan ner.nextLine());
profits[i] = storedDays;
}
return profits;
}
}
Arrays are enumarated from 0 so the first element of it is profits[0], next one is profits[1] and so on.
You are trying to reach an index that does not exist here:
for(int i = 1; i<days +1; i++) {
...
It actually should be
for(int i = 0; i<days; i++) {
...

How do I enter values from a loop into an array list?

this is my code:
public static void main(String[] args) {
System.out.println("Please enter the number of values you would like to enter: ");
Scanner scan = new Scanner(System.in);
int intNumberOfNumbers = scan.nextInt();
for (int i = 0; i < intNumberOfNumbers; i++) {
System.out.println("Please enter a value for index " + i + ":");
int intValue = scan.nextInt();
}
}
What I'm trying to do is create a scanner that asks how many values they want to enter and whatever that value is, that's how many times it asks for number input. The problem is after I ask the question how can I add the number to an array list?
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int numOfInput=sc.nextInt();
ArrayList<Integer> array=new ArrayList<Integer>();
while(numOfInput-->0){
array.add(sc.nextInt());
}
}
public static void main(String[] args) {
System.out.println("Please enter the number of values you would like to enter: ");
Scanner scan = new Scanner(System.in);
int intNumberOfNumbers = scan.nextInt();
ArrayList<Integer> myArray= new ArrayList<>();
for (int i = 0; i < intNumberOfNumbers; i++) {
System.out.println("Please enter a value for index " + i + ":");
int intValue = scan.nextInt();
myArray.add(intValue);
}
}

Add Problems In java

I want to take input of two variable as integer and than do addition with the two variables.
The ans will stored in another variable. The program will repeat after every addition end and will ask for user input of varibles and will do addition again.
My qus is taht how can i add all aditions ans again:
Exm:
Input a= 5
Input b=5
ans=10
Agin program will ask for
Input a= 6
Input b= 6
ans=12
now how can i take all " ans " value with program and do additions of all "ans"
Final Ans=10+12=22
code:
import java.io.*;
import java.util.Scanner;
public class math{
public void add()
{
Scanner keyboard = new Scanner(System.in);
int a;
int b;
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c=a+b;
System.out.println("\nans is :"+c);
math ob_m=new math();
ob_m.add();
}
public static void main(String args[])
{
math ob_main=new math();
ob_main.add();
}
}
The code just do addition one after another but i want that it will do one more task that ....
It all add all aditions reasuts also. how can i do it?
import java.io.*;
import java.util.Scanner;
public class Test {
int a;
int b;
int sum = 0;
public void add() {
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
sum = sum + (a + b);
System.out.println("\nans is :" + (a + b));
}
public static void main(String args[]) {
Test ob_main = new Test();
while (true) {
ob_main.add();
}
}
}
Just keep adding the intermediate sums to another variable, so at the end you get the final total.
Another alternative (though not preferable when simple solution is available) is to put these sums in a list and at the end iterate through the list and calculate the final total.
Also, do not use ob_m.add(); - just call add();
Store every answer in an additional variable. Then when you're done, sum all the answer variables
You can use a loop for repeating your action, and store each addition in a total sum?
Change
public void add() {
Scanner keyboard = new Scanner(System.in);
int a;
int b;
int total = 0;
for(int i = 0; i < 2; i++) {
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c = a+b;
total += c;
}
System.out.println("\nans is :"+total);
}
Have a total variable which you just keep adding c to.
I also changed your unneeded recursion into a while-loop.
public class math
{
public static void main(String args[])
{
int total = 0;
Scanner keyboard = new Scanner(System.in);
while (true)
{
System.out.print("\nEnter a (-999 to quit): ");
int a = keyboard.nextInt();
// terminating condition, modify appropriately
if (a == -999)
break; // break out of the while-loop
System.out.print("Enter b: ");
int b = keyboard.nextInt();
int c = a + b;
total += c;
System.out.println("\nans is: " + c);
}
System.out.println("total is: " + total);
}
}
have a field GrandSUM,
GrandSum = 0;
and after every addition, add ans to it.
GrandSum += ans;
at the end , GrandSum will have result you want.
Edit:
import java.io.*;
import java.util.Scanner;
public class math{
int GrandSum = 0;//added
public void add()
{
Scanner keyboard = new Scanner(System.in);
int a;
int b;
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c=a+b;
GrandSum += c;//added
System.out.println("\nans is :"+c);
}
public static void main(String args[])
{
math ob_main=new math();
ob_main.add();
//.....repeat as many times you want
ob_main.add();
System.out.println("grandsum: " + ob_main.GrandSum);
}
}
package farzi;
import java.util.ArrayList;
import java.util.Scanner;
public class dummy {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
ArrayList<Integer> sum = new ArrayList<Integer>();
String choice = "";
do{
System.out.println("enter the first number");
int a = keyboard.nextInt();
System.out.println("enter the second number");
int b = keyboard.nextInt();
int tempSum = a+b;
list1.add(a);
list2.add(b);
sum.add(tempSum);
System.out.println("Do you want to continue : type yes or no");
choice = keyboard.next();
}while(choice.toLowerCase().charAt(0)=='y');
System.out.println("here are the inputs with theri sum");
System.out.println("num1\t num2\t sum");
for(int i=0;i<list1.size();i++)
{
System.out.println(list1.get(i)+"\t"+list2.get(i)+"\t"+sum.get(i));
}
}
}

How to put a Scanner input into an array... for example a couple of numbers

Scanner scan = new Scanner(System.in);
double numbers = scan.nextDouble();
double[] avg =..????
You could try something like this:
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[5];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
}
It seems pretty basic stuff unless I am misunderstanding you
You can get all the doubles with this code:
List<Double> numbers = new ArrayList<Double>();
while (scan.hasNextDouble()) {
numbers.add(scan.nextDouble());
}
import java.util.Scanner;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
Scanner in=new Scanner (System.in);
int num[]=new int[10];
int average=0;
int i=0;
int sum=0;
for (i=0;i<num.length;i++) {
System.out.println("enter a number");
num[i]=in.nextInt();
sum=sum+num[i];
}
average=sum/10;
System.out.println("Average="+average);
}
}
**Simple solution**
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size;
System.out.println("Enter the number of size of array");
size = sc.nextInt();
int[] a = new int[size];
System.out.println("Enter the array element");
//For reading the element
for(int i=0;i<size;i++) {
a[i] = sc.nextInt();
}
//For print the array element
for(int i : a) {
System.out.print(i+" ,");
}
}
For the values of the array given by separated with space " " you can try this cool one liner Java 8 & onwards suppported streams based solution:
Scanner scan = new Scanner(System.in);
double[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToDouble(Double::parseDouble)
.toArray();
For int array you can try:
Scanner scan = new Scanner(System.in);
int[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToInt(Integer::parseInt)
.toArray();
With filter() method you can also avoid more than one spaces in between the inputs.
Complete code reference:
import java.util.Scanner;
import java.util.Arrays;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double[] arr = Arrays.stream(scan.nextLine()
.trim()
.split(" "))
.filter(x -> !x.equals(""))
.mapToDouble(Double::parseDouble)
.toArray();
for(double each: arr){
System.out.print(each + " ");
}
}
}
Input: 1 2 3 4 5 6 7 8 9
Output: 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
If you observe carefully, there are extra spaces in between the input randomly, that has also been handled with line .filter(x -> !x.equals("")) so as to avoid blank inputs ("")
import java.util.Scanner;
class Array {
public static void main(String a[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
System.out.println("Enter the Element "+num+" of an Array");
double[] numbers = new double[num];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
for (int i = 0; i < numbers.length; i++)
{
if ( (i%3) !=0){
System.out.print("");
System.out.print(numbers[i]+"\t");
} else {
System.out.println("");
System.out.print(numbers[i]+"\t");
}
}
}
double [] avg = new double[5];
for(int i=0; i<5; i++)
avg[i] = scan.nextDouble();
This is a program to show how to give input from system and also calculate sum at each level and average.
package NumericTest;
import java.util.Scanner;
public class SumAvg {
public static void main(String[] args) {
int i,n;
System.out.println("Enter the number of inputs");
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
int a[] = new int [n];
System.out.println("Enter the inputs");
for(i=0;i<n;i++){
a[i] = sc.nextInt();
System.out.println("Inputs are " +a[i]);
}
int sum = 0;
for(i=0;i<n;i++){
sum = sum +a[i];
System.out.println("Sums : " +sum);
}
int avg ;
avg = sum/n;
System.out.println("avg : " +avg);
}
}
List<Double> numbers = new ArrayList<Double>();
double sum = 0;
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
double value = scan.nextDouble();
numbers.add(value);
sum += value;
}
double average = sum / numbers.size();
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Please enter size of an array");
int n=s.nextInt();
double arr[] = new double[n];
System.out.println("Please enter elements of array:");
for (int i=0; i<n; i++)
{
arr[i] = s.nextDouble();
}
}
If you don't know the size of the array, you need to define, when to stop reading the sequence (In the below example, program stops when the user introduces 0 and obviously, last zero shouldn't be taken into account).
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main (String[]args)
{
System.out.println("Introduce the sequence of numbers to store in array. Each of the introduced number should be separated by ENTER key. Once you're done, type in 0.");
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
boolean go = true;
while (go) {
int value = scanner.nextInt();
numbers.add(value);
if (value == 0) {
go = false;
numbers.remove(numbers.size() - 1);
}
}
System.out.println(numbers);
}
}
Scanner scan = new Scanner (System.in);
for (int i=0; i<=4, i++){
System.out.printf("Enter value at index"+i+" :");
anArray[i]=scan.nextInt();
}
import java.util.Scanner;
public class sort {
public static void main(String args[])
{
int i,n,t;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of array");
n=sc.nextInt();
int a[] = new int[n];
System.out.println("Enter elements in array");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
t=a[1];
for(i=0;i<n;i++)
{
if(a[i]>t)
t=a[i];
}
System.out.println("Greates integer is" +t);
}
}

Categories

Resources