Java Array List - finding duplicate in While loop - java

I tried solving this ArrayList problem but no luck
Anyway in while loop I have to add new String items to the ArrayList.
If there is a duplicate item there should be a message that says REPEATED ITEM.
While loop will break by word END
public static void main(String[] args) {
ArrayList<String> lista1 = new ArrayList<>();
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("enter words: ");
lista1.add(in.nextLine());
if(lista1.containsAll(lista1)){
System.out.println("Repeated words");
}
if(lista1.contains("end")) {
break;
}
}
for(String data:lista1)
System.out.println(data);
}

If I understand what you're trying to do correctly, I believe it appears that you're trying to loop over user input until they type "end", each input to a list, and state if you already added that word by printing out "repeated word". If that's the case, you're pretty close. You just need to understand how to use the list data structure a little bit better.
public static void main(String[] args) {
ArrayList<String> lista1 = new ArrayList<>();
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("enter words: ");
String userInput = in.nextLine();
if (lista1.contains(userInput)) { // checks if user's input is already in lista1
System.out.println("Repeated word: " + userInput);
} else { // if it's not, then add user's input to lista1
lista1.add(userInput);
}
if (lista1.contains("end")) { // if lista1 contains "end", exit loop
break;
}
}
for(String data:lista1)
System.out.println(data);
}

Related

How to get the Scanner to scan all the elements in an array, in java

This is the Question: Create an array of Strings and assign 5 names to it. Ask the user what their name is, if their name is the same as one that is already in the list do something. Get creative!, use a for-each loop to print every name in the array with a space in-between each indices.
This is what I have so far. One of the issues I am having is that the scanner is only comparing the input to the first name on the array and not the rest.
public static void main(String[] args) {
String[] names = {"Jose", "Alex", "Steven", "Sky", "Ana"};
Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String input = scan.next();
for (String n:names) {
if (n.equalsIgnoreCase(input)) {
System.out.print("Hooray! Your odds of finding a keychain with your name on it are high! =) ");
}
else {
System.out.print("Welcome to the rare names club!!! =D " );
System.out.print(names + " ");
}
break;
}
}
}
Feel free to comment on any other issues you see. I am new at this and I'd appreciate an feedback. Thx
Maybe this will be helpful. I think the "break" is called prematurely. There are lots of ways you can solve this, but I used a boolean to determine if the name was found. Then I used the boolean after the loop to determine what to print.
public static void main(String[] args) {
String[] names = {"Jose", "Alex", "Steven", "Sky", "Ana"};
Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String input = scan.next();
boolean isFound = false;
for (String n:names) {
if (n.equalsIgnoreCase(input)) {
isFound = true;
break;
}
}
if (isFound) {
System.out.print("Hooray! Your odds of finding a keychain with your name on it are high! =) ");
} else {
System.out.print("Welcome to the rare names club!!! =D " );
System.out.print(names + " ");
}
}
Same method but slightly different :)
`import java.util.Scanner;
import java.util.ArrayList;
public class New {
public static void main (String[]args) {
String [] cities = {"Poznan", "Warsaw", "Gdansk", "Wroclaw", "Krakow", "Lodz", "Katowice"};
Scanner scan = new Scanner(System.in);
System.out.println("What is the name of your city in Poland? ");
String name = scan.nextLine();
for (String n:cities) {
if (n.equalsIgnoreCase(name)) {
System.out.println("You are citizen of Poland from " +name);
System.out.println("Thank your for visiting " +name);
}
else {
System.out.println("You are not from Poland!!!" );
System.out.println("There is not city in Poland called" +name);
}
break;
}
}
}`

ArrayList: I would like to find a word in my arrayList

