I am making a code generator that makes a new code and then querys a database to see if it exists. If it does, try again to make a different code. If it doesn't exist, add it into the database. But when I add the one code into the database, the query adds 3 different rows with 3 different values. One of the values, is the one supposed to be added, and the other two I don't know where they come from. Why is it inserting 3 when I only set it to add one. My full class file is:
package com.xium.accesscode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.ThreadLocalRandom;
import com.xium.log.ServerLogger;
import com.xium.sql.DBConnections;
import com.xium.utils.StringUtils;
public class NewAccessCode {
static String AccessCodeDBuser = "root";
static String AccessCodeDBpass = "";
static String AccessCodeDBhost = "localhost";
static String newAccessCode;
static String randS;
static String randFinal;
static int min = 000000000;
static int max = 999999999;
static int randI;
public static void AccessCode() {
if(newAccessCode() == 0) {
ServerLogger.writeLog("[ALERT] Database Error");
} else if(newAccessCode() == 1) {
//Reruns the code generator, to make a unique code
newAccessCode();
} else if(newAccessCode() == 2) {
ServerLogger.writeLog("[NOTE] New Access Code: " + newAccessCode);
}
}
/*
* Return Codes:
* 0 - Database Error
* 1 - Code Already Exists
* 2 - New Access Code Added
*/
private static int newAccessCode() {
genAccessCode();
newAccessCode = randFinal;
//Does it already exist?
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet results = null;
String statement = "SELECT count(*) FROM `xium`.`accesscodes` WHERE `accesscode`='" + newAccessCode + "'";
String statement2 = "INSERT INTO `xium`.`accesscodes` (`accesscode`, `used`, `assignedto`) VALUES ('" + newAccessCode + "', '0', '')";
try {
connection = DBConnections.getAccessCodeDB(AccessCodeDBuser, AccessCodeDBpass, AccessCodeDBhost);
preparedStatement = connection.prepareStatement(statement);
results = preparedStatement.executeQuery();
results.next();
if(results.getInt(1) == 0) {
} else if(results.getInt(1) >= 1) {
return 1;
}
connection = DBConnections.getAccessCodeDB(AccessCodeDBuser, AccessCodeDBpass, AccessCodeDBhost);
preparedStatement = connection.prepareStatement(statement2);
preparedStatement.executeUpdate();
return 2;
} catch (SQLException e) {
return 0;
}
}
private static String genAccessCode() {
randI = ThreadLocalRandom.current().nextInt(min, max + 1);
randS = randI + "";
randFinal = StringUtils.toMD5(randS);
return randFinal;
}
}
Every time you run your AccessCode() function, the if statements are running the statement as well. So don't do:
if(newAccessCode() == 0)
You should make a new integer value set equal to the value of your newAccessCode() function and then check the value of the int.
So:
int returnValue = newAccessCode();
Then check the value of the returnValue.
if(returnValue == 0)
That should fix your problem.
There is a call to newAccessCode() method in AccessCode() static method three times.
Change that to
public static void AccessCode() {
int newAccessCodeReturn = newAccessCode();
if(newAccessCodeR`enter code here`eturn == 0) {
ServerLogger.writeLog("[ALERT] Database Error");
} else if(newAccessCodeReturn == 1) {
//Reruns the code generator, to make a unique code
newAccessCode();
} else if(newAccessCodeReturn == 2) {
ServerLogger.writeLog("[NOTE] New Access Code: " + newAccessCode);
}
}
You're calling newAccessCode() repeatedly in your if/else if code. Every time you do this it inserts into the DB. Call it once and save the result in a variable.
int result = newAccessCode();
if(result == 0) {
ServerLogger.writeLog("[ALERT] Database Error");
} else if(result == 1) {
//Reruns the code generator, to make a unique code
newAccessCode();
} else if(result == 2) {
ServerLogger.writeLog("[NOTE] New Access Code: " + newAccessCode);
}
or use a switch statement:
switch (newAccessCode()) {
case 0:
ServerLogger.writeLog("[ALERT] Database Error");
break;
case 1:
//Reruns the code generator, to make a unique code
newAccessCode();
break;
case 2:
ServerLogger.writeLog("[NOTE] New Access Code: " + newAccessCode);
break;
}
Related
I'm new to Java, and i'm trying to create an automatic working shift schedule.
I want the code to mix four different employees to handle a morning shift and afternoon shift every work day.
I have made some code that just pick a random employee into a shift:
import java.util.Arrays;
import java.util.Random;
public class CreateNewShift {
public static void main(String[] args) {
int startWeek = 30; //Which week would start from?
int endWeek = 32; //which week will you end on?
generateShift(startWeek, endWeek);
}
private static void generateShift(int startWeek, int endWeek) {
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
for (int x = 0; x <= (endWeek - startWeek); x++) { //This is counting the number of weeks
System.out.println("\nWeek: " + (startWeek+x));
for (int i = 1; i <= 5; i++) { //this is finding the next working shift day
morningShift = p.chooseRandomEmployee(Employees);
afternoonShift = p.chooseRandomEmployee(Employees);
if (i == 1) {
System.out.println("Mon: " + morningShift + " + " + afternoonShift);
}
else if (i == 2) {
System.out.println("Tue: " + morningShift + " + " + afternoonShift);
}
else if (i == 3) {
System.out.println("Wed: " + morningShift + " + " + afternoonShift);
}
else if (i == 4) {
System.out.println("Thu: " + morningShift + " + " + afternoonShift);
}
else {
System.out.println("Fri: " + morningShift + " + " + afternoonShift);
}
}
}
}
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
However, I now want the code to handle more restictions.
So i'm currently trying to add the option for the employees to choose some specific days that they dont want to have a shift. I have done this by adding this code to the Employee class:
public class Employee {
boolean monShift = true;
boolean tueShift = true;
boolean wedShift = true;
boolean thuShift = true;
boolean friShift = true;
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
And then i had tried to create new objects in my main class:
private static void generateShift(int startWeek, int endWeek) {
Employee Employee1 = new Employee("Employee1");
Employee Employee2 = new Employee("Employee2");
Employee Employee3 = new Employee("Employee3");
Employee Employee4 = new Employee("Employee4");
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
....
Quetions:
How can I improve my code in the Employee class to do a check if the random chosen employee have
monShift = true;
I have tried something like this, but i know it will not work, (and does not work either):
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
**if (("Employee" + randomNumber).monShift == false) {**
// Go back and try find a new random employee
}
else {
return Employees[randomNumber];
}
}
}
So i need a way to make my code dynamic to know which object (employee) it has to check if they are available that specific day or not.
Feel free to ask for a deepening if my question is not clear.
Since this i my first question on this forum, I also appriciate feedback if my question and thoughts are too long, or any other comments.
I dont think that putting the chooseRandomEmployee() function inside the Employee object is a good idea beacuse is not a part of the employee, is not an "action" of it. I think you shiudl put it outside but I want to respect your decision so shoudl check the do while loop.
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
int randomNumber;
do {
//Generate a new random number
Random r = new Random();
randomNumber = r.nextInt(Employees.length);
//The line under is the same that saying "If monSift == false return to
//the beginning and start again generating a new number"
} while ("Employee" + randomNumber).monShift == false);
return Employees[randomNumber];
}
}
My return statement is not working while all values up until the get statement (i.e. the set, variables, etc) are working, if forced to a value the display works.
if (Pasta.isChecked() && Pork.isChecked() && Tomato.isChecked() && Carrots.isChecked() && TomatoPaste.isChecked()) {
// RecipeCodes recipe1 = new RecipeCodes();
//recipe1.setRecipeCode(1);
setRecipeCode(1);
getRecipecode();
//Recipecode = 1;
Log.i("INTERNAL CHECK", "RCODE ~" + Recipecode);
break;
public void setRecipeCode(int C) {
Recipecode = C;
Log.i("SETRECIPECODETEST", "RECIPE CODE ~ " + Recipecode);
}
public int getRecipecode(){
return Recipecode;
}
Here is my code for the class that displays based on the "RecipeCode" variable
Recipes temp = new Recipes();
RecipeCodes RDisplay = new RecipeCodes();
//temp.getRecipeCode();
if(temp.getRecipecode() == 1){
RDesc.setText("Italiano Sausage");
//Log.i("WITHINIF","RCODE INTERNAL ~ " + temp.getRecipeCode());
} else {
RDesc.setText("test");
//Log.i("TEST","RCODE WITHIN DISPLAY ~ " + RDisplay.getRecipeCode());
}
(I've done a lot of editing and commenting out of lines so if there's minor syntax errors my bad).
This works:
class Recipe {
private int recipecode;
public void setRecipeCode(int c) {
recipecode = c;
}
public int getRecipecode() {
return recipecode;
}
public static void main(String[] args)
{
Recipe temp = new Recipe();
temp.setRecipeCode(1);
System.out.println(temp.getRecipecode());
}
}
The issue is definitely within the scope but, I am having issues figuring out why since I declared the variables that are storing the information outside the loop
public Member searchMember (String email) {
int Sid = 0;
String name ="";
String adr = "";
String phone = "";
String email2 = "";
String pass = "";
boolean status =false;
Member a = new Member(name,adr,phone,email2,pass);
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://compsi:3306/mcrowley","mcrowley","700463874");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
System.out.println(email);
String query = "Select id,name,address,phoneNum,email,password,LoginStatus From member WHERE email Like '%"+email+"%' ";
ResultSet results = stmt.executeQuery(query);
System.out.println("Before while loop");
int count = 0;
while (results.next() || count == 0 ) {
if (count == 0)
results.absolute(1);
System.out.println("Start while loop");
Sid = results.getInt(1);
//System.out.println(Sid+" this is test in jdbc");
name = results.getString(2);
//System.out.println(name+" this is test in jdbc");
adr = results.getString("address");
phone = results.getString("phoneNum");
email2 = results.getString("email");
pass = results.getString("password");
int stat = results.getInt("loginStatus");
if (stat == 0) {
status = false;
}
else {
status = true;
}
count++;
if (!results.next()) {
a.setName(name);
a.setAddress(adr);
a.setPhoneNumber(phone);
a.setEmail(email2);
a.setPassword(pass);
a.setId(Sid);
a.setStatus(status);
return a;
}
}
System.out.println("After while loop");
a.setName(name);
a.setAddress(adr);
a.setPhoneNumber(phone);
a.setEmail(email2);
a.setPassword(pass);
a.setId(Sid);
a.setStatus(status);
//create object & print
stmt.close();
con.close();
return a;
}
catch (Exception e) {
e.printStackTrace();
}
return a;
}
So basically it sounds like you need a refresher course about the scope of variables.
Essentially, you're not coming here with broken code that you want to know how to fix. But instead you're being rolling because you think it ought not to work.
Here's how I remember it: every scope has access to variables declared in itself as well as the scope that is its direct parent. That is, the parent scope can't read and modify any of its soon-to-be cheers.
So basically, the answer to your question is that your intuition is incorrect. Variable scope doesn't function in the way you thought it did.
I am working on a project in which I have two tables in a different database with different schemas. So that means I have two different connection parameters for those two tables to connect using JDBC-
Let's suppose below is the config.property file-
TABLES: table1 table2
#For Table1
table1.url: jdbc:mysql://localhost:3306/garden
table1.user: gardener
table1.password: shavel
table1.driver: jdbc-driver
table1.percentage: 80
#For Table2
table2.url: jdbc:mysql://otherhost:3306/forest
table2.user: forester
table2.password: axe
table2.driver: jdbc-driver
table2.percentage: 20
Below method will read the above config.property file and make a ReadTableConnectionInfo object for each tables.
private static HashMap<String, ReadTableConnectionInfo> tableList = new HashMap<String, ReadTableConnectionInfo>();
private static void readPropertyFile() throws IOException {
prop.load(Read.class.getClassLoader().getResourceAsStream("config.properties"));
tableNames = Arrays.asList(prop.getProperty("TABLES").split(" "));
for (String arg : tableNames) {
ReadTableConnectionInfo ci = new ReadTableConnectionInfo();
String url = prop.getProperty(arg + ".url");
String user = prop.getProperty(arg + ".user");
String password = prop.getProperty(arg + ".password");
String driver = prop.getProperty(arg + ".driver");
double percentage = Double.parseDouble(prop.getProperty(arg + ".percentage"));
ci.setUrl(url);
ci.setUser(user);
ci.setPassword(password);
ci.setDriver(driver);
ci.setPercentage(percentage);
tableList.put(arg, ci);
}
}
Below is the ReadTableConnectionInfo class that will hold all the table connection info for a particular table.
public class ReadTableConnectionInfo {
public String url;
public String user;
public String password;
public String driver;
public String percentage;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
}
Now I am creating ExecutorService for specified number of threads and passing this tableList object to constructor of ReadTask class-
// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
service.submit(new ReadTask(tableList));
}
Below is my ReadTask that implements Runnable interface in which each thread is supposed to make a connection for each tables.
class ReadTask implements Runnable {
private final HashMap<String, XMPReadTableConnectionInfo> tableLists;
public ReadTask(HashMap<String, ReadTableConnectionInfo> tableList) {
this.tableLists = tableList;
}
#Override
public void run() {
int j = 0;
dbConnection = new Connection[tableLists.size()];
statement = new Statement[tableLists.size()];
//loop around the map values and make the connection list
for (ReadTableConnectionInfo ci : tableLists.values()) {
dbConnection[j] = getDBConnection(ci.getUrl(), ci.getUser(), ci.getPassword(), ci.getDriver());
statement[j] = dbConnection[j].createStatement();
j++;
}
while (System.currentTimeMillis() <= 60 minutes) {
/* Generate random number and check to see whether that random number
* falls between 1 and 80, if yes, then choose table1
* and then use table1 connection and statement that I made above and do a SELECT * on that table.
* If that random numbers falls between 81 and 100 then choose table2
* and then use table2 connection and statement and do a SELECT * on that table
*/
ResultSet rs = statement[what_table_statement].executeQuery(selectTableSQL);
}
}
}
Currently I have two tables, that means each thread will make two connections for each table and then use that particular table connection for doing SELECT * on that table depending on the random generation number.
Algorithm:-
Generate Random number between 1 and 100.
If that random number is less than table1.getPercentage() then choose table1
and then use table1 statement object to make a SELECT sql call to that database.
else choose table2 and then use table2 statement object to make a SELECT sql call to that database.
My Question-
I am having hard time in figuring out how should apply the above algorithm and how should I compare the random number with each tables percentage and then decide which table I need to use and after that figure out which table connection and statements I need to use to make a SELECT sql call.
So that means I need to check getPercentage() method of each table and them compare with the Random Number.
Right now I have only two tables, in future I can have three tables, with percentage distribution might be as 80 10 10.
UPDATE:-
class ReadTask implements Runnable {
private Connection[] dbConnection = null;
private ConcurrentHashMap<ReadTableConnectionInfo, Connection> tableStatement = new ConcurrentHashMap<ReadTableConnectionInfo, Connection>();
public ReadTask(LinkedHashMap<String, XMPReadTableConnectionInfo> tableList) {
this.tableLists = tableList;
}
#Override
public run() {
int j = 0;
dbConnection = new Connection[tableLists.size()];
//loop around the map values and make the connection list
for (ReadTableConnectionInfo ci : tableLists.values()) {
dbConnection[j] = getDBConnection(ci.getUrl(), ci.getUser(), ci.getPassword(), ci.getDriver());
tableStatement.putIfAbsent(ci, dbConnection[j]);
j++;
}
Random random = new SecureRandom();
while ( < 60 minutes) {
double randomNumber = random.nextDouble() * 100.0;
ReadTableConnectionInfo table = selectRandomConnection(randomNumber);
for (Map.Entry<ReadTableConnectionInfo, Connection> entry : tableStatement.entrySet()) {
if (entry.getKey().getTableName().equals(table.getTableName())) {
final String id = generateRandomId(random);
final String selectSql = generateRandomSQL(table);
preparedStatement = entry.getValue().prepareCall(selectSql);
preparedStatement.setString(1, id);
rs = preparedStatement.executeQuery();
}
}
}
}
private String generateRandomSQL(ReadTableConnectionInfo table) {
int rNumber = random.nextInt(table.getColumns().size());
List<String> shuffledColumns = new ArrayList<String>(table.getColumns());
Collections.shuffle(shuffledColumns);
String columnsList = "";
for (int i = 0; i < rNumber; i++) {
columnsList += ("," + shuffledColumns.get(i));
}
final String sql = "SELECT ID" + columnsList + " from "
+ table.getTableName() + " where id = ?";
return sql;
}
private ReadTableConnectionInfo selectRandomConnection(double randomNumber) {
double limit = 0;
for (ReadTableConnectionInfo ci : tableLists.values()) {
limit += ci.getPercentage();
if (random.nextDouble() < limit) {
return ci;
}
throw new IllegalStateException();
}
return null;
}
}
You could think of it as a loop over the available connections, something like the following:
public run() {
...
Random random = new SecureRandom();
while ( < 60 minutes) {
double randomNumber = random.nextDouble() * 100.0;
ReadTableConnectionInfo tableInfo = selectRandomConnection(randomNumber);
// do query...
}
}
private ReadTableConnectionInfo selectRandomConnection(double randomNumber) {
double limit = 0;
for (ReadTableConnectionInfo ci : tableLists.values()) {
limit += ci.getPercentage();
if (randomNumber < limit) {
return ci;
}
throw new IllegalStateException();
}
As long as randomNumber has a maximum value of less then sum(percentage), that'll do the job.
One other thing I thought of: if you're going to end up having so many possible queries that the a looping lookup becomes an issue, you could build a lookup table: create an array such that the total size of the array contains enough entries so that the relative weightings of the queries can be represented with integers.
For your example of three queries, 80:10:10, have a 10-entry array of ReadTableConnectionInfo with eight references pointing to table1, one to table2, and one to table3. Then simply scale your random number to be 0 <= rand < 10 (eg (int)(Math.random() * 10), and use it to index in to your array.
Regardless of how many tables you have, their percentages will always add up to 100. The easiest way to conceptualize how you would choose is to think of each table as representing a range of percentages.
For instance, with three tables that have the percents you mentioned (80%, 10%, 10%), you could conceptualize them as:
Random Number
From To == Table ==
0.0000 0.8000 Table_1
0.8000 0.9000 Table_2
0.9000 1.0000 Table_3
So, generate a Random # between 0.0000 and 1.0000 and then go down the ordered list and see which range fits, and therefore which table to use.
(BTW: I'm not sure why you have two connections for each table.)
You can build a lookup table which contains the table name and its weight:
class LookupTable {
private int[] weights;
private String[] tables;
private int size = 0;
public LookupTable(int n) {
this.weights = new int[n];
this.tables = new String[n];
}
public void addTable(String tableName, int r) {
this.weights[size] = r;
this.tables[size] = tableName;
size++;
}
public String lookupTable(int n) {
for (int i = 0; i < this.size; i++) {
if (this.weights[i] >= n) {
return this.tables[i];
}
}
return null;
}
}
The code to initialize the table:
LookupTable tr = new LookupTable(3);
// make sure adds the range from lower to upper!
tr.addTable("table1", 20);
tr.addTable("table2", 80);
tr.addTable("table3", 100);
The test code:
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < 10; i++) {
// r.nextInt(101) + 1 would return a number of range [1~100].
int n = r.nextInt(101) + 1;
String tableName = tr.lookupTable(n);
System.out.println(n + ":" + tableName);
}
I asked another question the other day about getting keyboard input while within a swing GUI--actually MCR input. One user found a low-level keyboard hook someone wrote. Very cool, and it mostly works. I had to learn some new things to implement it (always happy to do that), and tbh I may not be fully understanding what's going on.
Thing is, and I'll post the code below, it now runs through a while loop (while success == false, in CardRead.java) twice when I implement the thread for the keyboard hook. If I hard code sample data it only runs through once. If I delete the keyboard hook and use a normal Scanner.nextLine() (which means I have to click in the console to provide input to the application), it only runs through once. Start a new thread with an observer for keyboard input? Twice. I don't understand why, or how to fix it. I'd be happy with just understanding exactly what's going on-- if one of you all show me how to fix it, I'll be ecstatic.
Here's the code:
CardRead.java
public class CardRead {
public static String raw_card_data;
int readcount = 1;
String[] tracks = new String[2];
String[] tracks_final = new String[2];
public static void main()
{
// This doesn't happen until after card is swiped, dunno why.
//GUI.outputArea.setText(GUI.outputArea.getText() + "\n\n Scan card \n");
boolean success = false;
while (success == false)
{
//raw_card_data = "%test?;testing?"; // <-- using this, runs thru once
// using THIS, runs through twice.
// create an event source - reads from stdin
final KB_EventSource evSrc = new KB_EventSource();
// create an observer
final KB_RespHandler respHandler = new KB_RespHandler();
// subscribe the observer to the event source
evSrc.addObserver( respHandler );
// starts the event thread
Thread kb_thread = new Thread(evSrc);
kb_thread.start();
// sleep until card swiped
while (raw_card_data == null)
{
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
System.out.println(raw_card_data);
// Tokenize raw_card_data
StringTokenizer tokenizer = new StringTokenizer(raw_card_data, "?");
int i = 0;
do
{
tracks[i] = tokenizer.nextToken();
System.out.println(i + ": " + tracks[i]);
i++;
}
while (tokenizer.hasMoreTokens());
//System.out.println(track1);
//System.out.println(track2);
tracks_final[0] = tracks[0].substring(1,tracks[0].length());
if (tracks[1] != null)
{
tracks_final[1] = tracks[1].substring(1,tracks[1].length());
}
if ( (readcount <= 5) && ( (tracks_final[0].equals("E") || tracks_final[0].equals(null) ) || (tracks_final[1].equals("E") || tracks_final[1].equals(null)) ) )
{
GUI.notout.setText("Card Read Unsuccessful. Scan Again.");
GUI.outputArea.setText(GUI.outputArea.getText() + "Card read unsuccessful. Scan again. \n");
success = false;
readcount++;
}
else if (readcount <= 5)
{
GUI.notout.setText("Card Successfully Read");
GUI.outputArea.setText(GUI.outputArea.getText() + "\n Success! \n");
GUI.outputArea.setText(GUI.outputArea.getText() + "Track 1 = " + tracks_final[0] + "\n");
GUI.outputArea.setText(GUI.outputArea.getText() + "Track 2 = " + tracks_final[1] + "\n");
success = true;
} // end if else chain
} // end while success == false
} // end public void main
} // end class CardRead
KB_RespHandler.java
import java.util.Observable;
import java.util.Observer;
public class KB_RespHandler implements Observer
{
private String resp;
public void update (Observable obj, Object arg)
{
if (arg instanceof String)
{
resp = (String) arg;
CardRead.raw_card_data = resp;
}
}
}
KB_EventSource.java
import de.ksquared.system.keyboard.*;
import java.util.Observable;
public class KB_EventSource extends Observable implements Runnable
{
public static String temp = "";
public static String output = "";
public void run()
{
new GlobalKeyListener().addKeyListener(new KeyAdapter()
{
#Override public void keyPressed(KeyEvent event)
{
switch(event.getVirtualKeyCode())
{
case KeyEvent.VK_0:
if (event.isShiftPressed() == true)
temp += ")";
else if (event.isShiftPressed() == false)
temp += "0";
break;
case KeyEvent.VK_1:
if (event.isShiftPressed() == true)
temp += "!";
else if (event.isShiftPressed() == false)
temp += "1";
break;
/*insert processing for other keys here*/
case KeyEvent.VK_SPACE:
if (event.isShiftPressed() == true)
temp += " ";
else if (event.isShiftPressed() == false)
temp += " ";
break;
case KeyEvent.VK_RETURN:
/*if (event.isShiftPressed() == true)
temp += "\n";
else if (event.isShiftPressed() == false)
temp += "\n";*/
setChanged();
notifyObservers(temp);
//clearChanged();
break;
} // end switch (event.getVirtualKeyCode())*/
} // end public void keyPressed
});
while(true)
try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
So, I don't know what's going on. I was thinking maybe I need to stop the thread kb_thread after receiving input, but I can't find any way to do that. thread.stop() and thread.destroy() are deprecated and Eclipse and Google tell me not to use them. And that might not even be what I need to do anyway.
The comment in "CardRead.java" says "which upon success will change success = true".
Does this mean that it might fail, so it won't change success?
If that's true then raw_card_data would still be non-null, and it would try again.
I'm assuming that you resetting raw_card_data to null again at some point.
On another point, this:
if (event.isShiftPressed() == true)
temp += ")";
else if (event.isShiftPressed() == false)
temp += "0";
can be simplified to:
if (event.isShiftPressed())
temp += ")";
else
temp += "0";