Array inside a switch [duplicate] - java

This question already has answers here:
Array initialization syntax when not in a declaration
(4 answers)
Closed 8 years ago.
I'd like to ask if anyone knows how can I use the same array in a switch with different values for the different cases without getting error.
I have this code:
String [] measures;
switch(option){
case "Distance":
measures= {"Quilometers(km)", "Meters(m)"};
break;
case "Temperature":
measures= {"Celsius(ºC)", "Fahrenheit(ºF), "Kelvin(K)"};
break;
(...)
I'm getting the error "Array initializer is not allowed here" where I have measure={...}
But if I change the code and write inside each case,
String [] measures= {...}
I get the error "Variable measures is already defined in the scope".
Can you please help?

You can't initialize array with just braces { and } when you are not declaring the variable. But you can't re-declare measures because it has already been declared in the same block.
You need to explicitly use new String[] before the braces. Try
measures = new String[] {"Quilometers(km)", "Meters(m)"};
and likewise for your other cases.

Just say measures = new String[] {" instead of measures= {"....

Firstly, the String[] measures is not initialised. You should add in values in the array with String measures={...} or measures=new String[size];and then some values.
Secondly, and more importantly, Strings can not be used properly in a switch-case construct. It only tests equality and should be used only for intand char. Cheers!

Related

Why does the output for while (arar==arr){ arr[0]=2; } display this ([I#60e53b93)? [duplicate]

This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 1 year ago.
I basically see this in the output screen every time I am trying to set two non-boolean types equal to each other using a binary operator.
What I do not understand is, if the compiler goes on and compiles it but displays [I#60e53b93 (which seems to me to be an address),
is it because it is using arr as an object or is it because it is actually working and the loop is running infinitely?
So what I was trying to do was just experiment with arrays and see what I could do with them because it's been a while since I worked with Java.
So what I basically did was:
int [] arr = {1,2,3,4,5,6};
int[]arar={1,2,3,4,5,6};
while (arar==arr){
arr[0]=2;
}
System.out.println(arr);
and so I was basically expecting a red flag but then the code ran and displayed [I#60e53b93 which I did not understand why?
Can somebody explain this to me and if possible how I can display the array arr even if it is in a continuous loop?
Two things are going on here:
arr will never equal arar because == uses reference equality; since arr and arar can be modified independently, they aren't the same object.
System.out.println(anyArray) will always display output like yours, because arrays don't have a useful toString function.
You can solve both problems by using static methods from Arrays:
while (Arrays.equals(arr, arar)) {
...
}
System.out.println(Arrays.toString(arr));
Because arr is just a reference to an array. It's not the content of the array. The reference holds the memory location where the actual content of the array is. Calling toString() on an Object will by default output its memory location. (toString() will implicitly be called by System.out.println)
Every object in Java has a toString() method. Though you can call System.out.println basically on everything. Some objects have a custom toString implementation and print something useful, and others (like arrays) just print their memory location.
If you want to display the array contents, you have to loop over the array:
for(int elem : arr) {
System.out.println(elem);
}

Java - Never Quitting While Loops [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I am trying to create a file system/file commander in java, and I want to make the following loop a quit system that triggers when I type dc.
public static void main(String[] args)
boolean x; x=true;
String dc; dc="dc";
while (x=true) {
System.out.println("_____________________");
System.out.println("local disk C:");
System.out.println("bin");
System.out.println("_____________________");
String ltstcmdddd; ltstcmdddd = ltstcm.nextLine();
if (ltstcmdddd==dc) {
break;
}
}
So this is the code for the file commander, it's part of a game so ltstcm is a scanner, and lstcmd is a string you use to input commands for the game (Can't re-use it, I kept adding d's.), like I said before I want to leave this loop when I write dc, I made an if that checked lstcmdddd, I tried with checkingif (lstcmdddd=="dc") and that didn't work. I suspected that changing the value of the boolean x wouldn't work after discovering 'break', that failed. I then tried defining the string dc which contained "dc", and that didn't work either. I searched Stack Overflow about quitting loops, quitting loops failing, and changing values after defining a variable correctly. Nothing relevant to my problem, nothing I could salvage to solve the problem. (I AM NOT ASKING ABOUT COMPARISON!)
You cannot use the == comparison for strings, you have to use .equals, ie: lstcmdddd.equals("dc").
In Java, Strings are objects, so you cannot compare them using the double equal operator. As you are doing that however, your conditional will always return false and the break statement will never execute.
You should rather use .equals than ==. == is used to compare a single char or number, while .equals is used to compare strings.
[...]
String ltstcmdddd; ltstcmdddd = ltstcm.nextLine();
if (ltstcmdddd.equals(dc)) {
[...]
Use ltstcmdddd.equals(dc) instead of ltstcmdddd==dc
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal

String Array Assignment in Java [duplicate]

This question already has answers here:
Arrays constants can only be used in initializers error
(5 answers)
Closed 4 years ago.
Code:
String Foo[];
Foo={"foo","Foo"};
Error at Line 2: Illegal Start of expression
The code works if I say:
String Foo[]={"foo","Foo"};
Why does this happen, and how should I do the required without generating an error? This also happens with other data types.
Would appreciate if you could explain in layman terms.
{"foo","Foo"} is an array initializer and it isn't a complete array creation expression:
An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.
Java Specification
Use new String[] {"foo","Foo"} instead.
You have to initialize the string array:
String foo[] = new String[]{"foo, "Foo"}; Or
String foo[] = {"foo, "Foo"};
Modern IDEs give error for not initializing the array objects. You can refer more details here:
http://grails.asia/java-string-array-declaration

Java function definition with brackets syntax [duplicate]

This question already has answers here:
Java Syntax: byte f()[] vs. byte[] f()
(4 answers)
Closed 3 years ago.
Was looking in the source for ByteArrayOutputStream, and I saw this function:
public synchronized byte toByteArray()[] {
return Arrays.copyOf(buf, count);
}
Where is this syntax documented? I mean the [] in front of the function. Is this the same as in declaring a regular array where the bracket can go after the name of the array or before, but in this case, the bracket can go after the function name?
String[] args;
Vs
String args[];
Edit: 2018-05-22
I found even more uses of this crazy syntax here: 10 things you didn't know about Java
#3 is where they make mention of all the ways the above syntax can be exploited
In JLS Sec 8.4:
MethodDeclarator:
Identifier ( [FormalParameterList] ) [Dims]
...
The declaration of a method that returns an array is allowed to place some or all of the bracket pairs that denote the array type after the formal parameter list. This syntax is supported for compatibility with early versions of the Java programming language. It is very strongly recommended that this syntax is not used in new code.

Which one is preferable? [duplicate]

This question already has answers here:
Time complexity for java ArrayList
(6 answers)
Closed 6 years ago.
I am getting arraylist.get(i) every time a loop executes more than three times within the loop.
Is it advisable or shall I store it in separate variable then use it again and again? Which one is preferable performance wise?
Setting it to a variable is slightly more efficient. Accesing arrayList.get (I) is O (1) but still costs something eventhough it is really minor and insignificant.
Setting it to a variable is more readable in my opinion.
It's always a good approach to write readable and maintainable code. Since you question is very broad so expect broad answers as well.
List<Integer> integerList = new ArrayList<>();
for (int i=0;i<integerList.size();i++) {
Integer integerValue = integerList.get(i);
// make sure integerValue is not null.
// Thanks #Tom for pointing this out
System.out.println (integerValue);
// Do operations
System.out.println (integerValue);
// Do more operations
System.out.println (integerValue);
}
Now this is one time assignment but you can use it at multiple times. Now, for instance, you have to change the logic of program so that you want to get always i+1, it will be easy for you to change only once, not multiple times.
As others mentioned, getting object one time is slightly more efficient. Of course most of times this won't produce any problems and you can't notice any differences.
Logically because it's an O(1) operation, it shouldn't cause any differences at all, but because it calls a function of an object of type ArrayList , It's less cache friendly and direct memory reference maybe needed. Still the difference is very little.
declaring and assigning a variable once like String myString = arraylist.get(i); will be marginally faster than calling arraylist.get(i) multiple times.
Once you've done this you can call any methods on the myString instance.
I assume that arraylist is of type ArrayList<String>.
you may want to include a null check in your loop as well:
for(int i = 0; i < arraylist.size(); i++){
String myString = arraylist.get(i);
if(myString != null){
//any calls to methods on myString
}
}

Categories