简体   繁体   中英

Processing is acting strange with text()

I was trying to write a program to count down the seconds/minutes until the next year, but I have already hit something super weird and I can't figure out what it is doing. Here is my code:

import java.util.Calendar;
import java.util.GregorianCalendar;

Calendar currentTime;
Calendar newYear;
int nextYear;

void setup() {
    size(500, 250);
    frameRate(60);
}

void draw() {
    background(255, 0, 0);
    currentTime = Calendar.getInstance();
    nextYear = currentTime.get(Calendar.YEAR) + 1;
    newYear = new GregorianCalendar(nextYear, 1, 1, 0, 0, 0);
    textAlign(CENTER, CENTER);
    fill(0);
    textSize(20);
    long timeInMillis = currentTime.getTimeInMillis(); //I added this to try to fix it.
    System.out.println(timeInMillis); //Used to be System.out.println(currentTime.getTimeInMillis())
    text(timeInMillis, width/2, height/2); //Used to be text(currentTime.getTimeInMillis(), width/2, height/2)
}

I even tried making an actual local variable for the current millisecond time, but it didn't do anything. Here is the problem: Even though I am putting the same thing into System.out.println() and text() , the number displayed in the window stays constant the whole time. It also formats it as a decimal, even though it is a long value. When I ran the program, the text was:

1448569995264.000

However, the (last five) lines of the output were:

1448570028853
1448570028869
1448570028886
1448570028903
1448570028919

The text wouldn't change at all, and I can't figure out why.

The text() function isn't designed to handle long variables. It's only designed to handle String , int , and float variables. So the text() function is treating your long as a float . That's why you're getting the decimal places.

That's also why the number isn't changing- float values can only handle a certain number of significant digits, so they lose accuracy with very large values like the one you're using. As a side note, this issue can also lead to strange cases like this one:

float x = 123456789;
println(x == x+1); //prints true!

The solution is to not mix long values with the Processing functions. If you need to create a String value to pass into the text() function, then do that manually. The easiest way to do that might be the String.valueOf() function:

text(String.valueOf(timeInMillis), width/2, height/2);

There are other functions available for more specific formatting, but this will get you the basics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM