Ich bin gerade dabei, etwas über Methoden in Java zu lernen und war neugierig zu wissen, ob es schlechte Praxis ist, eine Methode als Argument innerhalb einer anderen Methode zu übergeben. Obwohl ich weiß, dass es viele Möglichkeiten gibt, dieselbe Lösung zu erreichen, gibt es Zeiten, in denen Code, die auf eine Weise geschrieben wurden, effizienter ist als andere. Rufen Sie dann beide Methoden an und zeigen Sie die Ergebnisse anhand der folgenden Bewertungsdaten (1500, 900, 400, 50). < /P>
Meine Lösung wurde wie folgt geschrieben: < /p>
public class Main {
public static void main(String[] args) {
displayHighScorePosition("Fred",calculateHighScorePosition(1500));
displayHighScorePosition("Ted", calculateHighScorePosition(900));
displayHighScorePosition("Jen", calculateHighScorePosition(400));
displayHighScorePosition("John",calculateHighScorePosition(50));
}
public static void displayHighScorePosition(String name, int highScorePosition) {
System.out.println(name + " managed to get into position " + highScorePosition + " on the high score table");
}
public static int calculateHighScorePosition(int score) {
int position = 4;
if(score >= 1000) {
position = 1;
} else if (score >= 500) {
position = 2;
} else if (score >= 100) {
position = 3;
}
return position;
}
}
< /code>
Dies zeigte dieselbe Ausgabe wie die von der Übung erwartete, aber der in der Übung geschriebene Code war < /p>
public class Main {
public static void main(String[] args) {
int highScorePosition = calculateHighScorePosition(1500);
displayHighScorePosition("Fred", highScorePosition);
int highScorePosition = calculateHighScorePosition(900);
displayHighScorePosition("Ted", highScorePosition);
int highScorePosition = calculateHighScorePosition(400);
displayHighScorePosition("Jen", highScorePosition);
int highScorePosition = calculateHighScorePosition(50);
displayHighScorePosition("John", highScorePosition);
}
public static void displayHighScorePosition(String name, int highScorePosition) {
System.out.println(name + " managed to get into position " + highScorePosition + " on the high score table");
}
public static int calculateHighScorePosition(int score) {
int position = 4;
if(score >= 1000) {
position = 1;
} else if (score >= 500) {
position = 2;
} else if (score >= 100) {
position = 3;
}
return position;
}
}
< /code>
macht es einen Unterschied? d.h. ist man eine bessere Möglichkeit zu schreiben oder werde ich auf den Weg gehen, wenn der Code viel komplexer wird?
Ist es in Java eine schlechte Praxis, eine Methode als Argument in einer anderen Methode zu verabschieden? ⇐ Java
-
- Similar Topics
- Replies
- Views
- Last post