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);
}
Related
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);
}
}
Ask user to enter word until they enter "exit", when they enter exit display all of their entered words without the "exit".
I'm confused how to combine all of their words and display it at the end, I know I will need another loop for that
import java.util.*;
public class testprac {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a word: ");
String word = input.nextLine();
if (word.equals("exit")) {
System.out.println("Exited");
System.out.println("You entered: ");
break;
}
}
}
}
You can use array or List to store the inputs and then loop through the list or array to print.You can also to toString() method to print.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<String> inputs = new ArrayList<>();
while (true) {
System.out.println("Enter a word: ");
String word = input.nextLine();
if (word.equals("exit")) {
System.out.println("Exited");
System.out.println("You entered: "+inputs);
break;
} else {
inputs.add(word);
}
}
}
}
This should work:
import java.util.*;
public class testprac {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner inputScanner = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
while (inputScanner.hasNextLine()) {
String line = inputScanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
String s = lineScanner.nextLine();
if (s.equalsIgnoreCase("exit")) {
System.out.println("Exited");
System.out.println("You entered: ");
System.out.println(sb.toString());
lineScanner.close();
System.exit(0);
} else {
sb.append(s);
}
}
}
inputScanner.close();
}
I'm trying to write a method for a school project for displaying a list of contacts from a text file. Only four contacts are supposed to display at a time and then re-entering "d" should display the next 4 until all have been displayed. Does anyone have any advice in how I could achieve this? Right now I just have it so it reads all of the lines of text.
import java.util.Scanner; import java.io.*;
public class Contacts
{
public static void main(String [] args) throws IOException
{
File aFile = new File("contacts.txt");
if (!aFile.exists())
System.out.println("Cannot find file");
else
{
Scanner in = new Scanner(aFile);
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
if (input.contains("d"))
{
String aLineFromFile;
while(in.hasNext())
{
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
}
in.close();
}
}
}
}
As MadProgrammer said, use a counter to track groups of 4.
else {
Scanner in = new Scanner(aFile);
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
while(input.contains("d")) {
int limit = 4;
String aLineFromFile;
while(in.hasNext() && limit > 0) {
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
limit--;
}
if(in.hasNext()) {
input = keyboard.nextLine();
}
else {
break;
}
}
}
My text file include:
Tom,Marry,Erick,Lok,Kevin,Ben,Sally
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner (new FileReader("name.txt"));
String Name;
Scanner in = new Scanner(System.in);
System.out.println("Enter a name:");
Name= in.nextLine();
String name = null;
while(sc.hasNext())
{
int i=0;
name= sc.next();
String [] Str=name.split(",");
if (Name.equals(Str[i]))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
if (i<Str.length)
{
i++;
}
}
i want to input a name, then display if in the text file or not. i tried many way, but still not work, help me please.
Your code will check only the first word means Tom in the String array. If you want to check each word of array use for loop. If you input Marry then it will compare with Tom so answer No.
while(sc.hasNext())
{
name= sc.next();
String [] Str=name.split(",");
for(String s: Str){
if (Name.equals(s))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}//for missed. otherwise it will check only the first word in the String array
}
Edit:
One more way to check
while(sc.hasNext())
{
name= sc.next(); //get each line from text file
String [] Str=name.split(",");
if(Arrays.asList(Str).contains(Name))//check whether Name contains or not
System.out.println("Yes");//If array contains the given input then Yes
else
System.out.println("No");//Otherwise No
}
Try this, it works
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner (new FileReader("name.txt"));
String Name;
Scanner in = new Scanner(System.in);
System.out.println("Enter a name:");
Name= in.nextLine();
String name = null;
name= sc.next();
String [] Str=name.split(",");
int flag=0;
for(String sd:Str)
{
if (Name.equals(sd))
{
flag=1;
break;
}
else
{
continue;
}
}
if(flag==1)
System.out.println("yes");
else
System.out.println("no");
}
}
I a newbie to java so please don't rate down if this sounds absolute dumb to you
ok how do I enter this using a single scanner object
5
hello how do you do
welcome to my world
6 7
for those of you who suggest
scannerobj.nextInt->nextLine->nextLine->nextInt->nextInt,,,
check it out, it does not work!!!
thanks
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Please specify how many lines you want to enter: ");
String[] input = new String[in.nextInt()];
in.nextLine(); //consuming the <enter> from input above
for (int i = 0; i < input.length; i++) {
input[i] = in.nextLine();
}
System.out.printf("\nYour input:\n");
for (String s : input) {
System.out.println(s);
}
}
Sample execution:
Please specify how many lines you want to enter: 3
Line1
Line2
Line3
Your input:
Line1
Line2
Line3
public class Sol{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
By default, the scanner uses space as a delimiter. In order to scan by lines using forEachRemaining, change the scanner delimiter to line as below.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
scanner.forEachRemaining(System.out::println);
}
try this code
Scanner in = new Scanner(System.in);
System.out.printf("xxxxxxxxxxxxxxx ");
String[] input = new String[in.nextInt()];
for (int i = 0; i < input.length; i++) {
input[i] = in.nextLine();
}
for (String s : input) {
System.out.println(s);
}
You can try only with lambda too:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.forEachRemaining(input -> System.out.println(input));
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int first = console.nextInt();
String second = console.nextLine();
String third = console.nextLine();
int fourth = console.nextInt();
System.out.println(first);
System.out.println(second);
System.out.println(third);
System.out.println(fourth);
}
so you get them in line by line
may be we can use this approach:
for(int i = 0; i < n; i++)
{
Scanner sc1 = new Scanner(System.in);
str0[i] = sc1.nextLine();
System.out.println(str0[i]);
}
that is we create the scanner object every time before we read the nextLine. :)