Variable might not have been initialized? - java

I have the following code for a conversion program:
private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {
int type, value;
double conversion;
String output;
type = Integer.parseInt(conversionchoiceInput.getText());
value = Integer.parseInt(valueInput.getText());
if (type == 1)
{
conversion = inchesToCentimetres(value);
output = value + " inches = " + Math.round(conversion) + " centimetres";
}
else if (type == 2)
{
}
else if (type == 3)
{
}
else if (type == 4)
{
}
outputLabel.setText(output);
}
It says "variable output might not have been initiaized" when I already have?
Thanks!

The problem is that output needs to be initialised no matter what execution path the program takes. It is only initialised in the if path. Therefore, you need to give it a default value at the start (of empty string or something) or set it in all branches.
String output = "";
or
if (type == 1)
{
conversion = inchesToCentimetres(value);
output = value + " inches = " + Math.round(conversion) + " centimetres";
}
else if (type == 2)
{
output = "";
}
else if (type == 3)
{
output = "";
}
else if (type == 4)
{
output = "";
}
Naturally, the first option is the best.

If type != 1, then output isn't initialized. And even if you give output a value in each of the if branches (1, 2, 3, 4) output might not have been initialized, as if type < 1 or > 4 it still has no value.

You have just declared the variable there which is different from initializing it.

Related

Jmeter - Creating a new variable if variable already exists using Java

I'm using Jmeter and want to use Java to update variables,
I have a variable called XXVONO which stores values and adds a number suffix when executed in a loop. Example:
XXVONO_1 = value1
XXVONO_2 = value2
XXVONO_3 = value3
These variables contains values which are automatically stored when the loop is executed. However, I am trying to make a code which checks if the variable is empty or not, If true, it will save the new values, where if false, it will create a new variable (XXVONO_4) and save the value there without overwriting the existing variables.
How would I go about doing this? Do I use a while loop?
if (vars.get("VONO_2") != "") {
if (vars.get("XXVONO_" + vars.get("aps200_count_3")) == "") {
vars.put("XXVONO_" + vars.get("aps200_count_3"), vars.get("VONO_2"));
vars.put("XXJRNO_" + vars.get("aps200_count_3"), vars.get("JRNO_2"));
} else {
while (vars.get("XXVONO_" + vars.get("aps200_count_3")) != "") {
vars.put("new_count", vars.get("aps200_count_3"));
Integer temp = Integer.parseInt(vars.get("new_count")) + 1;
vars.put("new_count", temp.toString());
}
vars.put("XXVONO_" + vars.get("new_count"), vars.get("VONO_2"));
vars.put("XXJRNO_" + vars.get("new_count"), vars.get("JRNO_2"));
}
}
You can try using a map instead of creating a variables at runtime
Map<String,Object> map = new HashMap<>();
Inside the loop
if(map.get("DynamicVariableName")!=null){
map.put("DynamicVariableName"+autogeneratedNumberSuffix,ValueToBeStored)
}
else{
map.put("DynamicVariableName",ValueToBeStored)
}
What you could do is use an if/else statement:
if (XXVONO_1 == null)
{
XXYVONO_1 = //Insert data here
}
else if (XXVONO_2 == null)
{
XXVONO_2 = //Insert data here
}
else if (XXVONO_3 == null)
{
XXVONO_3 == //Insert data here
}
else
{
XXVONO_4 == //Insert data here
}
Of course, you can keep adding variables.
If there is no limit to the number of variables, try this:
HashMap<String, String> XXVONO = new HashMap<String, Integer>();
for (i = 1; i <= /*Number of variables*/; i += 1; i++) {
if (XXVONO["XXVONO_" + i] == null) {
XXVONO.put("XXVONO_" + i, /*insert data here*/);
}
}

specifying the path for input data and output data

