Java seeing if list contains string - java

I'm trying to iterate through a list line by line to check if a string the user inputs can be found and if so that line is printed. This is what i have so far
while(true) {
System.out.println("Please enter a hill name or quit to exit: ");
String HillName = input.next();
if (HillName.equals("quit")) {
break;
}
else {
for(int i=0; i < HillList.size(); i++) {
if (HillList.get(i).contains(HillName)) {
System.out.println(HillList.get(i));
}
}
}
}
I'm getting an error over contains saying cannot resolve symbol method contains java lang string, any help is appreciated.

The problem is that the reference type of the HillList.get(i) expression doesn't have a contains method. HillList has type List<Hill>, so HillList.get(i) has type Hill.
You could add a contains method to the Hill class; but I wouldn't expect a Hill to have a contains method - what do hills contain, other than rock, peat and the occasional hydroelectric power station? :) I certainly wouldn't expect a contains(String) method to return true if its name contains the parameter.
It looks like you're actually trying to print hills whose names contain some substring. For instance, if you entered Ben, you might print the Hill instances for Ben Nevis, Ben Lawers, etc. If this is the case, it looks like a much more logical check is to get the name of HillList.get(i), and call contains on that, e.g.
if (HillList.get(i).getName().contains(HillName)) {
// ...
}
You've not given a definition of the Hill class, so I'm assuming there's an accessor for the name like this. But it doesn't have to be like that: you could call HillList.get(i).toString().contains(HillName), or something else, provided that method returns strings which contain the thing you're looking for.
Note that a better way to write the loop is to use an enhanced for loop:
for (Hill hill : HillList) {
if (hill.getName().contains(HillName)) {
System.out.println(hill);
}
}
Repeatedly calling HillList.get(i) is more verbose, error-prone, and potentially less efficient if HillList is e.g. a LinkedList.
(Also note that HillList should be called hillList by convention, since variables start with lower-case letters).

This code will cover the case where you have your hill name in several rows of your list. Just setup $$getYourHillProperyName$$ with a getterMethod of the property you want to search.
while(true) {
System.out.println("Please enter a hill name or quit to exit: ");
String HillName = input.next();
if (HillName.equals("quit")) {
break;
}
else {
events
.stream()
.filter(e-> e.$$getYourHillProperyName$$.contains(HillName))
.forEach(xx->System.out.println(xx));
}
You don't need that "for" just use the contains as you have tried.

Related

Is it possible to add an or condition to an if statement in java?

So recently I've switched over from python to java and was trying to recreate some of the projects that I made on python in java. The first thing that came to mind was a quiz.
Basically, to create a quiz, I define an answer variable to the answer then use the scanner method in java to detect the user's input. After that, I use an if statement to see if the input equals the answer.
ex.
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String answer = "dog";
System.out.println("What is a common furry animal");
String input = scan.nextLine( );
if (input.equals(answer))
{
System.out.println("Correct");
}
else
{
System.out.println("Inncorect");
}
}
}
Now that all works but the user doesn't know the exact casing of the answer variable which means if the variable was "dog" and he input "Dog" it would be incorrect. So if it was possible to create an "or" condition to an if statement it would be awesome if someone let me know.
-Thanks
To or any condition in Java, use the conventional || to separate conditions. In your case it would be something like:
if (input.equals(answer) || input.equalsIgnoreCase(answer))
Although you probably just need the Java method equalsIgnoreCase as the lone condition in the first place.

How to get corresponding data from different arrays

I have 2 arrays that have corresponding data, one has 20 names and another 20 grades, Im asking the user to enter a name and then taking the name and matching it up to the grades file and returning the grade, how would I go about doing that.
Ive tried doing something like this then returning g which refers to grade and getName refers to the name input from the user. Also getName is a string and g is an int array.
getName.length() = g.length;
Would I have to scan through the grades file to find that exact line with the corresponding grade? Im not really sure how to achieve this.
Since your question does not provide the relevant data, I'll try to answer your question with my own variable names, and you can cross check my code with yours.
Assuming the names are stored in the String array names[], and the marks are in the int array marks[], and getName contains the name to be found,
int FoundMarks = 0;
for(int i = 0; i < names.length; i++)
{
if(names[i].equalsIgnoreCase(getName))
{
FoundMarks = marks[i];
break;
}
}
System.out.println("Marks of "+getName+": "+FoundMarks);
This is a simple Linear Search which takes each individual name of names and checks if the user is searching for that particular one. If found, then the marks of that person is stored in FoundMarks, and the looping stops.
This type of searching algorithm will be incredibly useful in almost all array related operations.
I repeat, the variable names might be different than yours, but the core logic remains the same.

Ask user to choose from array

