Java scanner into a list - java

Unsuccessful to assign input numbers into a list, my code is as follows, which part was wrong?
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Please input numbers:");
Scanner input = new Scanner(System.in);
ArrayList<Double> list = new ArrayList<>();
while (input.hasNextDouble()) {
list.add(input.nextDouble());
}
for (p : list){
System.out.print(p);
}
input.close();
}
}

I think the variable 'p' cannot be resolved to a type, its type must be declared before used.
Maybe you can do like this:
for (Double p : list){
System.out.print(p);
}

Related

how to stop taking user inputs and print out arraylist

I am trying to create a program that takes user inputs stores them into an Arraylist and the prints the Arraylist out after user inputs a certain string. my current problem is that i cant get the user inputs to stop and print out. i think what i have currently have is a strong base, i cant see what is wrong.
import java.util.ArrayList;
import java.util.Scanner;
public class GroceryArraylist {
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter end to stop ");
while (!input.equals("end")) {
Grocerylist.add(input.next());
if (Grocerylist.equals("end")){
for(String str:Grocerylist)
System.out.println(str);
}
}
}
}
Here is the mistake:
Grocerylist.equals("end")
GroceryList is of type ArrayList and it will never be equal to the string "end". It's like comparing apples with oranges.
You could try this instead:
while (!input.equals("end")) {
String input = input.next();
Grocerylist.add(input);
if ("end".equals(input)){
for(String str:Grocerylist)
System.out.println(str);
}
break;
}
You can use hasNext command to avoid including "end" into the array.
public class GroceryArraylist {
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter \"end\" to stop ");
while (input.hasNext()) {
Grocerylist.add(input.next());
if(input.hasNext("end")) {
System.out.println(Grocerylist);
break;
}
}
}
}
Or you can use a do-while loop instead of:
public class GroceryArraylist{
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter \"end\" to stop ");
do {Grocerylist.add(input.next());}
while (!input.hasNext("end"));
System.out.println(Grocerylist);
System.exit(0);
}
}

How can I take the input and insert it into LINKED LIST in java?

I am trying to make a three different linked list. I will determine the first ones inputs but for the other two I want to ask the user for the inputs and then insert them into a linked list. Can anyone help me with how to do that? So far I could only write this code
package homework001;
import java.util.Scanner;
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
public class morph {
public static LinkedList<String> list;
public static void main(String[] args){
LinkedList<String> list = new LinkedList<>();
list.add("10");
list.add("34");
list.add("1");
list.add("97");
list.add("5");
list.add("62");
}
}
I think we can simply take user input in LinkedList by using
this method -> listname.add(sc.nextInt());
code for the implementation is below! thank you :)
public class LL_userInput {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<>(); //creating list
Scanner sc = new Scanner(System.in); //creating scanner for total elements to be inserted in list
System.out.println("enter total count of elements -> ");
int num = sc.nextInt(); // user will enter total elements
while(num>0) {
ll.add(sc.nextInt());
num--; // decrement till the index became 0
}
sc.close();
System.out.println(ll);
}
}
Using scanner, you can get input from any source. To read from console use
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()) sc.next();
int number = sc.nextInt();
for(i=0; i< number; i++)
myList.add(sc.next());
I think you don't understand from the comments here is a simple example ;
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();//declare your list
Scanner scan = new Scanner(System.in);//create a scanner
System.out.print("Enter the Nbr of element : ");
int nbr = scan.nextInt();//read the number of element
scan.nextLine();
do {
list.add(scan.nextLine());//read and insert into your list in one shot
nbr--;//decrement the index
} while (nbr > 0);//repeat until the index will be 0
scan.close();//close your scanner
System.out.println(list);//print your list
}
import java.util.*;
class LinkedList{
public static void main(String[] args) {
Scanner sc= new Scanner (System.in );
LinkedList<Integer>list=new
LinkedList<>();
System.out.println("Enter how many
elements you want");
int num=sc.nextInt();
for(int i=0;i<num;i++){
System.out.println("Enter element
at index "+i);
list.add(sc.nextInt());
}
System.out.print(list+" ");
}
}

Dynamically defined list

Hi I'm trying to make a simple program that prints out the elements
of a list.The catch is that the list should be dynamically initialized from
the console(the user must be able to input as much as elements he wants),and
then the program has to print on the console.
I wrote this code,but it's giving me some errors at line 13:
Error:
Multiple markers at this line
Syntax error on token "(", ; expected
void is an invalid type for the variable-"keyPressed"
Syntax error on token ")", ; expected
Code:
import java.util.ArrayList;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
public class test2 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
void keyPressed(KeyEvent e) {
for(Integer i = 0;i < list.size();i++){
i = (Integer) in.nextInt();
list.add(i);
if(e.getKeyCode() == KeyEvent.VK_ENTER){
System.out.println();
}
}
}
}
}
keyPressed method has to be defined outside the main method. Also, the body of your for loop won't be executed as the list is empty. You need to loop - "while" - until the user inputs the "KeyEvent.VK_ENTER" and then exit the loop and print the list.
Probably easier to do something like this instead of trying to capture each key press:
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
while(in.hasNextInt())
{
list.add(in.nextInt());
}
System.out.println("Invalid integer entered.");
System.out.println("List contents:");
for(int i : list)
{
System.out.print(i + " ");
}
}
}
Scanner in = new Scanner(System.in);
int nextInt = in.nextInt();
List<Integer> list = new ArrayList<>(nextInt);
for (int i = 0; i < nextInt; i++) {
list.add(in.nextInt());
}
for (Integer integer : list) {
System.out.println(integer);
}
code to store and print value of dynamic length of list with dynamic value input