I have an arrayList with several elements:
ArrayList<String> listName = new ArrayList<String>();
listName.add("julie");
listName.add("sandrine");
listName.add("toto");
The user enters a name for example popo, the element doesn't exists.
However, I have several prints, I don't understand?
The word isn't find
The word isn't find
The word isn't find
I tried to make an algorithm:
import java.util.ArrayList;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> listName = new ArrayList<String>();
listName.add("julie");
listName.add("sandrine");
listName.add("toto");
System.out.println("please enter your name : ");
String wordSearch = input.nextLine();
for (int i = 0; i < listName.size(); i++) {
if (listName.get(i).equals(wordSearch)){
System.out.println("The word is find : ");
} else {
System.out.println("The word isn't find ");
}
}
}
}
If you only want to print it once, you need to do the following:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> listName = new ArrayList<String>();
listName.add("julie");
listName.add("sandrine");
listName.add("toto");
System.out.println("please enter your name : ");
String wordSearch = input.nextLine();
boolean isUserFound = false;
for (String s : listName) {
if (s.equals(wordSearch)) {
isUserFound =true;
break;
}
}
if(isUserFound)
System.out.println("The word is find : ");
else
System.out.println("The word isn't find : ");
}
First find out if the user exist, set a flag accordingly and print the result also accordingly.
Or you can simply replace the loop by:
if(listName.contains(wordSearch))
System.out.println("The word is find : ");
else
System.out.println("The word isn't find : ");
or
if(listName.indexOf(wordSearch) != -1 )
System.out.println("The word is find : ");
else
System.out.println("The word isn't find : ");
Both of those methods (i.e., contains and indexOf) are part of the list collection so you don't need to reimplement that logic, just used what is already there.
Full example:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<String> listName = new ArrayList<>();
listName.add("julie");
listName.add("sandrine");
listName.add("toto");
System.out.println("please enter your name : ");
String wordSearch = input.nextLine();
if(listName.contains(wordSearch))
System.out.println("The word is find : ");
else
System.out.println("The word isn't find : ");
}
You are using an ArrayList<String> for your words. Since there would, imo, be no need to house duplicates, a HashSet would be better since it's lookup is much more efficient. A Set zeroes in on the location using the hashCode of the object while List must do a linear search.
Set<String> wordSet = new HashSet<String>();
listName.add("julie");
listName.add("sandrine");
listName.add("toto");
if (wordSet.contains(word)) {
System.out.println(word + " was found");
} else {
System.out.println(word + " was not found");
}
The downside to using a Set is that there is no way to do any index retrieval (which does not seem to be a requirement in your case). Also, sets are unordered which means if you iterate thru them, they may appear in a different order in which they were added. This latter situation can be avoided by using a LinkedHashSet where the order is maintained. I suggest learning about Sets as they have many uses.

How to take multi-line input in Java

I'm trying to take multi-line user input in Java and split the lines into an array, I need this to solve a problem for an online judge. I'm using a Scanner to take input. I cant determine the end of input. I always get an infinite loop, since I don't know the size of input (i.e number of lines)
Terminating input with an empty String (clicking enter) is still an infinite loop. Code provided below.
public static void main(String[] args) {
ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while (s.hasNextLine() == true){
in.add(s.nextLine());
//infinite loop
}
}
I'm not even sure why the loop executes the first time. I believe the hasNextLine() should be false the first time ,since no input was taken yet. Any help or clarification appreciated.
You could use the empty line as a loop-breaker:
while (s.hasNextLine()){ //no need for "== true"
String read = s.nextLine();
if(read == null || read.isEmpty()){ //if the line is empty
break; //exit the loop
}
in.add(read);
[...]
}
You could end the loop with something like below. Here, the String "END" (case-insenstive) is used to signify end of the multi-line content:
public static void main(String[] args) {
ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while (s.hasNextLine()) {
String line = s.nextLine();
in.add(line);
if (line != null && line.equalsIgnoreCase("END")) {
System.out.println("Output list : " + in);
break;
}
}
}
You can use this code. It returns when the user press Enter on an empty line.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
ArrayList<String> arrayLines = new ArrayList<>();
String line;
while(true){
line = scanner.nextLine();
if(line.equals("")){
break;
}
else {
System.out.println(line);
arrayLines.add(line);
}
}
System.out.println(arrayLines);
}
}
Best
You can do somthing like this:
while (s.hasNextLine() == true){
String line = s.nextLine();
if ("".equals(line)) {
break;
}
in.add(line);
//infinite loop
}

How to make arrayList read Strings only but not int?