I'm practicing Java and wanted to let the user choose an option from the Array such as:
String Food[] = {"Beans","Rice","Spaghetti"};
So far I only know of Scanner, but this is my first program so I don't know much of the subject.
Also, is there a way to print it? besides doing:
System.out.println(Food[0]); //and so on
for every single one of them.
Edit: not a Array list.
You can print the Array not ArrayList by doing:
System.out.println(Arrays.toString(Food));
It will print out: [Beans, Rice, Spaghetti]
If you are talking about an ArrayList, you would have to do:
ArrayList<String> Food = new ArrayList<String>();
Food.add("Beans");
Food.add("Rice");
Food.add("Spaghetti");
Then, you can loop over the ArrayList and build your own String with a StringBuilder
After reading your comment, I think you have a problem structuring your program. I will help you with that. Basically you have to complete these steps:
Program starts
Program outputs the options available in the menu
Program asks the user to choose one of the listed options
User chooses an option
Program will repeat step 3, only if the user wants to keep adding stuff to his order.
If the user does not want anything else, the Program outputs the total cost of the order
Some ideas of how to achieve this the right way:
I would use a class to encapsulate the characteristics of an "order". For instance: description, name, and price are important stuff that you need to be able to track per item.
when you don't know how many times your program will run, you have two options: using a do while loop or a while loop. Try to think in a condition that could make your program run indefinitely a number of times until the user is done. Inside the loop, you could have a sum variable where you would keep track of the items that the user wants.
It is better to keep track of items by just using numbers than Strings. Computers are faster to find stuff this way. So, if you use a HashMap to mock a database system in your program, it would make it better and faster. Then, instead of using if else to control your flow, you could use a switch instead.
I hope this helps.
EDIT: For a more efficient way of printing out the contents of the array, use an enhanced for-loop:
for(String f : Food)
{
System.out.println(f);
}
This is effectively the same as:
for(int i = 0; i < Food.size(); i++)
{
System.out.println(Food[i])
}
If I'm understanding what you're trying to do correctly, I think this should suffice (disclaimer, it's been a while since I've worked with Scanner():
public static void main(String[] args)
{
String[] food = {"Beans","Rice","Spaghetti"}; // Java standards are lowercase for variables and objects, uppercase for class names.
Scanner in = new Scanner(System.in);
System.out.println("What would you like to eat? Options:");
for(String f : food)
{
System.out.println(f);
}
String response = in.next();
boolean validEntry = false;
for(String f: food)
{
if(response.equalsIgnoreCase(f))
{
validEntry = true;
}
}
if(validEntry)
{
System.out.println("You chose " + response);
}
else
{
System.out.println("Invalid entry. Please retry.")
}
}

Can someone explain the Recursion in this Code

I've done HTML but that is nothing like learning java now in my AP class. So I'm pretty much brand new to coding. Today we learned about recursion and I'm pretty sure I understood it when it comes to using it like in this video.
https://www.youtube.com/watch?v=fpuWkZs51aM
But we then had to use it in a different way. We needed to make a program called WordPlay that accept any words, one at a time, until the word "STOP" is input. When stop was put in it prints them back out in reverse order. Here's the code.
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Enter list of words, one per line");
System.out.println("Final word should be STOP");
wordList();
}
public static void wordList()
{
Scanner keyboard = new Scanner(System.in);
String word = keyboard.next();
if (word.equalsIgnoreCase("STOP"))
System.out.println();
else
wordList();
System.out.println(word);
}
}
So the part that I don't understand is that this works fine but when I look at the ending of wordList() it seems to me that it would just keep repeating the last word that was input. I don't get what I'm missing. Can someone explain the logic here?
The recursion does output the word that was input, however each call to wordList gets a new local variable named word (each word value is on "the stack"). If you mark it final, nothing will complain - because the word isn't modified after initialization. Also, you should probably extract the Scanner (each invocation creates a new local one of those too).
public static void wordList()
{
Scanner keyboard = new Scanner(System.in);
final String word = keyboard.next(); // <-- this is the current word.
if (word.equalsIgnoreCase("STOP"))
System.out.println();
else
wordList(); // <-- it's not STOP, recurse... which
// will get a new local word (and print it).
System.out.println(word); // <-- however, this is still current word.
}
The function will execute from top to bottom as usual, but if it enters the else block it will jump back up to the beginning like shown below. It will 'loop' exactly like this until word equals "STOP", then it'll enter the if block, print out a new line (System.out.println()) then SKIP the else block, print out word then exit the function. Brackets in the if-else statement will make this easier to see.
public static void wordList()
{
|->Scanner keyboard = new Scanner(System.in);
|
| String word = keyboard.next();
| if (word.equalsIgnoreCase("STOP")) {
| System.out.println();
| }
| else {
|---wordList();
}
System.out.println(word);
}
Its basically a recursion function or method which calls itself again and again until if condition inside it is false.
So here first new word entered by user is stored in variable called word, then if condition will check if value stored in word is Stop, if its not then again wordlist method is called and all above process is repeated again.
So each time new values entered is stored in word variable.
Thats all!!
public static int wordList()
{
Scanner keyboard = new Scanner(System.in);
String word = keyboard.next();
if (word.equalsIgnoreCase("STOP"))
{
System.out.println();
return 0;
}
System.out.println(word);
return wordList();
}
Try this
This will be the sequence of operations
1) call wordlist()
2) Get a word, say WORD1 and store in local variable word.
3) before calling wordlist recursively, WORD1 goes into stack. Stack is something like a box where you can fill say biscuits one over an other, and you can take out the biscuit that you placed last. Now the stack has WORD1
4) get another word, say WORD2 and store in local variable word. This is a new function call, even if it is recursive. So a new local variable word is allocated memory.
5) before calling wordlist recursively, WORD2 goes into stack. So now WORD2 will be the top one and WORD1 will be below in the stack.
5) get another work, now it is STOP.
6) STOP is printed
7) function returns
8) now the flow returns to previous call. Now WORD2 is popped out of stack as the local variable holding WORD2 belongs to this instance of the recursive call.
8) print WORD2 and return to previous call. Now WORD1 is popped out of the stack as the local variable holding WORD1 belongs to this instance of the recursive call
9) WORD1 printed.
Just to tell you an analogy, let us assume you have a similar task. You have to get a set of books from a friend standing besides you. You have to give him back the books in the reverse order as you got it from him as soon as he gives you a book named stop.
1) You get the book from him
2) before getting the next book, you keep it on a table, since you cannot hold this and get more books from your friend
3) yet get the next book from him
4) before getting the next book, you keep it over the first book
5) you continue doing this until you get a book named stop
6) now you start returning the books, first you will return the book named stop and as you continue, since the books are stacked, you will be returning the book in reverse order.
Hope this clarifies.
It would just repeat that last word entered if the line System.out.println(word) was before the if statement.
To understand recursion, you need the notion of the "stack". Each call to wordList() occurs in a separate level in the stack. There is a different word variable in each of these stack levels.
Since the ``System.out.println(word)` line happen after the recursive call, each of these are executed when un-piling the stack (i.e. after the previous level returns). That's why words appear in reverse order. Image: if you pile boxes one atop the other, when you un-pile them, the last box is the first to go out (hence the acronym LIFO=Last In First Out).
Another important concept for recursion is to have a way of stopping it (i.e. prevent infinite recursion). In this program, it is done when the user enters "STOP".
I like to think of these problems as a 'call stack'. Each time you 'call' the method recursively you add another 'stack'. Every recursive method needs a stopping case. In your problem the first occurrence of the word 'STOP' (how convenient) acts as your stopping case.
For example if someone enters:
"Fox"
"Bear"
"Deer"
"STOP"
As soon as the word "STOP" appears, it will be printed. Now we pick up where we left off in your 'call stack' which is the ending of
wordList()
Now the only step left is
System.out.println(word)
The word 'Deer' will be printed and now our list being printed is:
"STOP"
"Deer"
And so forth until we reach the last word.

java : Make it the best "Searching method"

I have design the search method. According to my requirement, If a user wants to search a customer’s record, he/she can input the customer’s family name or given name into the name text field and then click the search button. The following two screen shots show an example of the events before and after button click (with input the name to be searched is Lee)
And below is the code for searching. It is working fine but I want to make it better?
private void search()
{
String studentName=CNameTextField.getText();
String record="";
int count=0;
for(int i=0; i<myList.size();i++)
{
String name=myList.get(i).getName();
String [] splitName= name.split(" ");
if(studentName.equals(splitName[0]) || studentName.equals(splitName[1]))
{
count++;
record=record+"\n"+myList.get(i).toString();
}
display.setText("");
display.append(count + " result(s) found for "+ studentName);
display.append("\n "+ record);
}
}
So you've basically got a list of String items, and you're searching through all of them for the value?
My recommendation would be to create Objects for each line in your DisplayArea, rather than Strings. For example, when you read in the input file for your DisplayArea, do the split() for each line and create objects of type Customer that have fields called ID, name, room, etc. This would be better OO programming anyway - Strings don't really have any meaning, whereas a Customer has meaning.
If you do this, in the search you can simply loop over all the Customers in the list, asking whether the name.equals(customer.getName()); This would remove the need to split the line every time you search.

Categories