I'm trying to compare a string, pass, to a dictionary file list. If it directly matches a word, it is considered weak (balloon). If it contains the word from the dictionary file (#balloon232), it is considered moderate. If neither, its strong. In this code, weak and moderate both work correctly, but when a strong pass is entered, it says it is moderate. Thanks for the help.
public static void passwordStrength(String pass, String file2) {
boolean found2 = false;
boolean found3 = false;
try {
y = new Scanner(new File(file2));
z = new Scanner(new File(file2));
while (y.hasNextLine()) {
if (pass.equals(y.nextLine().trim())) {
System.out.println("\nYour password is weak");
found2 = true;
break;
}
}
while (z.hasNextLine()) {
if (pass.contains(z.nextLine().trim()) && !found2) {
System.out.println("\nYour password is moderate");
found3 = true;
break;
}
}
if (!found3 && !found2) {
System.out.println("\nYour password is strong");
}
y.close();
z.close();
} catch (Exception e) {
System.out.print("Error");
}
}
The logic seems fine it should print password is strong. You should print out all lines that you read in from the file to debug and see both when the password and the word from the file doesn't match.
I don't think it makes sense to create multiple scanners and read the file twice. You can read in the file once and test the pass to see if it's a week or moderate and return the string and if not found return strong. You can throw the exception so that main up to you. Unless you specifically want to print out the password strength in this function.
Here is a sample.
import java.io.File;
import java.util.Scanner;
public class PasswordTest {
public static String passwordStrength(String pass, String file2) {
try {
Scanner fileScanner = new Scanner(new File(file2));
while (fileScanner.hasNextLine()) {
String passInFile = fileScanner.nextLine().trim();
if (pass.equals(passInFile)) {
return ("Your password is weak");
}
if (pass.contains(passInFile)) {
return "Your password is moderate";
}
}
} catch (Exception e) {
return e.getMessage();
}
return "Your Password is strong";
}
public static void main(String[] args) {
System.out.println(passwordStrength("test", "test.txt"));
}
}
Related
I get an error when I try to type a password consisting only alphanumeric characters but loops the way I intended if I type symbols. This is my first time trying to make a program that writes and reads a file and I'm still stuck here. I tried to paste the entire code to a different class but still runs into the same situation. I have no clue what caused this error. The IDE I'm currently using is Eclipse.
The full error is:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
TaskPerf6.main(TaskPerf6.java:66)
Source:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class TaskPerf6 {
public static boolean isAlphaNumeric(String username) {
return username != null && username.matches("^[a-zA-Z0-9]*$");
}
public static boolean isAlphaNumeric1(String password) {
return password != null && password.matches("^[a-zA-Z0-9]*$");
}
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Type L to log-in or R to register.");
String choice = scan.nextLine();
File file = new File("records.txt");
FileWriter writer = new FileWriter(file);
//Register
if (choice.compareToIgnoreCase("R") == 0) {
System.out.println("Registration:");
while(true) {
try {
System.out.println("Write your username (Alphanumeric Characters Only):");
String username = scan.nextLine();
if (isAlphaNumeric(username)==true) break;
writer.write(username + "\n");
writer.close();
}
catch (java.lang.IndexOutOfBoundsException e) {
System.out.println("a");
}
catch (java.io.IOException e) {
System.out.println("");
}
}
while(true) {
try {
System.out.println("Write your password (Alphanumeric Characters Only):");
String password = scan.nextLine();
if (isAlphaNumeric1(password)==true) break;
writer.write(password + "\n");
writer.close();
}
catch (java.lang.IndexOutOfBoundsException e) {
System.out.println("a");
}
catch (java.io.IOException e) {
System.out.println("");
}
}
String line1 = Files.readAllLines(Paths.get("records.txt")).get(1);
}
}
}
You do not need two of the same methods; delete one of the isAlphaNumeric methods.
public static boolean isAlphaNumeric(String word) {
return word != null && word.matches("^[a-zA-Z0-9]*$");
}
Your problem is here:
String line1 = Files.readAllLines(Paths.get("records.txt")).get(1);
you are attempting to retrieve the second line of this file from the .get(1), when you have not wrote anything to the file.
The reason why you are not writing to a file is because you are using break whenever the username and password matches your regex pattern.
if (isAlphaNumeric(username)==true) break;
writer.write(username + "\n");
writer.close();
which will take you out of the while loop before you can write to the file.
You should practice breaking up your code for reusability. Very helpful: here is my solution for your task.
public class TaskPerf6 {
static String fileName = "records.txt";
static File file = new File(fileName);
static Scanner scan = new Scanner(System.in);
static final String REGISTER = "R";
static final String LOGIN = "L";
public static void main(String[] args){
System.out.println("Type L to log-in or R to register.");
String choice = scan.nextLine();
switch(choice.toUpperCase()) {
case REGISTER:
register();
break;
case LOGIN:
login();
break;
}
String line1 = getLineItem(0);
System.out.println(line1);
}
private static void login() {
// TODO
}
private static void register() {
while(true) {
System.out.println("Write your username (Alphanumeric Characters Only):");
String username = scan.nextLine();
if (processed(username))
break;
}
while(true) {
System.out.println("Write your password (Alphanumeric Characters Only):");
String password = scan.nextLine();
if (processed(password))
break;
}
}
private static boolean processed(String word) {
boolean success = true;
if (isAlphaNumeric(word)) {
if (!writeToFile(word)) {
System.out.println("Was unable to write to file");
success = false;
}
} else {
System.out.println("Was not alphanumeric, try again");
success = false;
}
return success;
}
private static boolean isAlphaNumeric(String word) {
return word != null && word.matches("^[a-zA-Z0-9]*$");
}
private static boolean writeToFile(String word ) {
boolean success = true;
try {
FileWriter writer = new FileWriter(file);
writer.write(word + "\n");
writer.close();
} catch (IndexOutOfBoundsException | IOException e) {
success = false;
}
return success;
}
private static String getLineItem(int i) {
String item = "";
try {
item = Files.readAllLines(Paths.get(fileName)).get(i);
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
}
first change to be done might be not closing writer in the first loop for username but in second loop for password.
while(true) {
try {
System.out.println("Write your username (Alphanumeric Characters Only):");
String username = scan.nextLine();
if (isAlphaNumeric(username)==true){
System.out.println("username correct");
writer.write(username+"\n");
break;}
} catch (java.lang.IndexOutOfBoundsException e) {System.out.println("a");}
catch (java.io.IOException e) {System.out.println("");}
}
while(true) {
try {
System.out.println("Write your password (Alphanumeric Characters Only):");
String password = scan.nextLine();
if (isAlphaNumeric1(password)==true){
System.out.println("pass correct");
writer.write(password);
writer.close();
break;
}
}
catch (java.lang.IndexOutOfBoundsException e) {System.out.println("a");}
catch (java.io.IOException e) {System.out.println("");}
}
When record.txt cannot be found and you try to get index 1 that's why you're getting the index out of bound exception. Please use the following if check:
String line1;
if(!Files.readAllLines(Paths.get("records.txt")).isEmpty())
line1 = Files.readAllLines(Paths.get("records.txt")).get(1);
I am creating a simple login program in java. Here is the code i have so far.
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class PasswordProgram {
public static String user;
public String password;
public static boolean part1Finish = false;
public File file = new File("D:/file.txt");
public FileWriter UsernameWrite;
public char[] user1;
public void part1() {
System.out.println("Please create an account: ");
Scanner input = new Scanner(System. in );
System.out.println("Type in a username: ");
String user = input.next();
System.out.println("Type in a Password: ");
String password = input.next();
try {
UsernameWrite = new FileWriter(file);
UsernameWrite.write(user);
UsernameWrite.write(password);
System.out.println(user);
UsernameWrite.close();
part1Finish = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void part2() {
Scanner scan = new Scanner(System. in );
System.out.println("Please confirm your username: ");
String usercheck = scan.next();
int PassAttempts = 5;
int UserAttempts = 5;
user1 = user.toCharArray();
user1 = password.toCharArray();
char[] usernamecheck = java.util.Arrays.copyOfRange(user1, 0, user.length());
System.out.println(usernamecheck);
do {
if (usercheck.equals(usernamecheck)) {
while (PassAttempts > 0) {
System.out.println("Please confirm your password: ");
String passcheck = scan.next();
if (passcheck.equals(password)) {
System.out.println("Thank You ");
} else if (passcheck != password && PassAttempts > 0) {
PassAttempts--;
System.out.println("That is incorrect. Please Try Again");
passcheck = scan.nextLine();
} else {
System.out.println("You have run out of Password Attempts");
break;
}
}
} else if (usercheck != user && UserAttempts > 0) {
UserAttempts--;
System.out.println("That is an incorrect username. Please Try Again");
usercheck = scan.nextLine();
} else {
System.out.println("You have run out of Username Attempts");
break;
}
} while (UserAttempts > 0);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PasswordProgram login = new PasswordProgram();
login.part1();
if (part1Finish == true) {
login.part2();
}
}
}
The problem i am getting is in the method part2. Here when I try to add the username that was saved under the variable user into a character array to use it as a range I get the error NullPointerException.
After investigating i see that when running part2 the value of user is null and therefore I get the error.
Is there a way I could do this through the FileReader method instead or how can i fix the current error I am getting ? Thank you.
Because the static field user is never assigned in part1, you get a NullPointerException when you try to use it in part2.
There are also other issues in the posted code:
why there is a file involved is unclear
you use != with String, for example in passcheck != password
you use equals between String and char[] in usercheck.equals(usernamecheck)
passcheck is assagned but never used
local variables (because of their names) are hiding some fields
UsernameWrite and UserAttempts have non conventional names (should be usernameWrite and userAttempts
You have two user variables declared, one which is static and has global scope, another which is local to part1(). When part2() is attempting to access user, it is using the static declaration, which is null. Your modifications to user in part1() are done to the local variable.
This is something called variable shadowing and should be avoided at all costs.
See the below example:
class Ideone
{
static String bla = "test1";
public static void myMethod() {
String bla = "test2";
System.out.println(bla);
}
public static void main (String[] args) throws java.lang.Exception
{
myMethod();
System.out.println(bla);
}
}
It outputs:
test2
test1
I'm doing a project for a class, but for the life of me I'm having the hardest time figuring out how to read text from a file. We have to create a traffic light that queues trucks and cars coming from North, South, East, and West. It's been a long time since I've done any coding, so I'm struggling immensely. I think it just reads the memory location. Here's my code for reading in a file.
package Project1;
import java.io.*;
import java.util.*;
public class TrafficSim {
public String input;
public TrafficSim(String input)
{
this.input = input;
readFromFile();
}
private boolean readFromFile()
{
File inputText = new File("input1.txt");
try
{
Scanner scan = new Scanner(inputText);
while(scan.hasNextLine())
{
String direction = scan.nextLine();
int num = scan.nextInt();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TrafficSim sim = new TrafficSim("input1.txt");
System.out.println(sim);
}
}
Your method readFromFile sure enough reads from a file, but then it doesn't do anything. All you do is read line by line, storing a line of text and an int in variables which are forgotten after each iteration of your while loop.
Your code System.out.println(sim) prints out whatever the toString method of your class returns, and since you didn't override that method it will print out the result of Object.toString, which is not what you want.
To put it simply, you're reading from a file but you're not doing anything with the contents that you read.
Here is what I would do....
public class TrafficSim {
private String input;
private String content;
public TrafficSim(String input) {
this.setInput(input);
this.setContent(readFromFile());
}
private String readFromFile() {
File inputText = new File(input);
StringBuilder sb = new StringBuilder();
try {
Scanner scan = new Scanner(inputText);
while (scan.hasNextLine()) {
sb.append(scan.nextLine());
}
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return sb.toString();
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public static void main(String[] args) {
TrafficSim sim = new TrafficSim("input1.txt");
System.out.println(sim.getContent());
}
}
The issue I see though is that you're not following the comments and suggestions already made. ktm5124 was pretty clear on what the problem is. At some point you're going to have to understand what is going on here and how to fix it.
I have a properties file that holds username and password which I use in my java program however I am not being able to store more than one username and password like I do in database and just select where username and password match the many rows in the database. I imagine I need to have a two-dimensional array stored in the file holding usernames and corresponding passwords but I've failed to figure out how to do it and neither has google given me a way to hold a two-dimensional array in a file yet. Here are the key/value pairs for my username and password in the file
`password=k
username=k`
And here is the code that reads them and compares with what the user inserts
`String usr = userfield.getText();
String pwd = new String(pwdfield.getPassword());
Properties config = new Properties();
InputStream is;
try {
is = new FileInputStream("config.properties");
config.load(is);
if (usr.toString().equals(config.getProperty("user").toString()) && pwd.toString().equals(config.getProperty("pass").toString())) {
new DocMenu();
lgFrame.dispose();
} else {
JOptionPane.showMessageDialog(lgFrame, "Wrong credentials try again", "Oops", JOptionPane.ERROR_MESSAGE);
}
is.close();
} catch (Exception ex) {
System.out.println(ex);
ex.printStackTrace();
}`
Could someone please tell me how to change the properties file and the code so that I am able to have multiple usernames and passwords in the file to grant access to any user as long as their username and password exist.
If you store the property name as a concatenation of some key with the username, and the password as the value like this;
#Some bad passwords
username.bob=password
username.scott=tiger
username.admin=admin
..then you can check like this;
String password = config.getProperty("username." + usr.toString());
if (password != null && password.equals(pwd.toString())) {
new DocMenu();
lgFrame.dispose();
} else {
JOptionPane.showMessageDialog(lgFrame, "Wrong credentials try again", "Oops", JOptionPane.ERROR_MESSAGE);
}
In your posted code, you have 'username' in the properties, and you are trying to read the 'user' property.
Same goes for the password.
But this will only allow you yo have one pair user/pwd. You should have a more elaborated structure in your properties file. For instance you could have
user1=pwd1
user2=pwd2
...
and then check with something like :
if (password != null && password.equals(config.getProperty(usr)){
// ok ...
}
If you have to use properties, I think there's little option beyond doing
username.1
username.2
username.3
and iterating through until you have an index that you can't find the property for (in this case, username.4).
For more complex configurations, I would investigate frameworks such as Apache Commons Config, which can handle lists of elements.
As promised, here is the HashSet serialise/deserialise code:
import java.util.*;
import java.io.*;
class UserPasswordMap{
private HashMap<String,String> userMap;
private String m_filename;
public UserPasswordMap()
{
userMap = null;
m_filename = null;
userMap = new HashMap<String,String>();
}
public UserPasswordMap(String filename, String credo)
{
try{
m_filename = filename;
File f = new File(m_filename);
userMap = new HashMap<String,String>();
if(f.exists() && (!(f.canRead() && f.canWrite()))){
System.err.println("Oops, Insufficient permissions to read/write for filename: "+m_filename);
}else{
f.createNewFile();
}
}catch(Exception e){
System.err.println(e.getMessage());
}
if(credo.equals("D")){
try{
ReadMap(filename);
}catch(Exception e){ System.err.println(e.getMessage());}
}
}
public void ReadMap(String filename) throws IOException, ClassNotFoundException
{
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
userMap = (HashMap<String,String>)ois.readObject();
fis.close();
}
public void WriteMap(String filename) throws IOException{
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userMap);
oos.close();
}
public ArrayList<String> getUsers()
{
ArrayList<String> users = new ArrayList<String>();
if(userMap == null){
return null;/*or return users*/
}else{
for(String s:userMap.keySet()){
users.add(s);
}
}
return users;
}
public ArrayList<String> getPasswords()
{
ArrayList<String> passwords = new ArrayList<String>();
if(userMap == null){
return null;/*or return users*/
}else{
for(String s:userMap.values()){
passwords.add(s);
}
}
return passwords;
}
public String getPassword(String username)
{
return userMap.get(username);
}
public void addUser(String username, String password){
userMap.put(username, password);
try{
WriteMap(m_filename);
}catch(Exception e){
System.err.println(e.getMessage());
}
}
public void saveData(){
if(m_filename == null){
System.err.println("File-Name is not supplied");
}else{
try{
WriteMap(m_filename);
}catch(Exception e){
System.err.println(e.getMessage());
}
}
}
}
And the test code:
public class Main{
private UserPasswordMap map;
public static void main(String[] args){
Main obj = new Main();
obj.init();
Scanner scan = new Scanner(System.in);
System.out.println("0. Init With Serialisation(CAN THROW ERROR)");
while(true){
System.out.println("1. Add New User");
System.out.println("2. Query Permissions");
System.out.println("3. Exit");
int data = scan.nextInt();
switch(data){
case 0: obj.initWithSerialisation();
break;
case 1: obj.addNewUser();
break;
case 2: obj.queryPerms();
break;
case 3: System.exit(0);
}
}
}
public void init()
{
map = new UserPasswordMap("try1.ser","");
}
public void initWithSerialisation()
{
map = new UserPasswordMap("try1.ser","D");
}
private Scanner scan;
public void addNewUser()
{
System.out.print("Enter User:");
scan = new Scanner(System.in);
String username = scan.nextLine();
System.out.print("Enter Pass:");
String password = scan.nextLine();
map.addUser(username, password);
}
public void queryPerms()
{
System.out.print("Enter User:");
if(scan == null){ scan = new Scanner(System.in);}
String username = scan.nextLine();
System.out.print("Enter Pass:");
String pass = scan.nextLine();
if(map.getUsers().contains(username) && map.getPassword(username).equals(pass)){
System.out.println("authenticated!");
}else{
System.out.println("Oops Wrong credentials!");
}
}
}
So I am supposed to make 3 classes and am given a 4th class to use for a user interface. One class (DBBinding) is supposed to have a String key and String value and take something like name:Alien or star: harry dean and make name or star be the "key" and the other is the "value" the next class (DBrecord) is to hold a group of these "bindings" as one record. I have chosen to keep a group of these bindings in a ArrayList. The third class(DBTable) is another ArrayList but of . I am at the point where I am reading in a line of txt from file where each line of txt is going to be one DBrecord that we know will be in correct formatting(key:value, key:value, key:value, and so on).
Where I am having trouble is within the DBrecord class. I have a method(private void addBindingToRecord(String key_, String value_)) that is called from (public static DBrecord createDBrecord(String record)) from within the DBrecord class here are each methods code.
I am having trouble with the addBindingToRecord method ... it null pointer exceptions on the first time used. I think it has to do with sytax and how I am calling the "this.myDBrecord.add(myDBBinding);"... have tried it multiple ways with same result....
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
myRecord.addBindingToRecord(temp2[0], temp2[1]);
}
}
return myRecord;
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);///Here is where my null pointer exception is.
}
I am going to post the full code of all my classes here so you have it if need to look at. Thank for any help, hints, ideas.
package DataBase;
import java.io.*;
public class CommandLineInterface {
public static void main(String[] args) {
DBTable db = new DBTable(); // DBTable to use for everything
try {
// Create reader for typed input on console
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while (true) {
int length = 0;
int selectedLength = 0;
// YOUR CODE HERE
System.out.println("\n" + length + " records (" + selectedLength + " selected)");
System.out.println("r read, p print, sa select and, so select or, da ds du delete, c clear sel");
System.out.print("db:");
line = reader.readLine().toLowerCase();
if (line.equals("r")) {
System.out.println("read");
String fname;
System.out.print("Filename:");
//fname = reader.readLine();////ADD BACK IN AFTER READ DEBUGED
// YOUR CODE HERE
fname="movie.txt";
db.readFromFile(fname);
}
else if (line.equals("p")) {
System.out.println("print");
// YOUR CODE HERE
DBTable.print();
}
else if (line.equals("da")) {
System.out.println("delete all");
// YOUR CODE HERE
}
else if (line.equals("ds")) {
System.out.println("delete selected");
// YOUR CODE HERE
}
else if (line.equals("du")) {
System.out.println("delete unselected");
// YOUR CODE HERE
}
else if (line.equals("c")) {
System.out.println("clear selection");
/// YOUR CODE HERE
}
else if (line.equals("so") || line.equals("sa")) {
if (line.equals("so")) System.out.println("select or");
else System.out.println("select and");
System.out.print("Criteria record:");
String text = reader.readLine(); // get text line from user
// YOUR CODE HERE
}
else if (line.equals("q") || line.equals("quit")) {
System.out.println("quit");
break;
}
else {
System.out.println("sorry, don't know that command");
}
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
package DataBase;
import java.util.*;
import java.io.*;
public class DBTable {
static ArrayList<DBrecord> myDBTable;
public DBTable()
{
ArrayList<DBrecord> myDBTable= new ArrayList<DBrecord>();
}
public static void addRecordToTable(DBrecord myRecord)//added static when added addRecordToTable in readFromFile
{
if(myRecord!=null)
{myDBTable.add(myRecord);}
}
public static void readFromFile(String FileName)
{
try
{
FileReader myFileReader=new FileReader(FileName);
String line="Start";
BufferedReader myBufferdReader=new BufferedReader(myFileReader);
while(line!="\0")
{
line=myBufferdReader.readLine();
if(line!="\0")
{
System.out.println(line);//TEST CODE
addRecordToTable(DBrecord.createDBrecord(line));// made addRecordToTable static.
}
}
}catch(IOException e)
{System.out.println("File Not Found");}
}
public static void print()
{
if (myDBTable==null)
{
System.out.println("EMPTY TABLE");
return;
}
else
{
for (int i=0; i<myDBTable.size(); i++)
{
System.out.println(myDBTable.get(i).toString());
}
}
}
}
package DataBase;
import java.util.*;
import java.lang.reflect.Array;
//import DataBase.*;//did not help ... ?
public class DBrecord {
boolean select;
String key;
//need some type of collection to keep bindings.
ArrayList<DBBinding> myDBrecord;
public DBrecord()
{
//DBrecord myRecord=new DBrecord();
select=false;
ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
//System.out.println(myDBBinding.toString());//for testing
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);
System.out.println(key_);//for testing
System.out.println(value_);//for testing
}
public String toString()
{
//out put key first then all values in collection/group/record. use correct formatting.
StringBuilder myStringbuilder=new StringBuilder();
for (int i=0;i<this.myDBrecord.size();i++)
{
myStringbuilder.append(myDBrecord.get(i).toString());
myStringbuilder.append(", ");
}
myStringbuilder.delete(myStringbuilder.length()-2, myStringbuilder.length()-1);//delete last ", " thats extra
return myStringbuilder.toString();
}
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
//System.out.println("HERE");//for testing
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
//System.out.println("HERE");//for testing
//for(int i=0; i<Array.getLength(temp); i++) ///for testing
//{System.out.println(temp[i]);}
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
System.out.println(temp2[0]);//for testing
System.out.println(temp2[1]);//for testing
myRecord.addBindingToRecord(temp2[0], temp2[1]);
System.out.println(temp2[0]+ " "+ temp2[1]);////test code
}
}
return myRecord;
}
}
package DataBase;
public class DBBinding {
private String key;
private String value;
public DBBinding(String key_, String value_)
{
key =key_;
value=value_;
}
public String getKey()
{return key;}
public String getValue()
{return value;}
public String toString()
{return key+": "+value;}
}
In your constructor: ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
You only create a local variable named myDbrecord and initialize it, instead of initializing the field myDBrecord.
You probably wanted instead:
myDBrecord = new ArrayList<DBBinding>();