char[] password getters and setters to a String - java

I have a typical char[] password variable with getters and setters. I have done this so that my password variable is never shown in plain text.
private String passwordAsString;
private char[] password;
public char[] getPassword() { return password; }
public void setPassword(char[] password) { this.password = password; }
I want to send my password to a database, but I believe it needs to be sent as a String type. So, I decided to create a new variable called PasswordAsString. Is there a better approach? This seems sloppy.
Secondly my getPasswordAsString is not returning the password as a String. What I have so far is:
public void setPasswordAsString(String passwordAsString) {
this.passwordAsString = passwordAsString;
}
public String getPasswordAsString() {
return password.toString();
}

The getter/setter for the password as a String could be implemented like this:
public void setPasswordAsString(String passwordAsString) {
this.password = passwordAsString.toCharArray();
}
public String getPasswordAsString() {
return new String(password);
}
These get and set the char[] password field directly – no need for a passwordAsString field. Convert from char[] to String with new String(char[]) and from String to char[] with String.toCharArray().
I'm pretty sure that passing around the password as a String like this defeats any security purpose for using a char array, though.

A char array's toString() method is not going to get you what you want. Instead, construct a new String:
public String getPasswordAsString() {
return new String(password);
}
Also, I would probably consider not including a setter for the passwordAsString field (or having a second field at all, for that matter), as this goes against what you are attempting to accomplish here.

Related

calling methods from objects (Java)

I'm new(ish) to java and I'm making a program for fun that allows you to create different users, login to those users, and make notes. I'm stuck on the user creation part. There is this one line of code that won't work. I have an array called userarr that holds user objects. Inside the object is the user creation method. This is the line of code that takes the variables you type in for the username and password and plugs it into the usercreation method:
userarr[userarr.length+1] = new user.usercreation(username,password);
It says it can't find usercreation method inside the class. But I don't know how to use the usercreation method outside the object and be able to create different named objects.
Here is the entire class:
public class TextGame {
static Scanner scan = new Scanner(System.in);
class user extends TextGame {
String username;
int password;
String[] notes;
public void usercreation(String username, int password) {
this.username = username;
this.password = password;
}
public void login(int password) {
this.password = password;
System.out.println("please type the password to proceed.");
if (scan.nextLine().equals(this.password)) {
System.out.println("logged in. type 'note' to access notes, or 'logoff' to log off this user.");
}
}
}
static user[] userarr;
public static void newuser() {
System.out.println("\n\nType the username for this user.");
String username = scan.nextLine();
System.out.println("Username is now " + username + ". is this what you want? type 'yes' to proceed, or 'no' to enter username again.");
if (scan.nextLine().equals("no")) {
newuser();
}
else {
System.out.println("\n\n type the password for this user. (numbers only.)");
int password = scan.nextInt();
System.out.println("user is " + username + " and password is " + password + " is this what you want?");
if (scan.nextLine().equals("no")) {
newuser();
} else {
userarr[userarr.length + 1] = new user.usercreation(username, password);
}
}
}
public static void main(String[] args) {
System.out.println("Welcome to LINCOLN COMP console OS. Type 'new' to create a new user, type 'log' to log in to an existing user, or type 'exit' to leave.\nif you are asked a yes or no question, if you type something ether than yes or no, it will default to yes.");
String ch1 = scan.nextLine();
switch (ch1) {
case "new":
System.out.println("Initializing user creation method:");
newuser();
break;
case "log":
break;
case "exit":
System.out.println("Goodbye!");
System.exit(0);
break;
}
}
}
Okay, so starting with new user.usercreation(username,password);
usercreation is not a static inner class of user, so you can't create it
usercreation is a method of user which returns void, so you returns nothing, so you can't assign it to anything.
You could...
Create the instance of user, apply the properties and assign it to the array as separate actions
user newUser = user();
newUser.usercreation(username,password);
userarr[userarr.length+1] = newUser;
Equally, you could make usercreation a factory methhod, but I'm trying to keep it simply.
You could...
Based on what you seem to be trying to do, is make the usercreation method into a class constructor, which would make more sense...
class user extends TextGame {
String username;
int password;
String[] notes;
public user(String username, int password) {
this.username=username;
this.password=password;
}
public void login(int password) {
this.password=password;
System.out.println("please type the password to proceed.");
if (scan.nextLine().equals(this.password)) {
System.out.println("logged in. type 'note' to access notes, or 'logoff' to log off this user.");
}
}
}
Then you could just do...
userarr[userarr.length+1] = new user(username,password);
You're also haven't create an instance of the userarr, so you're going to hit a NullPointerException
You should do something like...
userarr = new user[10];
before you try and use it.
This will allow you to maintain ten instances of the user class. You should also check to ensure that you've not exceeded the number of available elements in the array before you try and add new elements.
Have a look at the Arrays Trail for more details
I'd encourage you to have a look at Code Conventions for Java, which make it easier for other people to read your code and make it easier for you to read others
Before you use the usercreation method from a different class, you must first instantiate an object of usercreation class to gain access to it's properties(methods, variables) in a different class.
Example:
UserCreation us = new UserCreation (default constructor parameters);
userarr[userarr.length+1] = us.usercreation(username,password);
You should really be using a constructor:
public user(String username, int password) { // should be named User
this.username = username;
this.password = password;
}
Then you could add a user to an array like so:
userarr[userarr.length+1] = new User("username", 1); // doesn't work!
...Except, this code will fail because you didn't instantiate the array. And even if you had, you can't assign an element to an array like this. Arrays do not automatically re-size themselves, so when you try to add an element like this you will get an ArrayIndexOutOfBoundsException and your program will exit.
Firstly, I'd like to state that you haven't instantiated the userarr array yet. So, I recommend to do that first.
Secondly,new user.usercreation(username,password); usercreation is not a static inner class of user, so you can't create it.
Thirdly, usercreation is a method which returns void in which case you can't assign it to anything.
it seems that you want to invoke this method:
public void usercreation(String username, int password) {
this.username=username;
this.password=password;
}
In order to invoke that method, you must create an object of type user first in order to invoke it.
Example:
user user1 = new user();
user1.usercreation(username,password);
userarr[userarr.length+1] = user1;
However, the easiest way would be to make a constructor to initialise the username and password like below:
public user(String username, int password) {
this.username=username;
this.password=password;
}
Hence you can easily do this:
userarr[userarr.length+1] = new user(username,password);

