int and boolean error - java

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.

Related

How can I increment the variable more than one time when sensor event changed?

As you can see that I am trying to increment the variable 'c' when the accelerometer z-axis value greater than 12. But I can do it at one time, it will change the value 0 to 1 after executing the program. But I want to collect how many times the z-axis value becomes more than 12.
#Override
public void onSensorChanged (SensorEvent event) {
textView.setText(event.values[0] + "");
textView1.setText(event.values[1] + "");
textView2.setText(event.values[2] + "");
String s = new String();
s = textView2.getText().toString().trim();
Float t = Float.parseFloat(s);
int c = 0;
if (t > 11) {
c++;
txt.setText(Integer.toString(c));
}
}
int counter = 0;
#Override
public void onSensorChanged (SensorEvent event) {
textView.setText(event.values[0] + "");
textView1.setText(event.values[1] + "");
textView2.setText(event.values[2] + "");
String s = new String();
s = textView2.getText().toString().trim();
Float t = Float.parseFloat(s);
int c = 0; // ???
if (t > 11) {
c++;
counter++;
txt.setText(Integer.toString(c));
System.out.println("I need to learn how to use global
variables.\n
also the thing has been greater than \"12\"
"+counter" times."
);
}
}
Also maybe using more meaningful variable names other than "textView#" would make it less of a pain for people to figure out what you're trying to do.
You can define the variable c as a field member like below:
public class MainActivity {
private int c = 0;
(...)
#Override
public void onSensorChanged (SensorEvent event) {
textView.setText(event.values[0] + "");
textView1.setText(event.values[1] + "");
textView2.setText(event.values[2] + "");
String s = new String();
s = textView2.getText().toString().trim();
Float t = Float.parseFloat(s);
if (t > 11) {
c++;
txt.setText(Integer.toString(c));
}
}
}

Regular Expression Union and subtracion for numeric

I am trying to have a union of regular expression and subtraction,I am able work range only like. String regex = "[1-3[5-7]]"; but need different type of numbers with range and at the same time union also like String regex = "\b([1-9]|[1-4][0-9]|5[0-5]&&[191])\b"; In this line am able to match 1 to 55 and also match 191.it is not working.Can any one give the suggestion where the problem getting. I tried for numeric range like below.
public class NumericRangeRegex {
public String baseRange(String num, boolean up, boolean leading1) {
char c = num.charAt(0);
char low = up ? c : leading1 ? '1' : '0';
char high = up ? '9' : c;
if (num.length() == 1)
return charClass(low, high);
String re = c + "(" + baseRange(num.substring(1), up, false) + ")";
if (up) low++; else high--;
if (low <= high)
re += "|" + charClass(low, high) + nDigits(num.length() - 1);
return re;
}
private String charClass(char b, char e) {
return String.format(b==e ? "%c" : e-b>1 ? "[%c-%c]" : "[%c%c]", b, e);
}
private String nDigits(int n) {
return nDigits(n, n);
}
private String nDigits(int n, int m) {
return "[0-9]" + String.format(n==m ? n==1 ? "":"{%d}":"{%d,%d}", n, m);
}
private String eqLengths(String from, String to) {
char fc = from.charAt(0), tc = to.charAt(0);
if (from.length() == 1 && to.length() == 1)
return charClass(fc, tc);
if (fc == tc)
return fc + "("+rangeRegex(from.substring(1), to.substring(1))+")";
String re = fc + "(" + baseRange(from.substring(1), true, false) + ")|"
+ tc + "(" + baseRange(to.substring(1), false, false) + ")";
if (++fc <= --tc)
re += "|" + charClass(fc, tc) + nDigits(from.length() - 1);
return re;
}
private String nonEqLengths(String from, String to) {
String re = baseRange(from,true,false) + "|" + baseRange(to,false,true);
if (to.length() - from.length() > 1)
re += "|[1-9]" + nDigits(from.length(), to.length() - 2);
return re;
}
public String run(int n, int m) {
return "\\b0*?("+ rangeRegex("" + n, "" + m) +")\\b";
}
public String rangeRegex(String n, String m) {
return n.length() == m.length() ? eqLengths(n, m) : nonEqLengths(n, m);
}
}
I think you are on the wrong track. You should simply extract and parse the numeric values and do the calculation in your regular programming language, as recommended by Patrick.
You can still create a wrapper class that helps to check numeric ranges using a simple function like
public static boolean between(int i, int minValueInclusive, int maxValueInclusive) {
return (i >= minValueInclusive && i <= maxValueInclusive);
}
or use commons.lang.Range:
Range<Integer> myRange = Range.between(1, 55);
if (myRange.contains(value)){
// do something
}
Based on conditions Ill try for union and subtraction is `^(?!250)0*?([0-9]|2(5([0-5])|[0-4][0-9])|1[0-9]{2}|[1-9][0-9]|2000)$. In this we are matching 1 to 255 range and 2000 numeric number(union) and for negate 250(subtraction).It's working fine.

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
}

Variable might not have been initialized?

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.

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 }));
}

Categories

Resources