Write a method called countWords that accepts an ArrayList of String as argument and
prints out the number of words (i.e. Strings) that start with ―A‖ or ―a‖ and prints all words longer than 5 characters on one line.
My solution is like
int count=0;
String[] st=null;
Scanner input=new Scanner(System.in);
ArrayList<String> array = new ArrayList<String>();
System.out.println("please input something");
while(input.hasNext()) {
String st1=input.next();
array.add(st1);
}
for(int i=0; i<array.size();i++) {
if(array.get(i).startsWith("a")||array.get(i).startsWith("A")) {
count++;
}
}
for(int j=0; j<array.size(); j++) {
if(array.get(j).length()>5)
st[j]=array.get(j);
}
System.out.println(count);
System.out.println(st);
}
but there will be no end for typing in Strings
As the last line of your question said
but there will be no end for typing in Strings
Well That is because you did not provided any way to end the while loop.
while(input.hasNext())
Will run forever and ever waiting for next user input. You have to break the while loop once the inputting is done.
AFTERWARDS
As the question said "prints out the number of words that start with A or a and prints all words longer than 5 characters on one line."
For this you can loop through the ArrayList and check for
if(array.get(i).startsWith("A") || array.get(i).startsWith("a")) count++;
if(array.get(i).length()>5) System.out.print(array.get(i)+" ");
and print the number of A or a Occurrence after the loop
System.out.println("\n Number of word with A or a:"+count);
Here is a working implementation of your code
public static void main(String[] args) {
int count=0;
String[] st=null;
Scanner input=new Scanner(System.in);
ArrayList<String> array = new ArrayList<String>();
System.out.println("please input something");
//System.out.println(input.hasNext());
while(input.hasNext()) {
String st1=input.next();
//System.out.println((int) st1.charAt(0));
if(st1.equals("exit")) break;
array.add(st1);
}
for(int i=0; i<array.size();i++) {
if(array.get(i).startsWith("A") || array.get(i).startsWith("a")){
count++;
}
if(array.get(i).length()>5) {
System.out.print(array.get(i)+" ");
}
}
System.out.println("\nNumber of word with A or a:"+count);
}
to end the loop you have to type exit.
Here is a solution to your problem..
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String... args){
// Sample String sentence
String sentence = "This is the sentence with 5 words starting with
all like allwords alltogether also Allnotout allother and allofus.";
// Splitting above sentence to get each word separately and storing them into List
List<String> strings = Arrays.asList(sentence.split("\\s+"));
// calling a method named countWord() as per your assignment question.
Test.countWords(strings);
}
// implementing that method
static void countWords(List<String> input){
long count = input.stream().filter(word -> word.startsWith("all") || word.startsWith("All")).count();
System.out.print("Total words starting with all/All are : "+ count +"\t");
input.stream().filter(word -> word.length() > 5).forEach( word -> System.out.print(word + "\t"));
}
}

Getting multiple Strings into an Array [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I'm having difficulties with my homework. I have the basic logic down but I'm messing up. The objective is to make a receipt from a shopping list that's inputted by the user. For example, the user enters:
Apples
OraNgeS // also it's not case sensitive
Oranges
Bananas
!checkout //this is to indicate the list is over
Output:
Apples x1
Oranges x2
Bananas x1
I'm stuck. My code so far:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Enter the items you wish to buy:");
String[] input = new String [keyboard.nextLine()];
keyboard.nextLine(); //consuming the <enter> from input above
for (int i = 0; i < input.length; i++) {
input[i] = keyboard.nextLine();
}
System.out.printf("\nYour input:\n");
for (String s : input) {
System.out.println(s);
}
}
I know I'll have to add the if statement eventually so if they type in "!checkout" it'll end the list. but I can't get past this yet.
Any tips or advice?
Try to use ArrayList <-- Link.
Array is need to statically initialize it first before you can use it while ArrayList is automatically expanding when you add values on it. you can use ArrayList without initializing a range on it. Here is the sample:
List<String> fruitList = new ArrayList<>();
Scanner keyboard = null;
Boolean isNotDone = true;
System.out.println("Press 'Q' if you want to print out.");
while(isNotDone) {
keyboard = new Scanner(System.in);
System.out.print("Input Fruits: ");
String temp = keyboard.nextLine();
if(temp.equalsIgnoreCase("q")) {
isNotDone = false;
} else {
fruitList.add(temp);
}
}
System.out.println(fruitList);
The following code will do exactly what you are looking for:
Scanner keyboard = new Scanner(System.in);
List<String> inputItems = new ArrayList<String>();
List<String> printedResults = new ArrayList<String>();
String input = keyboard.nextLine();
while(!"!checkout".equals(input))
{
inputItems.add(input);
input = keyboard.nextLine();
}
for(int i=0; i<inputItems.size();i++)
{
Integer thisItemCount = 0;
String currentItem = inputItems.get(i);
for(int j=0; j<inputItems.size();j++)
{
if(inputItems.get(j).toLowerCase().equals(currentItem.toLowerCase()))
thisItemCount++;
}
if(!printedResults.contains(currentItem.toLowerCase()))
{
System.out.println(currentItem.toLowerCase() + " x" + thisItemCount);
printedResults.add(currentItem.toLowerCase());
}
}

Categories

Resources