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);
}
}
Related
I want to have an ArrayList that records user entries and ends when it receives a non-integer value but I am getting an infinite loop and I don't know why.
public class Tryout1
{
public static void main(String[] args)
{
ArrayList entries = new ArrayList();
Scanner obj1 = new Scanner(System.in);
System.out.println("enter numbers");
int i = obj1.nextInt();
boolean accumulating = obj1.hasNextInt(); //check int
while(accumulating) {
entries.add(i);
}
System.out.println(entries);
}
}
you should move your check inside the loop, so it will check every time before the next loop is executed.
In your code, the check is only performed once.
public class tryout1 {
public static void main(String[] args) {
ArrayList entries = new ArrayList();
Scanner obj1 = new Scanner(System.in);
System.out.println("enter numbers");
do {
// get the next int
int i = obj1.nextInt();
entries.add(i);
} while (obj1.hasNextInt()); // <- check here for nextInt
System.out.println(entries);
}
}
I was given a assignment for my Intro to Computer Science class to make the user enter any word until they guess the secret word, once they get the secret word then the system will say "Stop!" So far I have the user trying once and I want the program to continue looping until the user enters the right word. I really need some help, this is what I have so far.
import java.util.Scanner;
public class HW2
{
public static void main(String[] args)
{
String input; //The users input
// New Scanner for keyboard input
Scanner keyboard = new Scanner(System.in);
//Tell the user to guess the word
System.out.print("Guess the secret word: ");
input = keyboard.nextLine();
if(input.equalsIgnoreCase("college"))
{
System.out.print("Stop !");
}
}
}
All you need is a do-while loop.
import java.util.Scanner;
public class HW2
{
public static void main(String[] args)
{
String input; //The users input
boolean hasGuessedCorrectly = false;
// New Scanner for keyboard input
Scanner keyboard = new Scanner(System.in);
//Tell the user to guess the word
do
{
System.out.print("Guess the secret word: ");
input = keyboard.nextLine();
if (input.equalsIgnoreCase("college"))
{
hasGuessedCorrectly = true;
System.out.print("Stop !");
}
} while (!hasGuessedCorrectly);
}
}
A do-while loop could be used for this task:
import java.util.Scanner;
public class Main {
private static final String SECRET_WORD = "college";
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Guess the secret word: ");
} while (!SECRET_WORD.equalsIgnoreCase(keyboard.nextLine()));
System.out.println("Stop!");
}
}
Live demo
Consider the while loop:
import java.util.Scanner;
public class HW2
{
public static void main(String[] args)
{
String input = ""; //The users input
// New Scanner for keyboard input
Scanner keyboard = new Scanner(System.in);
// The below code is run until the secret word is guessed.
while (!"college".equalsIgnoreCase(input))
{
//Tell the user to guess the word
System.out.print("Guess the secret word: ");
input = keyboard.nextLine();
/* if(input.equalsIgnoreCase("college"))
{
System.out.print("Stop !");
} This code is no longer necessary, as we have put the stop
condition in the while loop declaration. */
}
// This only runs after the loop has finished
System.out.println("Stop !");
}
}
I want to create a string ArrayList with input coming from user but inputs going to endless. How to stop it when user want.
public class SortingString {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
System.out.println("Enter the words:");
while (in.hasNext()) {
words.add(in.nextLine());
}
Collections.sort(words);
}
Edit: Thanks for all answers guys. It's working now.
What about?
public class SortingString {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
while (in.hasNext()) {
System.out.println("Enter the word:");
words.add(in.nextLine());
System.out.println("Do you want to continue? (y/n)");
in.hasNext();
if (!in.nextLine().equalsIgnoreCase("y")) {
break;
}
}
Collections.sort(words);
in.close(); // Don't forget to close the stream !!
}
}
A more elegant way: (EDIT Posted full code)
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
System.out.println("Enter the words or write STOP to exit:");
while (in.hasNext()) {
String inputLine = in.nextLine();
if (inputLine.equalsIgnoreCase("STOP")) {
break;
}
words.add(inputLine);
}
Collections.sort(words);
System.out.println("The words sorted:");
System.out.println(words);
in.close(); // Don't forget to close the stream !!
}
This would be a possible solution, where the "quit" word is not added to the words list.
public class SortingString {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
System.out.println("Enter the words:");
boolean isFinished = false;
while (!isFinished && in.hasNext()) {
String word = in.nextLine();
if ("q".equals(word)) {
isFinished = true;
} else {
words.add(word);
}
}
in.close();
Collections.sort(words);
}
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+" ");
}
}
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());
}
}
}