I am trying to tell whether that string was found in the list or not.
For instance, if I put Max in my list and search for Max, it should say "Max was found" If not, then it should say "Max was not found"
I do not know how to approach to getting the answer from here.
import java.util.ArrayList;
import java.util.Scanner;
public class OnTheList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (true) {
String input = scanner.nextLine();
if (input.equals("")) {
break;
}
list.add(input);
}
System.out.print("Search for? ");
System.out.print(scanner.nextLine());
if (list.contains(list)) ----> I think this is the part where I am not getting it
System.out.println(" was found!");
else
System.out.println(" was not found");
}
}
You may store the word to search, here you ask for it with scanner.nextLine() and print it but didn't save it. Then use the variable you saved the word in, to check into the List
System.out.print("Search for? ");
String toSearch = scanner.nextLine();
if (list.contains(toSearch))
System.out.println(toSearch + " was found!");
else
System.out.println(toSearch + " was not found");
Here you didn't store the user input that you are getting from Search for ,and you are trying to search an element of the list but passing list as the argument for the contains() method ,So first store the user input for a variable the search that input by passing it as the argument to contains() method and make sure to close the scanner variable at the end of the program to avoid memory leaks like below.
import java.util.ArrayList;
import java.util.Scanner;
public class OnTheList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (true) {
String input = scanner.nextLine();
if (input.equals("")) {
break;
}
list.add(input);
}
System.out.print("Search for? ");
String toSearch = scanner.nextLine();
if (list.contains(toSearch))
System.out.println(" was found!");
else
System.out.println(" was not found");
scanner.close();
}
}
Related
Hello guys I wrote program to add a name to array list but if you wrote 2nd times the same word the loop stop and write You gave the word twice. but I don't know where is the problem, Can you help me somebody?
package recurring.word;
import java.util.ArrayList;
import java.util.Scanner;
public class RecurringWord {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
while(true){
System.out.print("Type a word: ");
String name = reader.nextLine();
words.add(name);
if (words.contains(name)) {
break;
}
System.out.println("You gave the word " + name + "twice");
}
}
}
You have a logic error here:
words.add(name);
if (words.contains(name)) {
break;
}
You add the word to the ArrayList and then immediately after, if it is in the ArrayList you break out of the loop. You need to switch it to:
if (words.contains(name)) {
break;
}
words.add(name);
This will check to see if you already typed in the word before you add it to the list.
Also you have the print statement inside the while loop which is not what you want. Move it outside:
ArrayList<String> words = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
String name;
while(true){
System.out.print("Type a word: ");
name = reader.nextLine();
if (words.contains(name)) {
break;
}
words.add(name);
}
System.out.println("You gave the word " + name + " twice");
If someone could help me figure out how to search if a word exists in a file, I would greatly appreciate it. I do know how to read an entire text file though.
And this is what I have so far:
public static void main(String[] args) throws IOException {
File file = new File("words.txt");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word you would like to search for:");
String word = sc.nextLine();
List<String> words = new ArrayList<>();
try {
sc = new Scanner(file).useDelimiter( ",");
while (sc.hasNext()) {
final String wordFromFile = sc.nextLine();
if (wordFromFile.contains(word)) {
// a match!
System.out.println("The entered word: " + word + " exists in the dictionary");
break;
}
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
}
}
Just iterate through all the words in file an insert each into a HashSet from the file first. This is linear time O(n) to accomplish, no way around this as you got to read in the whole file.
Assuming one word from file it's like:
HashSet<String> set = new HashSet<>();
while (sc.hasNext()) {
set.add(sc.nextLine();
}
If someone a sticker any they really want it read to a list type collection, you can generate a HashSet like this from the list:
Set<String> set = new HashSet<>(wordList);
Note: This conversion operation is also O(n), so to read it into a list and convert you're O(2n), which is still O(n), but if this list is long far from optimal
For the lookup and/or insertion of the new word you check, can then do it in O(1) time.
if (set.contains(word)) {
//...blah..blah...bla...
} else {
set.add(word);
}
Hence the hash in the name HashSet.
This might help you understand
public static void main(String a[]){
File file = new File("words.txt");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word you would like to search for:");
String word = sc.nextLine();
boolean exist = false;
List<String> words = new ArrayList<String>();
sc = new Scanner(file);
while(sc.hasNext()){
words.add(sc.next());
}
for(int i=0;i<words.size();i++){
if(words.get(i).equals(word)){
System.out.println("The entered word: " + word + " exists in the dictionary");
exist = true;
break;
}
}
if(!exist){
System.out.println("This word is not in the dictionary.");
System.out.println("Do you want to add it");
if(System.in.read() == 'y'){
words.add(word);
}
}
}
I'm working on a Chat Bot project, and I'm almost done, other than the fact that whenever I enter an input, it returns multiple outputs depending on the length of the input X.
Here is the source code:
import java.util.*;
public class ChatBot
{
public static String getResponse(String value)
{
Scanner input = new Scanner (System.in);
String X = longestWord(value);
if (value.contains("you"))
{
return "I'm not important. Let's talk about you instead.";
}
else if (X.length() <= 3)
{
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
else if (X.length() == 4)
{
return "Tell me more about " + X;
}
else if (X.length() == 5)
{
return "Why do you think " + X + " is important?";
}
return "Now we are getting somewhere. How does " + X + " affect you the most?";
}
private static String longestWord(String value){
Scanner input = new Scanner (value);
String longest = new String();
"".equals(longest);
while (input.hasNext())
{
String temp = input.next();
if(temp.length() > longest.length())
{
longest = temp;
}
}
return longest;
}
}
This is for testing the Chat Bot:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.next();
}
}
}
I am also trying to modify the Bot so it counts the number of times it has responded; and also modify it so it randomly returns a random response depending on the length of the input. Any help will be much appreciated. Thank You!
You are using the Scanner.next method which only returns the next word in the string. So if you input a string with multiple words, your bot will respond to each of them.
You can use Scanner.nextLine() to get the entire input string, instead of only 1 word.
To count the number of times your bot has responded, you can create a field in the bot class:
private int responseCount = 0;
Then if you change yout getResponse method from a static method to an instance method, you can update this value from this method:
public String getResponse(String value)
{
String X = longestWord(value); //Your longestWord should also not be static.
this.responseCount++;
if (value.contains("you"))
{
...
Regarding counting the responses, just modify your main method:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
int numberOfResponses = 1;
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.nextLine();
numberOfResponses++;
}
input.close();
System.out.println(numberOfResponses);
}
}
If I have the time I will edit my post in a few minutes to check your problem regarding the double appearences of a response. You also forgot to close the Scanner.
EDIT: It actually happens because scanner has as a default the delimiter set to be on whitespace. so if you input a text with a whitespace, the while loop runs twice for one user input. Just use the nextLine() command.
Why is this code:
Scanner input = new Scanner (System.in);
In your getResponse method? Its not used at all. Take a closer look at your methods as they are holding some strange code.
I need to incorporate an IF statement to break the script when the user enters the letter Q.
I also need to display their input backwards to them - I am unsure on how I would do this, here is my code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListOfNames {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> list = new ArrayList<String>();
Scanner Scan = new Scanner (System.in);
String name;
System.out.println("Please enter some words (You may press Q to finish): ");
while (Scan.hasNext())
{
name = Scan.nextLine();
list.add(name);
}
Scan.close();
}
}
To check against Q:
while(Scan.hasNext())
{
name = Scan.nextLine();
if(name.equals("Q") || name.equals("q"))
{
break;
}
list.add(name);
}
To show list in the reverse order:
for(int i = list.size() - 1; i >= 0; i--)
{
System.out.println(list[i]);
}
How about this.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListOfNames {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> list = new ArrayList<String>();
Scanner Scan = new Scanner (System.in);
String name;
System.out.println("Please enter some words (You may press Q to finish): ");
while (Scan.hasNext())
{
name = Scan.nextLine();
if( name.equals("Q") ) {
break;
}
list.add(name);
}
Scan.close();
}
}
To display input backward put this code after loop that scans input.
for(int i = list.size()-1; i>=0; i--)
System.out.println(list.get(i));
while (Scan.hasNext())
{
name = Scan.nextLine();
//Input is stored to name, so you need to compare input with Q
if("Q".equals(name)
{
//You need to exit the loop
break;
}
list.add(name);
}
//You have what ever user entered in list. So use iterator (or) for-each to print them out again.
As I suspect this is homework, there are probably extra marks for using the Stack class.
Get the data in the loop and push it onto the Stack. Then when you need to print it pop results from the Stack.
From a Software Engineering standpoint, we try to stay away from using break; statements in loops. Instead, it's recommended to use a terminator
final String TERMINATOR = "Q";
boolean terminated = false;
while (scanner.hasNext() && !terminated)
{
String line = scanner.next();
if (!line.equals(TERMINATOR))
{
list.add(line);
}
else
{
terminated = true;
}
}
Also note how we do !line.equals(TERMINATOR) instead of line.equals(TERMINATOR) and do the normal list appending. This is because list appending is the nominal case and as such we want to do the least amount of checks and jumping to get to it.
As for printing out your list in reverse, you can do a simple backwards iterative for-loop
for (int i = list.size()-1; i >= 0; i--)
{
System.out.print(list.get(i) + " ");
}
thanks for all the help guys but now the nature of the question has changed using Patrick's suggestion below loop is running but it dise not seem to be storing the input to respective arrays data keeps hetting replaced into the ArrayLists rather than going to the next position into the ArrayList any suggestions?
import java.util.ArrayList;
import java.util.Scanner;
public class Arrray {
public static void main(String [] args){
ArrayList<String> names;
ArrayList<String> addr;
do {
names = new ArrayList<String>();
addr = new ArrayList<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Name and Adreess are: " + names.size() + "**"
+ addr.size());
System.out.println("please Enter Your Name :");
names.add(userInput.next());
System.out.println("please enter your Address :");
addr.add(userInput.next());
System.out.println("Do you want to add another entry? :(y/n)" );
String ans =userInput.next(); // get the value from the user using scanner class
if(ans.equals("n") || ans.equals("N"))
break;
} while (true);
int n = names.size();
int a = addr.size();
for(int i =0; i<n && i<a; i++ )
System.out.println("Name and address are as below: "+ names.get(i)+"**"+ addr.get(i));
}
}
Use a while(true) in conjunction with a break statement:
do {
if(input.next() == 'n'){
break;
}
} while(true);
get value from the user and if user enter n then break otherwise nothing
System.out.println("Do you want to add another entry? :(y/n)" );
String ans = .... // get the value from the user using scanner class
if(ans.equalsIgnoreCase("n"))
break;
Try to capture this user's input
System.out.println("Do you want to add another entry? :(y/n)");
and use that info in the while.
You have to do something like this:
String choice = "";
do {
.
.
.
.
System.out.println("Do you want to add another entry? :(y/n)" );
choice = userInput.next();
} while (!(choice.equals("n") || choice.equals("N")));
The line
choice = userInput.next();
will read user input, and the String classes equals method for comparing the input. The loop will continue until the choice is either N or n.
import java.util.ArrayList;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory y/n?");
answer = scanner.next();
} while (answer.equals("y") || answer.equals("Y"));
if (answer.equals("y") || answer.equals("Y")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the directory");
for (int i = 0; i < name.size(); i++) {
System.out.print(name.get(i) + "\t");
System.out.print(phone.get(i));
System.out.println("");
}
}
}
}