Your code contains multiple unrelated errors.
Array initializers not allowed
{"saturday", "sunday"}
That's not legal java, except in very specific places.
Specifically, in the initializing expression of either a local variable, or field declaration whose type is an array, that is legal, and it isn't legal anywhere else. In other words, okay:
String[] x = {"saturday", "sunday"};
And that's about the only place you can legally write that. If you want an expression that resolves to a string array with 2 'values', the first one being "saturday" and the second being "sunday", you write:
new String[] {"saturday", "sunday"};
This is also legit in variable declarations:
String[] x = new String[] {"saturday", "sunday"};
But you can 'shorten' it and omit the new String[]
part there.
Parameter confusion
In your main app you pass "long"
as parameter to your getWeekends
method, but your getWeekends()
method declaration accepts zero parameters. You need to fix that:
public static void getWeekends(String type) {
Return type confusion
You write return
in your getWeekends method, i.e. you want to return something. Specifically, you want to return a string array. However, you've declared it to return nothing (void
means: I return nothing). You must fix this:
public static String[] getWeekends(String type) {
Pointless creation of day
It looks like that whole day
thing is you trying random stuff, flailing about and having no idea what to do. Let's just get rid of it? Remove the stuff from String[] day
to day[3]=
; you can simply switch on type
, which is the parameter you got from whatever called you.
Your app does nothing
A return value is just... Returned. To the caller. The caller needs to do something with it. Perhaps, here, as an example, we shall print it. Let's add that to your main method using System.out.println(Arrays.toString(the-array-here))
.
null
confusion
null
should not be used unless you really know what you are doing and you have a clear definition of things. It most certainly should not be used as 'stand in' for an error condition. Just throw something if a code path occurs that you don't know how to deal with. The default
case should throw something instead of returning null
.
Putting it all together
Thus:
class App {
public static void main(String[] args){
String[] dayNames = App.getWeekends("long");
System.out.println(Arrays.toString(dayNames));
}
public static String[] getWeekends(String type) {
switch(type) {
case "long":
return new String[] {"saturday","sunday"};
case "short":
return new String[] {"sat", "sun"};
default:
throw new IllegalArgumentException("Pass either 'short' or 'long'");
}
}
}