JAVA IF Else variables - java

public void actionPerformed(ActionEvent arg0) {
String employeeInput;
String assetInput;
String userInput = txtUserInput.getText();
userInput = userInput.toLowerCase();
if (userInput.startsWith("emp")){
//String employeeInput = null;
employeeInput = userInput.replaceAll("\\s","");
txtUserInput.setText("");
JOptionPane.showMessageDialog(frame, "The Scan was " );
}else if (userInput.startsWith("u")){
assetInput = userInput;
assetInput.replaceAll("\\s","");
txtUserInput.setText("");
System.out.println("Employee ID is " + **employeeInput**); //asks for employeeInput to be declared.
JOptionPane.showMessageDialog(frame, "The Scan was " + assetInput);
I want the employeeInput to be filled and saved, untill it is replaced by another employeeInput. The problem I'm having is when getting the item input, the employeeInput is now missing. What is the way to do this?
Thank you, for your help

employeeInput is a method variable, so everytime you exit the method you will lose the reference to it.
The obvious thing to try is turn employeeInput into a member variable. Just declare it at the top of your class.
Better yet may be to persist that value to a database.

The compiler doesn't know that the first condition has already been met. Nor, do I. But, you could change
String employeeInput; // <-- may not have been initialized
to a default value (possibly even explicitly null), here the empty String "".
String employeeInput = "";

It doesn't look like your employeeInput variable is 'missing' or could be removed after any other variable is set. So its most likely you aren't initializing your variables when they're defined.
Try initializing them like
String employeeInput = ""; // or = null
String assetInput = ""; // or = null
String userInput = txtUserInput.getText().toLowerCase();
And your problem should be solved. The compiler might also be giving you a warning about this.
You might also want to try removing this txtUserInput.setText(""); line to test for problems.
Edit:
If you are trying to access this variable after your method has finished executing then it will be wiped so instead of putting it in your method declare it in your class like public class Name{
public /*static*/ String employeeInput = ""; //or null
}

Related

java.lang.IllegalArgumentException: Can not create a Path from a null string

**“Path inputPath = new Path(job.get(KnnDriver.QUERY_DIR_PROPERTY));”**//it gives out error。
if (inputPath == null)
throw new UnsupportedOperationException("ERROR: query directory not set");
job.setInputFormat(NonSplitableTextInputFormat.class);
NonSplitableTextInputFormat.addInputPath(job, inputPath);
Path outputPath = new Path(job.get(KnnDriver.RESULT_DIR_PROPERTY));
FileSystem.get(job).delete(outputPath, true);
// Change to FileOutputFormat to see output
job.setOutputFormat(TextOutputFormat.class);
TextOutputFormat.setOutputPath(job, outputPath);
KnnDriver.run(job);
}
I have taged the error in the text。
The following will be the static constant I have set in knnDriver.
public static final String QUERY_DIR_PROPERTY = "knn.query.dir";
public static final String RESULT_DIR_PROPERTY = "knn.result.dir";
public static final String THRESHOLD_PROPERTY = "knn.sim.threshold";
Instead of looking to see if the variable is null first, and then doing whatever you need, just do whatever you need as long as it's not null. This eliminates the need to check to see if a variable is "exactly" equal to something. It creates complications.
To avoid this, use an if statement that does what was stated above.
if(inputPath != null){
//Whatever you want
}else{
//However you want to catch it
}
Basically, you're not looking for the black swan anymore, but just checking that there aren't any. This approach is much less problematic and should be used instead of the way you did.

Getting the next Value in a ArrayList(Not working)

I'm trying to get the next value in a specific arraylist every time a user presses a button (using Swing).
This is my attempt at it:
private void BNextActionPerformed(java.awt.event.ActionEvent evt) {
int i = 0;
Parse p = new Parse();
temp = p.getTemp();
temp2 = p.getTemp2();
temp3 = p.getTemp3();
if (CBUniversities.getSelectedIndex() == 0) {
LNumStudents.setText("Number of students: " + temp);
Student s = p.getMacList().get(i+1);
jTextField2.setText(s.getFirstName());
TLastName.setText(s.getSurName());
jTextArea1.setText(s.getAddress());
i++;
}
}
Where Parse is a class, containing getter methods for 3 integerstemp,temp2,temp3, and a getter for an ArrayList.
Student s is an object of the Student class, where every student has a firstname, surname and address (initialized in a constructor).
When this if statement is executed it displays a students info in the specified fields, however, this only works for the first two students. After that, the i value never seems to increase?
I tried to place a println check to see it's value during the if statement, but it only changes once, oddly enough.
I also tried to make this into a for loop, yet the value again only seems to change once (of i).
Parse has this getter method I'm using
public ArrayList<Student> getMacList() {
return mac;
}
Also CBUniversities is a variable as such:
private javax.swing.JComboBox CBUniversities;
I'm not sure what's gone wrong here, any ideas?
You declared i within the scope of a method, so every time your method executes it reinitializes i.
Instead, declare an instance variable by putting private int i = 0; outside of your method, but still within the class scope.

Returning the needed value in a class - Java

I am confused about returning the needed value. Here is a part of my code:
public class StrNum {
public static int getInt(String input) {
String str = new String(input);
int result;
if (str.startsWith("b")) {
str = str.substring(1);
result = Integer.parseInt(str, 2);
}
else if (str.startsWith("x")) {
str = str.substring(1);
result = Integer.parseInt(str, 16);
}
Now, what I need to return is result. When I write return result;, it asks me to initialize the variable (and I am aware that it hasn't been initialized). When I use return result inside of the if statements, Eclipse tells me that I have to return a value.
Where am I being stupid here? I would appreciate a good explanation.
What will the method getInt() return if Str doesn't start with neither "b" or "x"? That would be an error because result is not being initialized. You could solve this by intializing result with a value that you would like to return in that case:
int result = -1; // for example
Edit:
Since you want to use input to determine if the number will be parsed as binary or hexadecimal, I would recommend you to add an else statement to parse the number in base 10 as default:
if (...)
// ...
else if (...)
// ...
else
result = Integer.parseInt(Str);
Note:
Try to follow Java naming conventions. Use names like someVar for variables/methods and use names like SomeClass for classes.
It's not necessary to create a new string instance Str, unless you are going to use the original input later in the same method.
To create a String with the same content you can simply do
String str = input;
Try
int result = 0;
You must initialize variables before returning them or in other words do result = . The variable must always be initialized no matter what code path your application takes.
Your can either return the result from if and also from else, provided you are not doing additional calculations after the else block.
or simply initialize result = 0, it will change anyways before you return.

How to check the type of variable that would store a given value (contained in a String)?

How Can I check the Type of a variable . in this way :
Pseudo Code :
do{
VARIABLE = JOptionPane.showInputDialog(null,"X = ");
}while(VARIABLE != Integer);
Set_X(VARIABLE);
In this case, your VARIABLE variable will be of type String.
You can try/catch Integer.valueOf on that variable to get its Integer value.
If a NumberFormatException is thrown, it means the user input cannot be converted to Integer.
For instance (draft code):
// initializing Integer interpretation
Integer input = null;
// infinite loop - breaks only once user has entered a valid integer-parseable value
while (true) {
// trying to convert user input after showing option pane
try {
input = Integer.valueOf(JOptionPane.showInputDialog(null, "X = "));
// breaking infinite loop
break;
}
// conversion unsuccessful
catch (NumberFormatException nfe) {
// TODO handle any error message if you need to
}
}
You can't check it for any type, obviously. You can, however, try to parse it using parsers of known types and, if parsing succeeds for one, cast it to that type and move on.
For example, the integer-parsing helper function is Integer.parseInt(String). Unfortunately, it throws an exception on failure (which will make your code ugly and slow at that point) and I'm not sure there are alternatives in the base library (equivalent to, say, C#'s TryParse).
The following example uses a Class object to print the class name of an object:
void printClassName(Object obj) {
System.out.println("The class of " + obj +
" is " + obj.getClass().getName());
}
Hence this code will perform the check you require:
do{
VARIABLE = JOptionPane.showInputDialog(null,"X = ").getClass().getName();
}while(!(VARIABLE.equals("java.lang.Integer"));

Object not recognized outside if-else clauses

In the if-else branches I declared two different PrintStream objects with the same name. However, when I use the PrintStream object later the compiler says that it "cannot find symbol". Why doesn't it see the object I created? The object works withing the if-else branch it was declared in. Here's the code:
System.out.println("Welcome. Would you like to continue a previous adventure, or begin anew?\n(type: new or old)");
status = scan.nextLine();
if(status.equals("new")) {
System.out.println("What do you call yourself?");
name = scan.nextLine();
System.out.println("And what shall be the title of your saga, after you are gone?");
game = scan.nextLine();
System.out.println("Very well. Prepare yourself, for this is the beginning of your end...\n...\n...\nAre you ready?");
status = scan.nextLine();
System.out.println("Not that it matters. Let us begin.");
status = scan.nextLine();
File file = new File(game + ".txt");
PrintStream print = new PrintStream(file);
print.println(name);
old = false;
} else {
System.out.println("So you're still alive? What was the title of your tale?");
game = scan.nextLine();
File file = new File(game + ".txt");
Scanner gscan = new Scanner(file);
String save = "";
while (gscan.hasNextLine()) {
save += gscan.nextLine();
save += "\n";
}
System.out.println(save);
PrintStream print = new PrintStream(file);
print.println(save);
old = true;
name = scan.nextLine();
}
if(old) {
}
print.println("beans");
You need to declare the variable outside the if statement, and then assign it in the two branches, like this:
PrintStream print;
if (status.equals("new")) {
...
print = new PrintStream(file);
} else {
...
print = new PrintStream(file);
}
Better yet, you can set the file inside the if, and then create PrintStream after the conditional:
if (status.equals("new")) {
...
} else {
...
}
File file = new File(game + ".txt");
PrintStream print = new PrintStream(file);
You are experiencing a scoping problem. You need to declare it outside the if-else statement if you want to use it outside the if-else statement.
There are different levels of scoping in Java programs. A scope is generally defined by a set of curly braces. However, there is also public, private, and protected types that allow for use of more global variables than just inside their braces.
Each of these scopes can have their own variables that are not available elsewhere.
Take a look at these two pieces of code:
String s;
if ( foo ) {
s = "one";
} else {
s = "two";
}
if ( foo ) {
String s = "one";
} else {
String s = "two";
}
In the first one, s is available after the if/else. In the second, s is only available within the {} (if/else blocks). Each block happens to have a variable with the same name, but it isn't the same variable. And it isn't available later.
What happens in a scope stays in the scope.
if(some condition)
{
int x = 10;
}
System.out.println(x);
This will not work because the scope of x is limited only till the if block. If you want it to live outside the if block, then declare it outside the if block.
Why define PrintStream print twice? You need to define it only once in this case outside the if.

Categories