I was wondering how I would go about getting a different set of data to print every time I press the same key for KeyPressed in Processing. The data being displayed is from an imported file so the code for what I'm doing is as follows:
import java.util.Scanner;
import java.io.*;
PImage cityMap;
FileInputStream in;
int Year=0;
void setup()
{
size(500,500);
cityMap=loadImage("cityMap.png");
background(cityMap);
}
void draw()
{
//EMPTY
}
void keyPressed() {
if(key==CODED)
{
if(keyCode==RIGHT)
{
//2015
String fif[]= loadStrings("2015data.txt");
for (int i=1; i<fif.length;i++)
{
Scanner sc= new Scanner(fif[i]);
int xValue= sc.nextInt();
int yValue= sc.nextInt();
int pixelX= locX2PixX(xValue);
int pixelY= locY2PixY(yValue);
stroke(200,200,250);
point(pixelX,pixelY);
}
//2016
String six[]= loadStrings("2016data.txt");
if(
for (int i=1; i<six.length;i++)
{
Scanner sc= new Scanner(six[i]);
int xValue= sc.nextInt();
int yValue= sc.nextInt();
int pixelX2= locX2PixX(xValue);
int pixelY2= locY2PixY(yValue);
stroke(250,200,250);
point(pixelX2,pixelY2);
}
//2017
String seven[]= loadStrings("2017data.txt");
for (int i=1; i<seven.length;i++)
{
Scanner sc= new Scanner(seven[i]);
int xValue= sc.nextInt();
int yValue= sc.nextInt();
int pixelX3= locX2PixX(xValue);
int pixelY3= locY2PixY(yValue);
stroke(20,200,250);
point(pixelX3,pixelY3);
}
}
}
}
int locX2(int locationX)
{
return((int)((6*locationX)-8));
}
int locY2(int locationY)
{
return((int)(8*locationY+8));
}
I managed to get the code to run minus that one feature.
I think I have most of the logic down, I'm just trying to figure out to have this show only one set of the data at a time and then the next one after I press the same key again. I was thinking I may need some type of if statement that could maybe use my year variable?
(I don't know that much about Processing, but it's silly to chat in comments about general purpose computer programming...)
It sounds like you need to maintain "state", which is a fancy way of saying a variable where you store information about if you have done something before, and what that thing is.
First, how many states do you care about? It sounds like you have two distinct options, so if you add the initial state, this technically makes three (but for only two valid states we can ignore that for now). Ok, so your startup code (constructor or initializer, whatever is typical for Processing) will set a variable of some sort to a known start value.
How to do this is up to you. It could be a String or an int or something advanced like an enum. The idea is that this is a testable, settable, persistent chunk of data that you know the meaning of.
Every time you handle the "event" of a button being pushed you do two things:
Test the state you initialized earlier and make a decision. In the initial state you want to load "2015" data. Ok. So do that.
Change the variable holding the state so it is in the "next" state. In the 2015 state we want to change that to 2016 so we are ready for the next button event we handle.
A simple example would be to create an int called dataState or something. In setup set this to 2015. In your button handler have a switch or if statement that checks for all possible values dataState can be, and runs the appropriate code for that state. e.g., if it is set to 2015 it will do whatever you need it to do for 2015, but at the end it should set the dataState to 2016 so that the next time through it does the 2016 branch.
It is up to you what the 2016 branch does to this state. You can reset it to 2015 or continue on to 2017, if your code needs to have that functionality.
Some comments:
You'll notice that your code for processing 2015 data is almost the same as the code that processes 2016 data. This is an opportunity to use a function or method that accepts a filename and does some work based on that, and then sets the state to the "next" state.
Once you do this, then your logic in the button handler becomes a nice short and understandable set of if ... else if statements that simply call the appropriate function for that state. This makes it easy to add, say, 2017 processing. Code always grows features so it's good to plan ahead for that.
Once you get really good at this, you'll start thinking about "state models" and then before you know it you'll want to have your state managed as a class or enum with a big switch statement that drives the whole works. This is a very common pattern with embedded, event driven code that Processing supports.
keep track of your year in a variable and change it when the key is pressed. Something like this
//start off one less than first desired year
int Year=2014;
void keyPressed() {
if(key==CODED) {
if(keyCode==RIGHT) {
//increment year
Year = Year+1;
//Clamp year between 2015 and 2017
Year= Math.max(2015, Math.min(2017, Year));
String yr[]= loadStrings(Year +"data.txt");
for (int i=1; i<yr.length;i++) {
Scanner sc= new Scanner(yr[i]);
int xValue= sc.nextInt();
int yValue= sc.nextInt();
int pixelX= locX2PixX(xValue);
int pixelY= locY2PixY(yValue);
stroke(200,200,250);
point(pixelX,pixelY);
}
}
}
}
Related
I want to be able to do something like this:
for(i = 0; i < 10; i++) {
//if any button in the array is pressed, disable it.
button[i].setOnAction( ae -> { button[i].setDisable(true) } );
}
However, I get a error saying "local variables referenced from a lambda expression must be final or effectively final". How might I still do something like the code above (if it is even possible)? If it can't be done, what should be done instead to get a similar result?
As the error message says, local variables referenced from a lambda expression must be final or effectively final ("effectively final" meaning the compiler can make it final for you).
Simple workaround:
for(i = 0; i < 10; i++) {
final int ii = i;
button[i].setOnAction( ae -> { button[ii].setDisable(true) } );
}
Since you are using lambdas, you can benefit also from other features of Java 8, like streams.
For instance, IntStream:
A sequence of primitive int-valued elements supporting sequential and parallel aggregate operations. This is the int primitive specialization of Stream.
can be used to replace the for loop:
IntStream.range(0,10).forEach(i->{...});
so now you have an index that can be used to your purpose:
IntStream.range(0,10)
.forEach(i->button[i].setOnAction(ea->button[i].setDisable(true)));
Also you can generate a stream from an array:
Stream.of(button).forEach(btn->{...});
In this case you won't have an index, so as #shmosel suggests, you can use the source of the event:
Stream.of(button)
.forEach(btn->btn.setOnAction(ea->((Button)ea.getSource()).setDisable(true)));
EDIT
As #James_D suggests, there's no need of downcasting here:
Stream.of(button)
.forEach(btn->btn.setOnAction(ea->btn.setDisable(true)));
In both cases, you can also benefit from parallel operations:
IntStream.range(0,10).parallel()
.forEach(i->button[i].setOnAction(ea->button[i].setDisable(true)));
Stream.of(button).parallel()
.forEach(btn->btn.setOnAction(ea->btn.setDisable(true)));
Use the Event to get the source Node.
for(int i = 0; i < button.length; i++)
{
button[i].setOnAction(event ->{
((Button)event.getSource()).setDisable(true);
});
}
Lambda expressions are effectively like an annonymous method which works on stream. In order to avoid any unsafe operations, Java has made that no external variables which can be modified, can be accessed in a lambda expression.
In order to work around it,
final int index=button[i];
And use index instead of i inside your lambda expression.
You say If the button is pressed, but in your example all the buttons in the list will be disabled. Try to associate a listener to each button rather than just disable it.
For the logic, do you mean something like that :
Arrays.asList(buttons).forEach(
button -> button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button.setEnabled(false);
}
}));
I Also like Sedrick's answer but you have to add an action listener inside the loop .
I've been tasked to write a basic guessing game, which I have done, but part of the task is confusing me. We've been asked to create a warning when a user inputs the same guess too many times. I've tried several ways to take the previous user guess and compare them with the current one but none seem to work. Can anyone help me with this? My Google skills seem to have failed me.
Mostly I've tried this:
void guessWarning(int confirmedGuess){
int prevGuess = currentGuess;
int currentGuess = confirmedGuess;
if(prevGuess == currentGuess){
text("Same guess, try again",350,350)
}
}
There are multiple ways to tackle this.
One option would be keep track of the previous attempts in a dynamic array (see ArrayList). Here a bit of code to illustrate the concept:
//create a new list of integers
ArrayList<Integer> guesses = new ArrayList<Integer>();
//in your check function, test if the new value already exists
if(guesses.contains(NEW_GUESS_HERE)){
println("you've already tried this number");
}else{//otherwise add the current guess to keep track of for next time
guesses.add(NEW_GUESS_HERE);
}
Another option is using a HashMap. This is an associative array as opposed to an index based array. This method is more efficient and you can also keep track of how many attempts there were for each value. Be sure to read more on HashMaps: it will help you on the long run and potentially impress your tutors on the short run.
Here's a basic sketch to illustrate the idea:
//create a new hashmap of integers (key = guess, value = number of times tried)
HashMap<Integer,Integer> guesses = new HashMap<Integer,Integer>();
int answer = '=';
void setup(){}
void draw(){}
void keyPressed(){
guess(keyCode);
println(keyCode);
}
void guess(int newValue){
if(newValue == answer){
println("you guessed it!");
}else{
//check if the value was already recorded
try{
//if there was a value with this key, it's been tried before
int numberOfTries = guesses.get(newValue);
println("you've tried this value",numberOfTries,"times");
//increment the number of times this has beeen attempted
guesses.put(newValue,numberOfTries+1);
}catch(NullPointerException e){
println("it's the first time you try this number, but you haven't guessed it yet");
guesses.put(newValue,1);
}
}
}
A similar option, but a bit more hacky would be using a JSONObject.
The concept is similar: an associative array (albeit the key is a string, instead of an int), but you'd need to convert the guessed number to a string to index it first:
JSONObject guesses = new JSONObject();
int answer = '=';
void setup(){}
void draw(){}
void keyPressed(){
guess(keyCode);
println(keyCode);
}
void guess(int newValue){
if(newValue == answer){
println("you guessed it!");
}else{
//hacky int to string
String newValueStr = newValue+"";
//check if the value was already recorded
if(guesses.hasKey(newValueStr)){
//if there was a value with this key, it's been tried before
int numberOfTries = guesses.getInt(newValueStr);
println("you've tried this value",numberOfTries,"times");
//increment the number of times this has beeen attempted
guesses.setInt(newValueStr,numberOfTries+1);
}else{
println("it's the first time you try this number, but you haven't guessed it yet");
guesses.setInt(newValueStr,1);
}
}
}
One nice thing is that you could save the guesses to disk, then load it so the program could recall previous guesses even if the it was restarted.
I'll leave you the fun exercise of attempting to load the data when the sketch starts and saving the data when the sketch exists.
This code actually works fine, the question I have with my code is how do you store the enum constant in any variable, and why do we use enum? and what does the statement mean HouseType houseType;? Thank you so much in advance.
import java.util.Scanner;
public class HomeBuying {
public enum HouseType{UNKNOWN,SINGLEFAMILY,TOWNHOUSE,CONDOMINIUM};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the type of house you want to purchase"); //1.Single Family/n" " 2. Townhouse/n" " 3. Condominium/n");
int choice = input.nextInt();
HouseType houseType;
switch(choice) {
case 1:
houseType = HouseType.SINGLEFAMILY;
break;
case 2:
houseType = HouseType.TOWNHOUSE;
break;
case 3:
houseType = HouseType.CONDOMINIUM;
break;
default:
houseType = HouseType.UNKNOWN;
break;
}
System.out.println(houseType);
}
The code snippet you provided already stores an Enum value in a variable.
HouseType houseType; //declaration of variable of type HouseType (means it can store values of the HouseType enum)
houseType = HouseType.UNKNOWN; //put value into the houseType variable
We use enums whenever we need to represent values from some known and finite set. For example if you want your program to keep track of whether it is day or night, you could just make up some rule for yourself and use integers, say 1 represents day and 0 represents night. But then what the other numbers mean? Or you could just use boolean for that (again, with some arbitrary meaning attached to false and true).
enum TimePeriod{
DAY,
NIGHT
}
Enums represent a better alternative by letting you to be explicit about what values mean. This is not just a convenience - being explicit in your intentions is what makes your program readable by others.
Let's talk about theory a bit. We have one container, let's call it TMyObj that looks like this:
struct TMyObj{
bool bUpdated;
bool bUnderUpdate;
}
Let a class named TMyClass have an array of the container above + 3 helpful functions. One for getting an object to be updated. One for adding update info to a certain object and one for getting an updated object. It's also called in this order. Here's the class
class TMyClass{
TmyObj entries[];
TMyObj GetObjToUpdate;
{
//Enter critical section
for(int i=0; i<Length(entries); i++)
if(!entries[i].bUnderUpdate)
{
entries[i].bUnderUpdate=true;
return entries[i];
}
//Leave critical section
}
//the parameter here is always contained in the Entries array above
void AddUpdateInfo(TMyObj obj)
{
//Do something...
//Enter critical section
if(updateInfoOver) obj.bUpdated=true; //left bUnderUpdate as true so it doesn't bother us
//Leave critical section
}
TmyObj GetUpdatedObj
{
//<-------- here
for(int i=0; i<Length(entrues); i++)
if(entries[i].bUpdated) then return entries[i];
//<-------- and here?
}
}
Now imagine 5+ threads using the first two and another one for using the last function(getUpdadtedObj) on one instance of the class above.
Question: Will it be thread-safe if there's no critical section in the last function?
Given your sample code, it appears that it would be thread-safe for a read. This is assuming entries[] is a fixed size. If you are simply iterating over a fixed collection, there is no reason that the size of the collection should be modified, therefore making a thread-safe read ok.
The only thing I could see is that the result might be out of date. The problem comes from a call to GetUpdatedObj -- Thread A might not see an update to entries[0] during the life-cycle of
for(int i=0; i<Length(entrues); i++)
if(entries[i].bUpdated) then return entries[i];
if Thread B comes along and updates entries[0] while i > 0 -- it all depends if that is considered acceptable or not.
I have a scenario where, at certain points in my program, a thread needs to update several shared data structures. Each data structure can be safely updated in parallel with any other data structure, but each data structure can only be updated by one thread at a time. The simple, naive way I've expressed this in my code is:
synchronized updateStructure1();
synchronized updateStructure2();
// ...
This seems inefficient because if multiple threads are trying to update structure 1, but no thread is trying to update structure 2, they'll all block waiting for the lock that protects structure 1, while the lock for structure 2 sits untaken.
Is there a "standard" way of remedying this? In other words, is there a standard threading primitive that tries to update all structures in a round-robin fashion, blocks only if all locks are taken, and returns when all structures are updated?
This is a somewhat language agnostic question, but in case it helps, the language I'm using is D.
If your language supported lightweight threads or Actors, you could always have the updating thread spawn a new a new thread to change each object, where each thread just locks, modifies, and unlocks each object. Then have your updating thread join on all its child threads before returning. This punts the problem to the runtime's schedule, and it's free to schedule those child threads any way it can for best performance.
You could do this in langauges with heavier threads, but the spawn and join might have too much overhead (though thread pooling might mitigate some of this).
I don't know if there's a standard way to do this. However, I would implement this something like the following:
do
{
if (!updatedA && mutexA.tryLock())
{
scope(exit) mutexA.unlock();
updateA();
updatedA = true;
}
if (!updatedB && mutexB.tryLock())
{
scope(exit) mutexB.unlock();
updateB();
updatedB = true;
}
}
while (!(updatedA && updatedB));
Some clever metaprogramming could probably cut down the repetition, but I leave that as an exercise for you.
Sorry if I'm being naive, but do you not just Synchronize on objects to make the concerns independent?
e.g.
public Object lock1 = new Object; // access to resource 1
public Object lock2 = new Object; // access to resource 2
updateStructure1() {
synchronized( lock1 ) {
...
}
}
updateStructure2() {
synchronized( lock2 ) {
...
}
}
To my knowledge, there is not a standard way to accomplish this, and you'll have to get your hands dirty.
To paraphrase your requirements, you have a set of data structures, and you need to do work on them, but not in any particular order. You only want to block waiting on a data structure if all other objects are blocked. Here's the pseudocode I would base my solution on:
work = unshared list of objects that need updating
while work is not empty:
found = false
for each obj in work:
try locking obj
if successful:
remove obj from work
found = true
obj.update()
unlock obj
if !found:
// Everything is locked, so we have to wait
obj = randomly pick an object from work
remove obj from work
lock obj
obj.update()
unlock obj
An updating thread will only block if it finds that all objects it needs to use are locked. Then it must wait on something, so it just picks one and locks it. Ideally, it would pick the object that will be unlocked earliest, but there's no simple way of telling that.
Also, it's conceivable that an object might become free while the updater is in the try loop and so the updater would skip it. But if the amount of work you're doing is large enough, relative to the cost of iterating through that loop, the false conflict should be rare, and it would only matter in cases of extremely high contention.
I don't know any "standard" way of doing this, sorry. So this below is just a ThreadGroup, abstracted by a Swarm-class, that »hacks» at a job list until all are done, round-robin style, and makes sure that as many threads as possible are used. I don't know how to do this without a job list.
Disclaimer: I'm very new to D, and concurrency programming, so the code is rather amateurish. I saw this more as a fun exercise. (I'm too dealing with some concurrency stuff.) I also understand that this isn't quite what you're looking for. If anyone has any pointers I'd love to hear them!
import core.thread,
core.sync.mutex,
std.c.stdio,
std.stdio;
class Swarm{
ThreadGroup group;
Mutex mutex;
auto numThreads = 1;
void delegate ()[int] jobs;
this(void delegate()[int] aJobs, int aNumThreads){
jobs = aJobs;
numThreads = aNumThreads;
group = new ThreadGroup;
mutex = new Mutex();
}
void runBlocking(){
run();
group.joinAll();
}
void run(){
foreach(c;0..numThreads)
group.create( &swarmJobs );
}
void swarmJobs(){
void delegate () myJob;
do{
myJob = null;
synchronized(mutex){
if(jobs.length > 0)
foreach(i,job;jobs){
myJob = job;
jobs.remove(i);
break;
}
}
if(myJob)
myJob();
}while(myJob)
}
}
class Jobs{
void job1(){
foreach(c;0..1000){
foreach(j;0..2_000_000){}
writef("1");
fflush(core.stdc.stdio.stdout);
}
}
void job2(){
foreach(c;0..1000){
foreach(j;0..1_000_000){}
writef("2");
fflush(core.stdc.stdio.stdout);
}
}
}
void main(){
auto jobs = new Jobs();
void delegate ()[int] jobsList =
[1:&jobs.job1,2:&jobs.job2,3:&jobs.job1,4:&jobs.job2];
int numThreads = 2;
auto swarm = new Swarm(jobsList,numThreads);
swarm.runBlocking();
writefln("end");
}
There's no standard solution but rather a class of standard solutions depending on your needs.
http://en.wikipedia.org/wiki/Scheduling_algorithm