how to access variables from private bodies in java - 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).

Related

Set compulsory field for an object

I am working on my pet ownership system and struggle at a problem. To add a resident object, I need 5 fields which are phone, postcode, name, birthday and pet. Among them, phone, postcode, and name are compulsory fields, and the others are optional. An object can only be built with the existence of compulsory fields.
How can I do that, to differentiate between compulsory and optional fields? I just taught myself the OOP system. Really need a hint. Any answer is welcome!
The best way to do this is to make sure through prompt(user input) or string check(file input) if the input has the correct fields needed to correctly create your object(class)
After this use a programmer defined constructor
Documentation for that in the link
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
to instantiate the object using the needed fields and I would use Set functions for optional inputs.
If the inputs do not match the needed inputs output a fail message and do not instantiate the object.
I hope this helps with your problem.
This is just an example of how you could approach the problem
public class Example{
String phone;
String postcode;
String name;
String birthday;
String pet;
public Example()
{
birthday="N/A";
pet="N/A";
}
public static void main(String[] args)
{
//Ask phone number
while(phone==null||phone=="")
{
//keep on asking
}
//Ask postcode
while(postcode==null||postcode=="")
{
//keep on asking
}
//Ask name
while(name==null||name="")
{
//keep on asking
}
//Ask birthday, and no need for checks
//Ask pet, and no need for checks
}
}

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;
}

Dynamically Creating Objects in a Class from String

I'm trying to make a Sign Up window on JFrame Form in NetBeans. I have created a class named users (in the same package) that has a username as String and password as char[].
When the username and password are filled, and Sign Up button is pressed, I want to make a new object in the class 'users' so that it's name is taken from username textfield itself.
I want to dynamically create object whose names have been taken from a string.
eg: If I put value of Username as "guy", then create users.guy which has a String = "guy" and a char[] as password.
package login;
public class users {
private char[] password;
String username;
users() {
username = "anonymous";
password = null;
}
users(String u, char[] p) {
username = u;
password = p;
}
void putdata() {
System.out.println(username);
System.out.println(password);
}
}
Thanks in advance.
If I understand good your question what you want to do is a mapping. In Java there's a lot of ways for do that.
I would recommend you the use of HashMap, it's simple and efficient.
There's a simple example.
String userYayotrón = "Yayotrón";
char[] passwordYayotrón = "contraseña".toArray();
Map<String, char[]> usersMap = new HashMap<String, char[]>();
//This hashmap will take two values, the KEY which identifies the VALUE. The key is the first one, which I define as String. I will use it for save the User's name. And the value will be the password.
usersMap.put(userYayotrón,passwordYayotrón);
Now, you can use this map for a lot of things. For example:
usersMap .get(userYayotrón); // This will return an char[] with the password of Yayotrón.
usersMap .size(); // How many users do you have in this map.
Also I highly recommend read the following question related:
What java collection should I use?
How to use Java Set?
How does HashMap works in Java?
Create a new instance of the users class passing the username and password like so:
new users(userTextField.getText(), userPasswordField.getText().toCharArray())
If you include the code for the GUI itself I'd be able to give you a more direct answer/solution.

Using user input for searching object in 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.

Categories

Resources