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.
Related
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.
I am creating a java program that asks for a number of variables, what the user wants to name them, and then asks for the user to input an equation. The program then writes a program that asks for the variables defined by the user and then solves an equation using the formula the user defined.
I have this so far:
int variables;
String equation;
Scanner reader = new Scanner(System.in);
System.out.print("Enter the number of required variables for equation (at most 20 variables): ");
variables = reader.nextInt();
System.out.println("");
System.out.println("Assign letters or words to each variable: ");
I was thinking of making an if statement for each of the twenty possible variables, but that would be incredibly time consuming. I want my program to take the input number of variables, for example four, and automatically name them in the program "variable1", "variable2", etc. I also want to know how to take an input equation using the scanner and use that as a real equation in the program later on.
I was also thinking of somehow using the assigned names defined by the user as the classification of the variable. So if they had two variables and named the first one 'a' and the second 'b', the strings would be referenced as String a and String b, but yet again, I don't really know how to do that.
You can use an array of size 20,
int[] arr = new int[20];
and the read the integers.
for (int i = 0; i < 20; i++) arr[i] = reader.nextInt();
When you want to use these values in an equation:
int value = arr[0]*arr[1]/arr[2];
You can't use assigned values defined by the user to set variable names. This defeats the purpose of having variables; you won't know how to reference those variables in code, since the variables don't have a constant name.
This program I am writing is giving me fits. What I am trying to do is prevent a user from entering the same integer twice. The program takes 4 int inputs and compares them to an array of 4 random int's, searching for a match. Here is what I have thus far in my attempts to prevent multiple inputs.
for (int z = 0; z<4; z++){
System.out.println("Enter a number between 0-9. No duplicates please!");
temp[z] = inputDevice.nextInt();
for(int why = 0; why<temp.length; why++){
if(Arrays.asList(temp).contains(temp[z])){
System.out.println("Duplicate found! Please enter a non-repeating digit");
temp[z]=0;
z--;
}
}
}
The inputs are coming into the temp array just fine. And are being passed on to the other methods in the program, and that is working. I am guessing the issue is with my conditional statement - if(Arrays.asList(temp).contains(temp[z]))
Is there a better way to test to see if an array already contains a value?
Thanks in advance.
1) Since you are converting the array to a list, might as well use an ArrayList
2) Store your input in a variable and test if it is contained within the list already
List<Integer> my_list = new ArrayList<Integer>();
for (int z = 0; z<4; z++){
System.out.println("Enter a number between 0-9. No duplicates please!");
int input = inputDevice.nextInt();
if(my_list.contains(input)){
System.out.println("Duplicate found! Please enter a non-repeating digit");
z--;
}
else{
my_list.add(input);
}
}
When you check if temp contains z, it already contains z. Put the input in a temporary variable before you check it and only add it afterwards.
You're not using the why from your loop.
However if possible I would change temp to an ArrayList implementation. The problem with toList method. It's using the int[] array as a single object rather than treating it as an array of int objects. To do the latter you must use Integers.
I am trying to figure a way in how to change an object's value. I've made a class in which it contains set and get for the object and 3 sorts of values being PRICE, QUANTITY and NAME.
The price and name are already set in the test class
System.out.println("How many would you like?");
String quantity = s1.nextLine();
quantity = food1.setQuantity();
quantity = food1.setQuantity(); is wrong. How do I change it according to how much quantity the user wants?
You may try with:
quantity = food1.setQuantity(Integer.parseInt(quantity));
instead of:
quantity = food1.setQuantity();
I don't mean to sound harsh, but programming isn't magic. Look at what you're doing:
String quantity = s1.nextLine();
quantity = food1.setQuantity();
You're overwriting the string with what one would hope to be a void set method. Instead, the method should be a void set method, which accepts an integer, so you would do the following (assuming proper function implementation):
String quantity = s1.nextLine();
food1.setQuantity(Integer.parseInt(quantity));
Not sure if you learned Exception handling yet, but you should wrap this in a try/catch if you have. If not, you can use regular expressions to see if it's an integer, if that is necessary. Odds are this is a class assignment, and you're probably assuming that the input is valid or using exception handling. Good luck.
Assuming, that the quantity is supposed to be an integer, you could write this:
String quanity = s1. nextLine();
//check that quanitity is a valid number before trying to parse it as a number
if(quantity.matches("\\d+"))
{
food1.setQuantity(Integer.parseInt(quantity));
}else
{
System.out.println("The quantity you entered is not a valid number.");
}
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.