I'm trying to add a L to the end of this integer and I get an error to make it a long. I need it to be in the form of an integer though...
Can someone please help me?
Here is my code:
int timeBetween = plugin.getConfig().getInt("timeBetweenSendsInTicks");
timeBetween = timeBetween + "L";
Although, remember, it must strictly be an INTEGER!
EDIT: I need it to be something that goes with this:
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
#SuppressWarnings("unused")
BukkitTask task = new Timer(JavaPlugin.getPlugin(GodSends.class), amountOfChest).runTaskTimer(JavaPlugin.getPlugin(GodSends.class), 20, timeBetweenChest);
String startMSG = plugin.getConfig().getString("startMSG");
getServer().broadcastMessage(startMSG);
}
}, 0L, timeBetween); //< this needs to have an L at the end, I have it set to 60000 in the config, but I cant seem to get the L after it.
It seems the API you're using scheduler.scheduleSyncRepeatingTask() expects the last two parameters to be of type long. Since, an int can implicitly fit into a long, passing timeBetween as it is will work just fine.
Same goes for the second parameter too. You can pass 0 instead of 0L there as well. It works out the same. Basically, you're gaining nothing by explicitly passing a long literal here. They make sense in cases where you want to assign a long with a literal value that's outside of the integer's range.
You appear to be trying to make an int variable into a long variable at runtime by putting an "L" 'at the end' of the integer. This is not the correct way to do this.
Putting an L at the end of a numeric integer literal within a java program will cause the compiler to treat it as a long value instead of an int value. But you aren't feeding a literal to the compiler, so the "L" notation doesn't help you here.
I think what you need is to cast your int to a long for passing to your method, whatever it is -- so instead of
}, 0L, timeBetween);
you should have
}, 0L, (long) timeBetween);
Related
I am developing an app in which I am adding views dynamically and assigning an unique id using but it is returning negative value:
long time = System.currentTimeMillis();
view.setId((int)time);
So I searched on google and found another solution but however it also doesn't work. It also returns negative value:
Long time = System.currentTimeMillis();
view.setId(time.intValue());
So how can I convert long value returned by System.currentTimeMills() to int safely?
System.currentTimeMills() returns 1505645107314 while converting to int returns -1888413582.
The value will be changed when a large long value is casted to int. You may want to divided the time by 1000 to get time in seconds, or subtract the value from time of 1 day ago (depending upon the uniqueness you prefer) and use it as the id of the view.
view.setId((int)(time/1000)); //this gives unique id for every second.
Edit
Use following code to get unique id for every millisecond:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
long yesterday = calendar.getTimeInMillis();
int uniqueId = (int) (yesterday - System.currentTimeMillis());
currentTimeMillis returns a long, which can sometimes not fit into an int. Therefore, I don't think you should use this as a way to set unique int ids for views.
If you want a unique int for each of the views you create, try this approach, create a static counter thingy:
static int nextViewID = 0;
When you create a new view, you just
view.setId(nextViewID);
nextViewID++;
If you want a random unique integer, you can do something like this:
Create a static Set
Generate a random integer using java.util.Random
Try to add the number to the set
Keep generating another integer until you successfully added the number to the set
This is normal. Casting from a large data type (such as long) to a smaller data type (like int), in some cases, might lead to a change in value. You can devise other means by dividing by a certain preset constant (say 10,000). For example:
Long t = System.currentTimeMillis() / 10000;
view.setId((int) t);
This would surely give you a positive value!
You can't do it. Why do you use time as unique id? Bad approach.
For instance, 2147483648 would be represented as -2147483648. For small values, casting is enough:
long l = 42;
int i = (int) l;
However, a long can hold more information than an int, so it's not possible to perfectly convert from long to int, in the general case.
You can use Hash values within integer limit as unique id.
I'm trying to do random number generation using the given date to create good pseudo-random numbers in Java. I decided to use the Calendar class and to count milliseconds in the day. This worked to some extent, but I can only get a different random value when I start the program. Running it any more times in the program will just give me the same number. I'm using Thread.sleep() to make sure that there is an actual difference on time, but I still get the same numbers.
Heres my method that I'm calling (from another class)
public long genRNG()
{
long mask = 0xFFFF000000000000L;
long randomValue = seed & mask;
seed = 0x5D588B656C078965L * cal.get(Calendar.MILLISECOND) + 0x0000000000269EC3;
return randomValue;
}
and here's my main method
public static void main(String[] args) throws InterruptedException
{
Seed key = new Seed();
for (int x = 0; x <=10; x++)
{
Thread.sleep(200);
System.out.println(key.genRNG());
}
}
and the given output:
-7389844038561562624
-7389844038561562624
-7389844038561562624
-7389844038561562624
-7389844038561562624
-7389844038561562624
-7389844038561562624
-7389844038561562624
-7389844038561562624
It seems you are setting mask to the same value each time and seed to the same value each time, so seed & mask yields the same value each time. A Calendar object does not automatically change its value after it has been instantiated — in other words it keeps the time it got when you constructed it (typically the time when it was constructed) until you explicitly change it. So one suggestion is to do reinitialize cal in each call to genRNG().
Here I have changed cal to a local variable:
long mask = 0xFFFF000000000000L;
long randomValue = seed & mask;
Calendar cal = Calendar.getInstance();
seed = 0x5D588B656C078965L * cal.get(Calendar.MILLISECOND) + 0x0000000000269EC3;
return randomValue;
Now I can get output like:
0
8430738502437568512
-2453898846963499008
2916080758722396160
3291568377654411264
-1326873040214032384
-951385421282017280
1212312724692795392
-3406128693175648256
-1298444067566256128
-5916885485434699776
The initial 0 comes from seed not having been initialized. I gather it’s not a problem in your code.
I don’t think you’re there yet, though. Calendar.get(Calendar.MILLISECOND) always returns a value in the interval 0 through 999, so you are getting up to 1000 different “random” values. Not a lot for storing in a long. You may get more for instance like this:
seed = 0x5D588B656C078965L * System.currentTimeMillis() + 0x0000000000269EC3;
If for some reason you want an object for the current time rather than just the long you get from System.currentTimeMillis(), if you can use Java 8, I suggest Instant.now().toEpochMilli(). It gives you the same long value, but Instant.now() gives you an object representing the current time, much like Calendar.getInstance(), only more modern and more versatile if you want to use it for other purposes.
Another issue is because of the mask your value will always end in 48 zeroes in binary representation (it’s easy to see all the values are even). Maybe this is as designed?
Also I suppose there is a reason why you are not just using java.util.Random.
I need to pass an int value inside a float from java code to php.
The reason is that the third-party API that I have to use in between accepts only float values.
In java I have the following code, that works as expected:
int i1 = (int) (System.currentTimeMillis() / 1000L);
float f = Float.intBitsToFloat(t);
int i2 = Float.floatToIntBits(f);
//i1 == i2
Then I pass float value from Float.intBitsToFloat() to the third-party API and it sends a string to my server with float:
"value1":1.4237714E9
In php I receive and parse many such strings and get an array:
{
"value1" => 1.4237714E9, (Number)
"value2" => 1.4537614E9 (Number)
...
}
Now I need to make Float.floatToIntBits() for each element in php, but I'm not sure how. Will these php numbers be 4 bytes long? Or maybe I can somehow get integer while parsing from string? Any suggestions?
Thank you in advance!
Thank you, guys! Yes, I forgot about pack/unpack.
It's not really an answer, yet it works for my case:
function floatToIntBits($float_val)
{
$int = unpack('i', pack('f', $float_val));
return $int[1];
}
But not vice versa! The strange thing:
$i1 = 1423782793;
$bs =pack('i', $i);
$f = unpack('f', $bs);
//array { 1 => 7600419110912} while should be 7.6004191E12 (E replaced with 109?)
//or may be 7600419110000 which also right, but not 7600419110912!
I can't explain this. Double checked on home system and on server (5.5 and 5.4 php) - the same result.
Hi the staff that I found you probably will not like:
function FloatToHex1($data)
{
return bin2hex(strrev(pack("f",$data)));
}
function HexToFloat1($data)
{
$value=unpack("f",strrev(pack("H*",$data)));
return $value[1];
}
//usage
echo HexToFloat1(FloatToHex1(7600419100000));
Give the result like 7600419110912
so the 109 is NOT a substitution of E the problem is recalculation of the numbers with float point. It's sounds funny but PHP recalculation bring you the most accurate answer possible. And this is an answer 7600419110912
So read this post for more info https://cycling74.com/forums/topic/probably-a-stupid-question-but/
So, I have to make a random number generator to get numbers ranging from 0 to 400. I'm putting these into an array and then sorting them later on. I just am not sure how to go about doing this. I was given something along the lines of;
public int nextInt(400) //gives me errors
{
random.setSeed(12345L);
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
}
I've already called the random class, since the directions indicated that. I just don't know why this is not working. It's giving me errors especially with the first part; class, interface, or enum expected. Could somebody steer me in the right direction please?
Functions in Java (all programming languages) have "variables" in their definition.
You've got:
public int nextInt(400)
Over here, you want your 400 to be a value that is passed to the function.
Think of this as math. I'm sure you've dealt with something like f(x) = 2 * x. Here, x is the variable, and you "evaluate" f(x) with a value for x. Similarly, in programming, we'd have something like :
public int nextInt(int x)
As you see, our function defines x to be of type int. This is necessary in a language like Java because you're telling the compiler that this function will only accept integers for x.
Now that you've done that, you can use x as a variable in the body of your function.
Note that whenever you use a variable, it first has to be defined. A line such as:
int variable;
defines variable as an int.
Your program is missing these for random, val, arr, and a. Note here that arr and a are arrays (and somehow I get the feeling that they should not be two separate variables).
You should really brush up on variables definitions, arrays, and functions before attempting this question. Your best resource would be your textbook, because it'll explain everything in an organized, step-by-step manner. You can also try the many tutorials that are available online. If you have specific questions, you can always come back to StackOverflow and I'm sure you'll find help here.
Good luck!
You need to define this function within a class definition
even you have specified :
public int nextInt(400)
in this line function returns int and in your whole body u didn't have any return statement.
and yes as Kshitij Mehata suggested dont use 400 directly as value use variable over there.
this should be your function:
public int[] nextInt(int x) //gives me errors
{
random.setSeed(12345L);
int[] a=new int[arr.size];
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
return a;
}
even there is some issue with arr from where this arr come?
I'm working on (what is to a beginner) a rather complex assignment. I think I've got the jist of it down, but I'm having trouble with it printing "null" after Monday-Sunday are entered into the dialog box. Also, the goal of the assignment is, later, for the user to enter a number 0-6 and then the corresponding weekday (from the String[] weekArray set in the method) is printed. I'm not really sure how to do this and my book doesn't seem to be showing me the way, but am I even going to be able to do that the way my code is set up? Thanks and best regards. Here's the code.
EDIT - there's an example in my book under returning an array from a method. I'm not sure if it's applicable to my assignment as they seem to have different goals, but here it is..
EDIT#2 - instructions for reference to what I'm doing.
EDIT#3 - my interpretation of the example for passing methods to arrays.
EDIT #4 - solved the issue. I was going about it the wrong way for much. The book's example wasn't much help. Thanks to those of you who replied. I deleted the homework assignment description in consideration of the professor (who probably wouldn't like his assignments on the internet next semester)
Excerpt of the code below... I was making this way more complicated than it was
public static String[] getWeek() {
String[] weekArray = new String[7];
for (int i = 0; i < weekArray.length; i++) {
weekArray[0] = JOptionPane.showInputDialog("Enter 'Monday'. ");
if (weekArray[0].compareTo("Monday") > 0) {
weekArray[0] = JOptionPane.showInputDialog("Enter 'Monday'. ");
Your branches have unreachable statements -
weekArray[5] = ...
while(weekArray[5].equalsIgnoreCase(null)) {
// Cannot reach this point as equalsIgnoreCase(null) always returns false.
}
From String#equalsIgnoreCase:
true if the argument is not null and the Strings are equal, ignoring case; false otherwise.
Emphasis mine.
EDIT: From your edit above you appear to be having trouble with populating an array. The rough idea is:
public static void main(String[] args) {
// Just an example
int[] values = new int[5];
System.out.println(Arrays.toString(values));
populateArray(values);
System.out.println(Arrays.toString(values));
}
private static void populateArray(int[] toBePopulated) {
toBePopulated[0] = 42;
toBePopulated[1] = 11;
// Etc. Again, just an example.
}
This will print:
[0, 0, 0, 0, 0]
[42, 11, 0, 0, 0]
The idea is that what is passed to the method populateArray is a reference to the location of the array in memory. That means that you can manipulate the contents of the array, and the change will be reflected in values afterwards.
I don't know if i got it right , but from a cursory look , seems you're mistaking the sunday part , guess it should be sth like :
if (weekArray[5].equalsIgnoreCase("Sunday")) // Note the "5"
Your cheek for string being null is probably not what you want. If you indent the code it would be easier to see.
After formatting this is what you have
while (weekArray[0].equalsIgnoreCase(null)) {
if (weekArray[0].equalsIgnoreCase("Monday"))
return weekArray[0];
}
So, if weekArray[0] is null, then you check if null equalsIgnoreCase("Monday"). This logic is not what you want.
After asking and checking all days you return null (at the end of the method). This si the null being printed.