Storing Objects of Class into an Array

I'm trying to store objects that have a username and password from the class "Driver" into an array list. When I try to print every value in the array to test whether they're being stored, it only prints the last value declared, numerous times. I have tried nearly every other solution on thee forums related to this issue and it just wont work :(
Code below:
package eDepotSystem;
import java.util.ArrayList;
public class Driver {
protected static String driverUserName;
protected static String driverPassWord;
public Driver (String userName, String passWord) {
driverUserName = userName;
driverPassWord = passWord;
}
public static void driverArray() {
ArrayList<Driver> driverList = new ArrayList<Driver>();
Driver driver = new Driver(driverUserName, driverPassWord);
driver.setUserName("driver1");
driver.setPassword("123");
driverList.add(driver);
driver = new Driver(driverUserName, driverPassWord);
driver.setUserName("driver2");
driver.setPassword("321");
driverList.add(driver);
Driver tempDriver = new Driver(driverUserName, driverPassWord);
for (int i = 0; i < driverList.size(); i++) {
tempDriver = driverList.get(i);
System.out.println(tempDriver);
}
}
public void setPassword(String password) {
driverPassWord = password;
}
public static String getUserName() {
return driverUserName;
}
#Override
public String toString() {
return driverUserName + driverPassWord;
}
}
I don't know whether my loop is wrong or the way I'm declaring the objects is wrong? Any help would be grand and thanks in advance!
your field variables should not be static.
It is being shared by all instances of Driver class (ie objects), hence it is printing the last value which you added.
Problem 1:
Your "instance variables" (username and password) are static. Therefore you only have one instance of them. If you print them out you must always get the same value.
Problem 2:
You only add one object. You add it once, change it's values and add it a second time. If you print it out you must get the same values ... even if you remove the statickeywords.
You should instead try something like this:
package eDepotSystem;
import java.util.ArrayList;
import java.util.List;
public class Driver {
private final String driverUserName;
private final String driverPassWord;
public Driver (String userName, String passWord) {
driverUserName = userName;
driverPassWord = passWord;
}
public static void driverArray() {
List<Driver> driverList = new ArrayList<Driver>();
driverList.add(new Driver("drv1", "pw1"));
driverList.add(new Driver("drv2", "pw2"));
for (Driver tempDriver : driverList) {
System.out.println(tempDriver);
}
}
}
The static keyword forces the driverUserName and driverPassWord variables to be instantiated only once in memory. While they are not constants, it makes any further additions to your list reference that first and only instance in memory, hence why it keeps showing the same value.
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

The method Registration(String, String, String, String) is undefined for the type Client

if (type == "REGISTRATION"){
String name = json.getString("name");
String Location = json.getString("loc");
Client.Registration(username, password, name, Location); //error
DatabaseController.registerUser(Pobj, userObj);
}
Client.java
public static boolean Registration(String username, String password, String name, String loc){
clientUsername = username;
clientPassword = password;
clientname = name;
clientlocation = loc;
}
Registration function is defined here
it gives me error like:
method Registration(String, String, String, String) is undefined for the type Client
In java (and many other programming languages), your methods (or functions) have to have a return type. In your case, you declared the return type of your function to be boolean. This however means that this method must return a boolean. In your code, you have no return statement.
To solve the problem: you could either add a return statement, or change the return type to void, meaning it doesn't return anything.
Considering that you aren't returning anything in your function, I suggest using the second option, as follows:
public static void Registration(String username, String password, String name, String loc)
{ ... }
Also, as #Peadar Ó Duinnín mentioned, Java methods should be written in camel case, meaning the first word is not capitalized, but all the words after are, i.e. myFunctionThatDoesSomething(). This means your method should become registration(...)
Your Registration method (which should be registration. Method/Functions are camelCase in Java.) should be in your Client class as follows. You should also be returning a boolean or change the method signature to public static void registration(...
public class Client {
public static boolean registration(String username, String password, String name, String loc) {
clientUsername = username;
clientPassword = password;
clientName = name;
clientLocation = loc;
}
}

Accessing class string returns NULL

This is a debug oriented question, but i've been very confused why some of my objects are returning NULL values.
I have a GUI here that takes strings from the text field when a button is clicked,
public class USAdditionalGUI extends javax.swing.JFrame {
public String AreaCode; // declare Strings
public String Exchange;
public String LastFour;
public String State;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// On button click use getText() to collect the strings from the
//`enter code here` fields and store them into the declared strings.
AreaCode = jTextField3.getText();
Exchange = jTextField1.getText();
LastFour = jTextField2.getText();
State = jTextField4.getText();
}
The next class has get methods for each of the String varibles, and here lies the problem, I create an object to the GUI class and try to access the String information but it keeps coming up NULL when I print it out.
public class TRFUSAddressFormatting{
private String State;
private String areacode; // 3 digits
private String digitExchange; // 3
private String lastfour; // 4
USAdditionalGUI usobj = new USAdditionalGUI();
public String getState(){
State = usobj.State;
System.out.println(State); // Why does this print NULL!!?!?!
return State;
}
}
Am I accessing the string correctly?
when you declare strings, you need to initialize them or they will be null.
public class USAdditionalGUI extends javax.swing.JFrame {
public String AreaCode = ""; // declare Strings
public String Exchange = "";
public String LastFour = "";
public String State = "";
or whatever DEFAULT value you want to them
btw, I suggest you to declare them private and implement a get method to retrieve their information
public class USAdditionalGUI extends javax.swing.JFrame {
private String AreaCode = ""; // declare Strings
private String Exchange = "";
private String LastFour = "";
private String State = "";
public String getAreaCode(){
return AreaCode;
}
//and so
Variables/fields in your snippet ie, AreaCode, Exchange are instance variables of a class which are initialized to their default values when class's object is created. Objects' default value is null unless explictly initialized and primitives have their own default values like int -> 0 etc. Since Areacode, Exchange, LastFour, State above are of type String which are stored as objects on JVM Heap hence they are initiazed to null unless you explicitly initialize them yourself.

How to print the output of an accessor of every instance of a class?

How would you go about creating a class like this:
public class tmUser {
private String Username;
private int wHours;
static int numUsers;
public tmUser(){
Username = "";
wHours = 0;
}
public tmUser(String U, int H){
Username = U;
wHours = H;
}
public void setUsername(String U){
Username = U;
}
public void setwHours(int H){
wHours = H;
}
public String getUsername(){
return Username;
}
public int getwHours(){
return wHours;
}
public static void initnumUsers(){
numUsers = 0;
}
public static int getnumUsers(){
return numUsers;
}
}
and then printing all of tmUser instances Username variable? in maybe a for each loop? I'm hoping for something like:
for each(tmUser){
System.out.println(Username);
}
This is for a menu in a program which displays all created users usernames.
You almost had it:
List<TmUser> tmUsers = ...
for(TmUser user : tmUsers) {
System.out.println(user.getUsername());
}
You would also want to capitalize tmUser into TmUser.
When you create a tmUser add it to a collection like
List<TmUser> tmUsers = new ArrayList<TmUser>();
TmUser tmUser = new TmUser(username, hoursWorked);
tmUser.add(tmUser);
// later
for(TmUser tmUser: tumUsers)
System.out.println(tmUser.getUsername());
You need to store all of tmUser instances somewhere first. You could do it this way:
public class tmUser {
...
public static List<tmUser> USERS = new ArrayList<tmUser>();
public tmUser() {
...
USERS.add( this );
}
and then printing:
for (tmUser user : tmUser.USERS) {
System.out.println(user.getUsername());
}
The 3 current answers are basically the same. Just wanted to add that if the class defined a toString() that returned the user name, it would not be necessary to add the .getUsername() method call, since System.out.println(Object) will automatically call the toString() method.
Whether this could work for your use case is debatable. The toString() method would normally provide more data on the object.
As the answers already posted indicate, this would involve maintaining some sort of data structure that holds references to all instances of tmUser (e.g. a List<tmUser>).
This would mean that a reference to each and every instance ever created will always be held there, they will never be garbage collected. You could explicitly remove them when you decide an instance is no longer needed, but then you would have to keep track of the life cycle of all instances, and basically end up doing memory management yourself.

Categories

Resources