while there is input from user

I'm new to java. In my program, I have the user enter the integers that are being added to an array list. I need to set up a while loop that will be something like this:
arrayList = new ArrayList<int>;
int i = scanner.nextInt();
while(there is input from user)
{
arrayList.add(i);
}
I expect the user to enter 5 values. What do I put as the condition statement of the while loop. In other words, how do I say "while there is input?" Thanks
Try something along the lines of
while(scanner.hasNextInt())
{
arrayList.add(i);
}
import java.util.Scanner;
import java.util.ArrayList;
public class A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList arrayList = new ArrayList<Integer>();
int input;
for (int i = 0; i < 5; i++)
{
input = scan.nextInt();
arrayList.add(input);
}
}
}
I tried below code and tested its working fine. let me know if u want another requirements.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<Integer>();
System.out.print("enter 5 numbers");
int counter=1;
while(scan.hasNextInt()){
int i=scan.nextInt();
arr.add(i);
counter++;
if(counter==5){
scan.close();
break;
}
}
}
}
I believe, you're currently accepted answer has a very fatal (it never updates i). What you need is something more like this -
// arrayList = new ArrayList<int>; // And arrayList isn't a great name. But I have
// no idea what they actually are. So
// just use a short name.
List<Integer> al = new ArrayList<Inteeger>(); // <-- Use the interface type?
// And, you have to use the wrapper type.
// int i = scanner.nextInt();
while (scanner.hasNextInt())
{
al.add(scanner.nextInt()); // You don't need `i`.
}

Java Arraylist to store user input

Hi I am new to arraylists and java and I was wondering if someone could help me or give me pointers on how to create a program that allows the user to repeatedly enter directory entries from the keyboard and store them in an arraylist.
enter name:
enter telephone number:
and then ask if the user wants to enter another one
enter another: Y/N
thanks
You can still use two ArrayLists, or make a class with name and phone attributes and then make one ArrayList of objects of that class.
First approach shown here.
import java.util.ArrayList;
import java.util.Scanner;
public class AAA {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Please enter your name: ");
name.add(sc.next());
System.out.println("Please enter your number: ");
phone.add(sc.nextInt());
}
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Tester {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> directoryNames= new ArrayList<String>();
String input=getDirectoryName();
String directoryPath="";
String userChoice="";
String[] inputTokens=input.split(" ");
if(inputTokens.length>1)
{
directoryPath=inputTokens[0];
userChoice=inputTokens[1];
}
else
{
directoryPath=inputTokens[0];
}
while(!"q".equalsIgnoreCase(userChoice))
{
directoryNames.add(directoryPath);
input=getDirectoryName();
inputTokens=input.split(" ");
if(inputTokens.length>1)
{
directoryPath=inputTokens[0];
userChoice=inputTokens[1];
}
else
{
directoryPath=inputTokens[0];
}
}
}
public static String getDirectoryName()
{
String input="";
System.out.println("Please Enter Directory name . If you want to quit press q or Q at the end of directory name \n ");
System.out.println("\n Example <directory_path> q");
Scanner in = new Scanner(System.in);
input=in.nextLine().trim();
return input;
}
}
It seems that you want to use a Map instead of an array list.
You want to use the .put(k,v) method to store your inputs.
Map newMap= new Map();
newmap.put(inputName,inputNum);
Link to Map API
import java.util.*;
class simple
{
public static void main(String args[])
{
ArrayList<String> al=new ArrayList<String>();
ArrayList<Integer> al1=new ArrayList<Integer>();
Scanner ac=new Scanner(System.in);
al.add(ac.next());
al1.add(ac.nextInt());
Iterator itr=al.iterator();
Iterator itr1=al1.iterator();
while(itr.hasNext()&& itr1.hasNext())
{
System.out.println(itr.next());
System.out.println(itr1.next());
}
}
}

Categories