constant expression required while using constants - switch-statement

private static int counter = 0; public static final int
CLIENT_REQUEST_TIME = counter++;
...
switch (command) { case Command.CLIENT_REQUEST_TIME:
...
but here it comes the
"Error:(20, 25) java: constant expression required",
for the case statement.
but why on earth? since CLIENT_REQUEST_TIME is constant
I know this is something that should be rather addressed to Oracle and I can choose from millions of workarounds... but just in case someone can see some logic behind, it will certainly make me sleep better tonight :)

This error comes because you set not constant property to constant field. I am not understand what this code must to do, but possibly you can change it to look like this:
private static int counter = 0;
public static int CLIENT_REQUEST_TIME = counter++;

Related

Misleading exception message in GatewayMethodInboundMessageMapper with un-annotated parameters

The following code throws a MessagingException with message At most one parameter (or expression via method-level #Payload) may be mapped to the payload or Message. Found more than one on method [public abstract java.lang.Integer org.example.PayloadAndGatewayHeader$ArithmeticGateway.add(int,int)].
#MessagingGateway
interface ArithmeticGateway {
#Gateway(requestChannel = "add.input", headers = #GatewayHeader(name = "operand", expression = "#args[1]"))
Integer add(#Payload final int a, final int b);
}
The desired functionality could be achieved with something like:
#MessagingGateway
interface ArithmeticGateway {
#Gateway(requestChannel = "add.input", headers = #GatewayHeader(name = "operand", expression = "#args[1]"))
#Payload("#args[0]")
Integer add(final int a, final int b);
}
Should the first version also work? Nevertheless I believe the error message could be improved.
A sample project can be found here. Please check org.example.PayloadAndGatewayHeader and org.example.PayloadAndGatewayHeaderTest.
EDIT
The purpose of #GatewayHeader was to show why one may want to have additional parameters that will not be part of the payload but I am afraid it created confusion. Here is a more streamlined example:
#MessagingGateway
interface ArithmeticGateway {
#Gateway(requestChannel = "identity.input")
Integer identity(#Payload final int a, final int unused);
}
Shouldn't the unused parameter be ignored since there is already another one that is annotated with #Payload?
You can't mix parameter annotations (which are static) with expressions (which are dynamic) because the static code analysis can't anticipate what the dynamic expression will resolve to at runtime. It is probably unlikely, but there theoretically could be conditions in the expression. In any case, it can't determine at analysis time that the expression will provide a value for #args[1] at runtime (it could, of course for this simple case, but not all cases are this simple).
Use one or the other; use your second approach or
Integer add(#Payload final int a, #Header("operand") final int b);

Is their a way for a user to input a word and have that word be (turn into) a #?

I am trying to create program that roles 2 dice. Then the user and say Yes to role the dice again or say No to stop rolling the dice.
import java.util.*;
public class Dice
{
public static void main(String[] args)
{
Random dice1 = new Random();
Scanner in = new Scanner(System.in);
//varibles
int die1;
int die2;
byte playagain=1;
byte Yes = 1;
byte No = 0;
int total;
int stop = 0;
//Want find I way to change words into #s
String start = Yes;
while(stop<5 && start<Yes){
stop+=1;
die1=dice1.nextInt(6)+1;
die2=dice1.nextInt(6)+1;
total=die1 + die2;
System. out. println("You rolled a " + total+ ".");
System. out. println("Do you want to play again?");
System. out. println("Type Yes to keep playing you and No to stop.");
/*I want people to be able to input Yes and that equal a # so I can use it in the While loop. Same with No.*/
start=in.next();
System. out. println("start is at " + start);
}
}
}
I have looked throughout internet an could not find any help so that is why I am asking.
If you mean you want to read an int from your scanner, try using Scanner.nextInt http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()
You can use hasNextInt to determine if using nextInt will work or not: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
If you already have the string and want to turn it into an int, try Integer.parseInt http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
In general, if you want to know if a function that does something basic exists, you should check the APIs in java.lang, java.util, java.io, etc (depending on where you think it would be)

Progress Bar with countdown timer in android

I need a progress bar in my layout, which will have a total time of 30 secs and will tick every second. Basically I want the user of my app to see that he has 30 sec time before time is up.
This is the piece of code I have written.
But this gives me a blank progress bar with no activity. Please help.
What am I doing wrong
public class MySeekBarActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setProgressBarVisibility(true);
final ProgressBar progressHorizontal = (ProgressBar) findViewById(R.id.progress_horizontal);
progressHorizontal.setProgress(progressHorizontal.getProgress()* 100);
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
progressHorizontal.incrementProgressBy(1);
int dtotal = (int) ( 30000 - millisUntilFinished ) /30000 * 100;
progressHorizontal.setProgress(dtotal);
}
public void onFinish() {
// DO something when 2 minutes is up
}
}.start();
}
}
You've got a type conversion bug, due to two things:
you're dividing by an int, which causes the decimal to be rounded down,
also, you're casting the result too early, so even if you'd divide by a float/double, the result would get rounded down anyway.
To see what I mean - you can safely remove the cast to int from your code, and it will compile anyway. That means your final number is an int, and since you're not making any casts earlier, it means you're losing the decimal info pretty early on in the code.
This is a possible fix:
int dtotal = (int) (( 30000 - millisUntilFinished ) /(double)30000 * 100);
to resolve such bugs in the future, make a dummy Java program with a loop containing the equation, and print out the intermediate result, for example:
public class NumberTester {
//define the constants in your loop
static final int TOTAL_TIME = 30000;
static final int INTERVAL = 1000;
public static void main(String[] args) {
//perform the loop
for(int millisUntilFinished = TOTAL_TIME;millisUntilFinished >=0;millisUntilFinished -= INTERVAL) {
int dtotal = (int) (( TOTAL_TIME - millisUntilFinished ) /(double)TOTAL_TIME * 100);
System.out.println(dtotal);
}
}
}
Also, some important things:
don't start your timer in onCreate - your activity is not visible yet at this point! Use onResume instead.
kill your timer in onPause. Leaving timers and threads unmanaged like that is bad form, and may lead to weird bugs.
don't use "magic numbers". Place all your constant values in a static final class members, like I've done in the example. This will save you a lot of headaches when you decide to change those values.
EDIT: as to why your progress bar stops short of completion, that's because the onTick method works a bit differently than you're probably assuming it does. To see what I mean, add:
System.out.println("Milis:" + millisUntilFinished);
System.out.println("dtotal:" + dtotal);
to your onTick method. The values clearly don't count down to 0 (and hence 100 in the case of dtotal, it being derived from millisUntilFinished) - you have to compensate for that.

