This site requires JavaScript, please enable it in your browser!
Greenfoot back
nerdlemon888
nerdlemon888 wrote ...

2012/7/2

Are new java 7 features working?

nerdlemon888 nerdlemon888

2012/7/2

#
{ String temp = /*some string */ switch(temp) { case "enter": // action A case "shift": // action B case "tab": // action C case "space": // action D case "backspace": // action E } } This is some code that won't compile because Greenfoot complains that the switch operation is not supported in this case (Assume the commented out stuff works). The error is literally given, "strings in switch are not supported in -source 1.6 (use -source 7 or higher to enable strings in switch). My problem is that Java 7 is the only SE version installed on my computer, but it somehow treats it as Java 6 (based on what I'm seeing). I am running Greenfoot v 2.2.1 at the moment. Can I get any help with this? Note that I did get a couple other Java 7-specific features such as the new multiple-exception handling thread.
SPower SPower

2012/7/2

#
Just use an if statement for strings:
if (string.equals(....)) {
.....
} else if [etc....]
danpost danpost

2012/7/2

#
You could also run your strings together and get the index, as follows:
String specialKeys = "entershifttabspacebackspace";
switch (specialKeys.indexOf(temp))
{
    case 0: // temp = "enter"
        break;
    case 5: // temp = "shift"
        break;
    case 10: // temp = "tab"
        break;
    case 13: // temp = "space"
        break;
    case 18: // temp = "backspace"
        break;
}
mjrb4 mjrb4

2012/7/3

#
@danpost - eurgh. I wouldn't do that, it's rather ugly to say the least! Just use a bunch of if statements as SPower suggested if you need to do that, it's much clearer code to read. If you *must* insist on using switch then you can potentially switch on the hashcode of strings, but bear in mind there is the potential for collisions there, however small. In terms of Java 7 features - they're deliberately not enabled for compatibility reasons. If someone were to run a scenario on the gallery uploaded with Java 7 source features, and they only had Java 6 installed, then their code wouldn't run. Granted Java 7 introduces some nice new features, but trying to deal with different major versions appropriately in this way would be much more hassle than its worth.
You need to login to post a reply.