I am new in java and I have to use the code below but the code it does work because I have to specifying the path for input data and output data. The code is got it from the internet. please help me
class Svm_scale
{
private BufferedReader rewind(BufferedReader fp, String filename) throws IOException
{
fp.close();
return new BufferedReader(new FileReader(filename));
}
private void output_target(double value)
{
LnCount++;
if(y_scaling)
{
if(value == y_min)
value = y_lower;
else if(value == y_max)
value = y_upper;
else
value = y_lower + (y_upper-y_lower) *
(value-y_min) / (y_max-y_min);
}
formatterscaled.format(value+" ");
System.out.println(" Line Number "+LnCount + " ");
}
private void output(int index, double value)
{
count++;
double Threshold1=0,Threshold2=0;
Threshold1= Avg[index]+(STDV[index]/2);
Threshold2= Avg[index]-(STDV[index]/2);
if(value > Threshold1 )
value = 2;
else if(value < Threshold2 )
value = -2;
else
value = 0;
formatterscaled.format( formatter.format(value) + ",");
// System.out.println(" Counter "+count);
// }
}
String save_filename =Save1; // = null?
String restore_filename =null;
String scale_data_filename =Disc; // set this to the path where the output should be stored, e.g. = "C:\\temp\\scaled";
String data_filename =Libsvm; // set this to the path where the input can be get, e.g. = "C:\\temp\\inputdata"
These are the Strings you need to adapt in order that the program can read and write. Save1, Disc, Libsvm are not in your code, so it can only be guessed where they come from.
data_filename and scale_data_filename are required. save_filename seems to be optional and may be set to null.

Set int value in conditional statement after declaring string

I have a string (breakmsg) that I would like to be the same for every if statement, with an integer value that needs to change depending on what it is declared as inside the if statement. How would I go about changing the value of the value variable after I have already declared the breakmsg string? Previous attempts are commented inside the code.
Here is my current code:
private int value;
public void setValue(int v){
value = v;
}
#EventHandler
public void onBlockBreak(BlockBreakEvent e) {
Block b = e.getBlock();
Player p = e.getPlayer();
//int value = 0;
String breakmsg = ChatColor.GREEN + "You gained " + ChatColor.GOLD + value + ChatColor.GREEN + " points for collecting " + ChatColor.AQUA + b.getType() + ChatColor.GREEN + ".";
#SuppressWarnings("deprecation")
int itemID = p.getItemInHand().getTypeId();
if (b.getType() == Material.DIAMOND_ORE) {
if (itemID == 257 || itemID == 278) {
//value = 5;
setValue(5);
int points = getConfig().getInt("players." + p.getUniqueId() + ".points");
getConfig().set("players." + p.getUniqueId() + ".points", points + value);
saveConfig();
startScoreboard();
e.getPlayer().sendMessage(breakmsg);
}
}
if (b.getType() == Material.GOLD_ORE) {
if (itemID == 257 || itemID == 285 || itemID == 278) {
//value = 3;
setValue(3);
int points = getConfig().getInt("players." + p.getUniqueId() + ".points");
getConfig().set("players." + p.getUniqueId() + ".points", points + value);
saveConfig();
startScoreboard();
e.getPlayer().sendMessage(breakmsg);
}
}
}
You could wrap that logic in a private function.
private String generateBreakMsgFrom(Block block, int value) {
return ...
}
Then within the if statements rather than setting value you can do:
breakmsg = generateBreakMsgFrom(b, 5);
Please note that you could and should probably also simply set the message after the if statements, but still you want to extract the message generation logic into a private function.
I would really recommend you to read Clean Code. Your function is very long, it is doing multiple things, it has a lot of magic numbers and quite a lot of code duplication...
EDIT: Since you declared int value in your function I haven't realized that it was an instance variable, therefore.
private String generateBreakMsgForBlock(Block block) {
return ... //you can use value from here once properly set
}

junit arrays not equal test

I'm trying to write a test case where my scenario is that two byte arrays should be not equal.
Can I do this with junit?
Or do I have to use something external like Hamcrest? I couldn't change the code in this answer to do the job
Please give a sample.
You can use
assertFalse(Arrays.equals(array1, array2));
If you wanted to check they were equal, I would use the following instead.
assertEquals(Arrays.toString(array1), Arrays.toString(array2));
as this produces a readable output as to what was different rather than just failing.
I prefer doing this the Hamcrest way, which is more expressive:
Assert.assertThat(array1, IsNot.not(IsEqual.equalTo(array2)));
Or the short version with static imports:
assertThat(array1, not(equalTo(array2)));
(The IsEqual matcher is smart enough to understand arrays, fortunately.)
Note that a limited version of Hamcrest is part of the JUnit 4.x distribution, so you don't need to add an external library.
Newer versions of JUnit offer org.junit.Assert.assertArrayEquals(byte[], byte[]), with overloads for other array types. Failures show the first index with a non-match and the differing elements at that index.
I also enjoy assertEquals(Arrays.asList(expected), Arrays.asList(actual)). The Hamcrest-powered rendition mentioned above is probably best.
Here is a possible alternative, which has the advantage of using the same code as assertArrayEquals() :
private void assertArrayNotEquals(byte[] expecteds, byte[] actuals) {
try {
assertArrayEquals(expecteds, actuals);
} catch (AssertionError e) {
return;
}
fail("The arrays are equal");
}
You could do it like this:
assertNotEquals(arrayOne, arrayTwo)
Sorry this is a bit long but it's easy to debug with and you can cut and paste it into your unit test.
private int span = 10;
private boolean equal(byte[] expected, byte[] got) {
final boolean result;
String message = null;
int offset = -1;
int length = -1;
if(expected == null && got == null) {
result = true;
} else if(expected == null || got == null) {
message = "One array is null: " + (expected == null ? "expected" : "got");
result = false;
} else if(expected.length != got.length) {
message = "Lengths differ: expected = " + expected.length + ", got = " + got.length;
result = false;
} else {
length = expected.length;
for(int i = 0; i < length; i++) {
if(expected[i] != got[i]) {
offset = i;
break;
}
}
result = offset == -1;
if(!result) {
message = "Contents differ";
}
}
if(!result) {
System.err.println(message);
if(offset >= 0) {
hexDump("Expected: ", expected, offset, length);
hexDump(" Got: ", got, offset, length);
}
}
return result;
}
private void hexDump(String label, byte[] ba, int offset, int length) {
System.err.print(label);
if(ba == null) {
System.err.println("<null>");
} else if(ba.length == 0) {
System.err.println("<zero-length-array>");
} else {
// <span> bytes either side
final int from = Math.max(0, offset - span);
final int to = Math.min(length, offset + span);
if(from != 0) {
System.err.print("(offset:" + from + ") ");
}
for(int i = from; i < to; i++) {
System.err.printf("%02X ", new Byte(ba[i]));
}
System.err.println();
}
}
#Test
public void testExample() {
assertTrue(equal(new byte[] { 1, 2, 3 }, new byte[] { 1, 8, 3 }));
}

int and boolean error

I have a method that generates and error that a int was expected but found boolean but when I switch it to a boolean it says the same error but reverse int and boolean. Here is my code:
private void compileDeclaration(boolean isGlobal) {
if (equals(theToken, "int")) {
accept("int");
String ident = theToken;
if (!isIdent(theToken)) t.error("expected identifier, got " + theToken);
else if (isGlobal){
symTable.allocVar(ident, isGlobal);
}
if (!isGlobal) cs.emit(Machine.ALLOC, symTable.stackFrameSize());
//dprint("declaring int " + ident);
theToken = t.token();
accept (";");
} else if (equals (theToken, "final")) {
accept("final");
accept("int");
String ident = theToken;
if (!isIdent(theToken)) t.error("expected identifier, got " + theToken);
theToken = t.token();
accept("=");
int numvalue = new Integer(theToken).intValue();
if (!isNumber(theToken)) t.error("expected number, got " + theToken);
else if (numvalue = 0) { **//This is where it highlights my error**
symTable.allocConst(ident, numvalue);
}
Any help would be most appreciated.
The line
else if (numvalue = 0) { **//This is where it highlights my error**
is missing an equals symbol, i.e.
else if (numvalue == 0) { **//This is where it highlights my error**
Most likely you're calling it in two different places, once with an integer and once with a boolean.
Either that or symTable.allocVar() expects an int.

Categories

Resources