Structure Reading Theory Problem

Iam have a DBC file, which is a database file for a game, containing ingame usable spell data, like ID, SpellName, Category etc...
Struct is something like this:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct SpellEntry
{
public uint ID;
public uint Category;
public float speed;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8, ArraySubType = UnmanagedType.I4)]
public int[] Reagent;
public int EquippedItemClass;
[MarshalAs(UnmanagedType.LPStr)] // Crash here
public string SpellName;
}
Iam reading the file with a binary reader, and marshaling it to the struct. Snippet:
binReader.BaseStream.Seek(DBCFile.HEADER_SIZE + (index * 4 * 234), SeekOrigin.Begin);
buff = binReader.ReadBytes(buff.Length);
GCHandle handdle = GCHandle.Alloc(buff, GCHandleType.Pinned);
Spell.SpellEntry testspell = (Spell.SpellEntry)Marshal.PtrToStructure(handdle.AddrOfPinnedObject(), typeof(Spell.SpellEntry));
handdle.Free();
Now to be more complex, lets see how does the DBC file storing the strings, for example the SpellName. Its not in the records, strings are contained in the end of the file, in a "string table" block. The string data in the records contains a number (offset) to the string in the string table. (so its not really a string).
I managed to read all the strings from the string block (at the end of the file), to a string[]. (this is dont before start reading the records)
Then I would start reading the records, but first problem Is :
1.) I cant read it, because it "crashes" on the last line of my struct (because its not a string really)
2.) I cant assign a string to the number.
When I read it, it will be a number, but at the end, as a result, I have to assign that string to the SpellName, thats got pointed by the number, in the string table. Jeez .
public struct SpellEntry
{
//...
private int SpellNameOffset;
public string SpellName {
get { return Mumble.GetString(SpellNameOffset); }
}
}
This is hard to get right, Mumble must be a static class since you cannot add any members to SpellEntry. That screws up Marshal.SizeOf(), making it too large. You'll need to initialize Mumble so that its static GetString() method can access the string table. Moving the SpellName property into another class solves the problem but makes the code ugly too.
This is liable to confuse you badly. If you got a version going that uses BitConverter then you're definitely better off by using it instead. Separating the file format from the runtime format is in fact an asset here.

What's a possible justification for not wrapping long argument lists? (StyleCop SA1115)

I'm stuck in a battle between ReSharper and StyleCop, and I'd like to let ReSharper win, but I want to hear the arguments in favour of StyleCop before I do that.
When I'm writing long argument lists ReSharper sensibly chops the parameter list and restarts it on the next line. I find that much more readable.
When I run StyleCop over the code it wants me to leave those lines really long. I don't like that, so I want to ignore that StyleCop rule (SA1115). I can't think of a good reason why SC would want those long lines in the first place – is it just a case of "we've always done it this way"?
StyleCop doesn't want you to put all your parameters on one really long line. However, it also doesn't want you to just arbitrarily insert a newline to move part of the parameter list down to the next line. StyleCop would like you to do one of the following:
public void MyMethod(int param1, int param2, int param3)
public void MyMethod(
int param1, int param2, int param3)
public void MyMethod(
int param1,
int param2,
int param3)
It's probably there to remind you that your argument list is too long and should be shortened.
Whilst playing about with the code from this question, I also fell foul of SA1115 via running StyleCop from the VS IDE. After some mucking about, here is the end result which StyleCop felt was OK:
public static string Format<T>(string pattern, T template)
{
Dictionary<string, string> cache = new Dictionary<string, string>();
return RegexExpression.Replace(
pattern,
match =>
{
string key = match.Groups[1].Value;
string value;
if (!cache.TryGetValue(key, out value))
{
var prop = typeof(T).GetProperty(key);
if (prop == null)
{
throw new ArgumentException("Not found: " + key, "pattern");
}
value = Convert.ToString(prop.GetValue(template, null));
cache.Add(key, value);
}
return value;
});
}
Just thought I'd share it.
It seems the rule technically says "parameter must follow comma." Pretty nit-picky if you ask me, but some people believe in starting continuation lines with the commas in order to really show hey! This line is a continuation! E.g.
void Foo( int blah
, string blork
, ...
Whatever floats your boat, personally :)

Resources