Using user input for searching object in java - java

When creating e.g an address book I also want a method for searching it.
Imagine I go for an object like this:
public class someone {
private static someone [] addressBook = new someone[150];
private String firstName;
private String lastName;
private String address;
//...
public someone(String firstName, String lastNameame, String adress/*,...*/){
this.firstName=firstName;
//...
}
Now I'm planning on searching for someone using user input and Scanner. First, the user should declare for what (s)he is searching in gerneral:
public static void searchSomeone(){
System.out.println("What do you want to search for?: ");
Scanner sc1 = new Scanner(System.in);
String userInput1 = sc1.next(); // e.g. userInput1="firstName"
Second, the user is asked for the exact value (s)he is searching for:
System.out.println("Enter a " + userInput1 + ": ");
Scanner sc2 = new Scanner(System.in);
String userInput2 = sc2.next(); // e.g. userInput2="Peter"
for (int i=1;i<150;++i){
if(getAddressBook[i].**"Value of userInput1"**.contains(userInput2)){ // here is my problem!*
System.out.println("Congrats, we've found someone! ");
}
}
}
Is there a way to use the value of the input as a call for the member variable?
In this case the argument should 'become'
if(getAddressBook[i].firstName.contains(userInput2)){}
I tried to implement another method like getInputValue that simply returns the String but it didn't work here.
If there is no such solution I will have to include code for every member variable separately which I really dont want to!
Hope you get my idea! And please be kind I'm quite new to forums. :P

FYI
What I was trying to do here is not possible within Java I guess. However Visual Basic provides a "var" keyword and also something called "generics". For everyone who has the same problem may find a solution there.

Related

How to get the name of an object to call a class method if I don't know the name?

I have a class called AttendanceSystem:
LinkedList<LinkedList<String>> student = new LinkedList<LinkedList<String>>();
public AttendanceSystem(String s){
student.add(new LinkedList<String>());
student.get(student.size()-1).add(s);
}
public void setEmail(String d){
student.get(student.size()-1).add(d);
}
In my main I have this:
System.out.println("Please enter your ID.");
String s = keyboard.nextLine();
new AttendanceSystem(s);
System.out.println("Please enter your Email.");
String d = keyboard.nextLine();
I want to add more elements into the object but since I used new AttendanceSystem(s) I don't know the name of the object I created so I cannot simply do objectname.setEmail(s). How can I call a method to that very object? Or is there a better way to do this?
I am using a scanner so I can keep adding new objects automatically until I tell it to stop.
UPDATED:
My main now:
LinkedList<AttendanceSystem> list = new LinkedList<AttendanceSystem>();
System.out.println("Please enter your ID.");
String s = keyboard.nextLine();
list.add(new AttendanceSystem(s));
System.out.println("Please enter your Email.");
String d = keyboard.nextLine();
list.get(list.size()-1).setEmail(d);
I stored all the objects in a linked list so I can just do this list.get(list.size()-1).setEmail(d);.
Simply:
AttendanceSystem identiferName = new AttendanceSystem(s);
then use the setEmail to set the relevant data for that object.
EDIT
you might want to create an addAttendee method which will take the ID and Email then simply add it to the LinkedList inside the AttendanceSystem class.
public void addAttendee(String id, String email){
LinkedList<String> myList = new LinkedList<>();
myList.add(id);
myList.add(email);
this.student.add(myList);
}
note - in this case, you should just get rid of the constructor parameter & don't use it to add any IDs or Emails.
With does changes in mind and considering that you don't want to store a reference to a new object, you call it like this:
new AttendanceSystem().addAttendee(id,email);

Using an array to store multiple variables from user input

I am relatively new to Java and would like to know how to store variables separately from a single line of user input.
At the minute the user is prompted to enter football results in the following format
home_name : away_name : home_score : away_score
and I am using a while loop to continue to ask user for input until they enter "stop"
(while (input != "stop))
Once the loop is broken I would like my program to output a variety of data such as total games played, but I'm struggling to store the home_name, away_name etc.. especially if the user wishes to enter multiple lines of results.
Two mainstream ways to store a "record" are:
Maps
Data objects
A map is more generic:
Map<String,String> match = new HashMap<>();
match.put("home_name", "Alvechurch Villa");
match.put("away_name", "Leamington");
match.put("home_score", "0");
match.put("away_score", "6");
You can add a map to a list:
List<Map<String,String>> matches = new ArrayList<>();
matches.add(list);
... and retrieve them:
Map<String,String> match = matches.get(0);
System.out.println(match.get("away_score"));
A data object is more tuned to your data format, but you have to write the class yourself.
public class Match {
public String homeName;
public String awayName;
public int homeScore;
public int awayScore;
}
Now you can use this class:
Match match = new Match();
match.homeName = "Studley";
// etc.
You can add and retrieve these from lists too:
List<Match> matches = new ArrayList<>();
matches.add(match);
Match aMatch = matches.get(0);
This is simple, but it's considered bad practice to have public fields like this - it's better to get at them via methods. For brevity, here's a data class with only one field:
public class Player {
private String name;
public Player(String name) {
this.name = name;
}
public String name() {
return name;
}
}
Player neilStacey = new Player("Neil Stacey");
You can use the same technique with all the fields in Match.
(A common style is to name a method like this getName(), and also to have a setName(). I have used a different style and made the object immutable, in an effort to set a good example!)
One advantage of the data object is that it has different types for different fields: homeName is a String, homeScore is an integer. All the fields in the Map are Strings. You can get around this by using Map<String,Object> but then as a consumer you have to cast to the right type when you read.
String homeName = (String) match.get("home_name");
Data objects allow the compiler to do a lot of compile-time checking that helps you know your code is correct. If you use a map, you won't find out until runtime.
Prompt the user separately for each input.
System.out.println("home_name: ");
String hN = scan.next();
System.out.println("away_name: ");
String aN = scan.next();
System.out.println("home_score: ");
String hS = scan.next();
System.out.println("away_score: ");
String aS = scan.next();

How to create a java method that stores User Input?

I've been trying to wreck my brain around this for days.
I need to make a method that is going to ask for the user input via the keybaord.
I've written it as
private static String getFromUser(String question){
String s = " ";
System.out.print(question);
while(in.hasNext()){
s = in.next();
//return s;
}
return s;
}
or
private static String getFromUser(String question){
String s;
System.out.print(question);
s = in.nextLine();
return s;
}
HOWEVER
When I "uncomment" a skeleton code:
public static void create() {
in = new Scanner(System.in);
String name = "";
String address = "";
//ask the user for the name and address of the company receiving the invoice
//String name = getFromUser("name of company to invoice"); // ******TASK ONE******
//String address = getAddress(); // ******TASK TWO******
It keeps stating : "variable name is already defined in method create()". BUT I'm not allowed to change the codes that has already been written. HENCE, I'm only allowed to remove the "//" comment lines.
Do I just return a string or would I require to use method overloading ( I don't fully understand method overloading, tbh).
Please Advice or give tips. Thank you very much.
You have defined the variable two times in the same method scope, what you need to do is to remove the second declaration of the variables like :
String name = "";
String address = "";
// here don't declare the variable again, just use it like
name = getFromUser("name of company to invoice");
address = getAddress();
If you're already declaring the variable here:
String name = getFromUser("name of company to invoice");
Then you don't need to also declare it here:
String name = "";
Just remove the shorter one.
You can declare it on one line and then use it later:
String name = "";
name = getFromUser("name of company to invoice");
or do both on one line (which you already do):
String name = getFromUser("name of company to invoice");
But you can't declare the same variable twice in the same scope.
The other two answers are correct in that you cannot define a variable twice within the scope of a single method. Are you permitted comment out lines? eg. you could comment out the initial definition like so.
//String name = "";
String address = "";
//ask the user for the name and address of the company receiving the invoice
String name = getFromUser("name of company to invoice");
//String address = getAddress();
and then do the same for address once you are ready to use task two.
If this is not permitted then you will have to approach your instructor (assuming this is for a class) and indicate it is not possible.
Id rather use the Scanner class instead. Makes it look cleaner:
private static String getAnswerFromUser(String question){
Scanner input = new Scanner(System.in);
System.out.println("Question: " + question);
System.out.print("Answer: ");
String answer = input.next();
return answer;
}

how to access variables from private bodies in java

public void TheBank() {
Scanner Sc = new Scanner(System.in);
System.out.println("Please Enter your Username and Password");
MemoryStorage();// Stores the Username and Password in the system.
VariableCompare();// Compares the Username and Password to see if they match or do not
}
private void MemoryStorage(){// this should just be here to store the variables username and password
Scanner Sc = new Scanner(System.in);
String username = Sc.nextLine();
String password = Sc.nextLine();
}
private void VariableCompare() {// this should compare to see if they match or dont and print the results
if (username.equals (password){
System.out.println("Please try again your Username and Password cannot be the same");
} else {
System.out.println (" Your username is:" + username);
System.out.println(" Your password is:" + password);
}
}
}
My question is the body (MemoryStorage), i want it to save the username and password, so that the other bodies can use it aswell to proceed with their calculations. At the moment the variables username and password are not accepted into the other bodies and i want to know how i can make those two variables available to all bodies to use.
Currently you're declaring local variables. Those only exist while you're executing the method. It sounds like they should actually be instance variables (fields) within your class:
public class Whatever {
private String username;
private String password;
// Methods which assign to username/password and read from them
}
You should also read up on naming conventions in Java, and think about how to name your methods more along the lines of what they're actually doing. Oh, and consider passing the Scanner into your current MemoryStorage method rather than creating a new one - I've seen various problems when people create multiple instances of Scanner with the same underlying stream.
As an alternative to instance fields, you could consider using return values from the methods. For example:
AuthenticationInfo auth = requestUserAuthentication(scanner);
validateAuthentication(auth);
... again though, it's not clear that these should really be separate methods. Why is the method which asks for the auth info not validating it? Note that the validation you're using is a simple one which isn't actually checking that the username/password combination is correct - it's just checking that it's possibly correct (the same sort of validation as would check for a minimal password length etc).

Adding multiple instances of another class into a LinkedList

I am attempting to create a list of bank records. Each record consists of a first name, last name, phone number, and balance. In the first class I ask the user for this information, then create a new instance of the records class to add to the list. However, as I add more records it replaces all records with the most recent one, which you can see with my showAllRecords() method. How do I fix this?
The add and showAllRecords method in the main class. These methods are called from a switch statement in the main method:
private static void showAllRecords()
{
if(records.bankRecords.size() == 0)
System.out.println("There are no records.");
else
for (int i = 0; i < records.bankRecords.size(); i++)
{
System.out.println(records.bankRecords.get(i));
}
}
private static void add()
{
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the first name: ");
String firstName = scan.next();
System.out.print("Please enter the last name: ");
String lastName = scan.next();
System.out.print("Please enter the phone number: ");
String phoneNumber = scan.next();
System.out.print("Please enter the balance: ");
int balance = scan.nextInt();
bankRecords.add(new records(firstName, lastName, phoneNumber, balance));
}
The records class
public class records
{
public static String firstName;
public static String lastName;
public static String phoneNumber;
public static int balance;
LinkedList<records> bankRecords = new LinkedList<records>();
public records(String tFirstName, String tLastName, String tPhoneNumber, int tBalance)
{
firstName = tFirstName;
lastName = tLastName;
phoneNumber = tPhoneNumber;
balance = tBalance;
}
}
The problem occurs because all the fields in records class are static. Remove the static keyword from the declarations of fields. As they are static whenever you create a new object of records class you overwrite those static fields.
Static fields belong to the class not to the object.
Remove the LinkedList instance that you have declared in records class. Why are u doing that. Declare it in your main class and try to use ArrayList which I think is better in your case. The reason is that records has static fields
Why your class name starts with small letter. Its a very very bad practice.
You have an inherent planning problem.
There is a difference between the entity "Bank Record", which includes, as you said, a name, balance etc., and the entity "List of Bank Records", which includes, well, a variable number of bank records.
Your "records" class (please use a capital letter in the beginning of a class name) tries to mix both. So you have both a record and a list inside it. You should separate the two entities. You then create a new "Record", and add it to the "ListOfBankRecords" objects.
Also, it seems that you have both a variable and a variable called "records". This is also why a capital letter would have been good. You shouldn't have a variable that has the same name as a class.

Categories

Resources