我如何简化这一点并让它仍然做同样的事情?
package test;
import java.util.Scanner;
public class HI {public static void main(String[] args) {
String Welcome1 = "Welcome";
String specialWelcome1 = "Welcome Parzival";
String joinLogin1 = "What would you like to do?";
System.out.println(Welcome1);
System.out.println("Insert your name below");
Scanner scan = new Scanner(System.in);
String Person = scan.nextLine();
if (Person.equals("Parzival")) {
System.out.println(specialWelcome1);
System.out.println(joinLogin1);
String doing1 = scan.nextLine();
if(doing1.equals("Kill")) {
System.out.println("What is the password?");
String killCode = scan.nextLine();
if(killCode.equals("OASIS kill")){
System.out.println("Shutting down...");
}
if(doing1.equals("Join Game")) {
System.out.println("Joining...");
}
}
}else {
System.out.println(Welcome1 + " " + Person);
}}}
代码看起来很乱,很难读懂。我不知道如何解决这个问题。
答案 0 :(得分:-1)
显而易见的一点是,您无法减少String消息的数量。
但是,您仍然可以通过使用单个System.out.println
语句替换连续的System.out.println
语句来消除混乱,如下所示:
您的代码:
的System.out.println(specialWelcome1);
的System.out.println(joinLogin1);
格式化代码:
System.out.println(specialWelcome1 +" \ n" + joinLogin1);
对于有更多System.out.println
语句的情况,上面的格式化代码看起来很难看。在这种情况下,您可以充分利用缩进,如下所示:
> System.out.println(specialWelcome1
> +"\n"+joinLogin1
> +"\n"+joinLogin2
> +"\n"+joinLogin3
> +"\n"+joinLogin4
> +"\n"+joinLogin5
> +"\n"+joinLogin6
> +"\n"+joinLogin7
> );
此外, Suchen Oguri 的开关版本更好。您应该优先选择切换语句而不是if-else,因为它们在性能方面更好。 if-else 将逐个检查条件,直到找到匹配的条件,而switch语句则不然。
答案 1 :(得分:-2)
我没有尝试优化,只是使用开关进行组织以便轻松理解。
package test;
import java.util.Scanner;
public class HI {public static void main(String[] args) {
String Welcome1 = "Welcome", specialWelcome1 = "Welcome Parzival", joinLogin1 = "What would you like to do?";
System.out.println(Welcome1);
System.out.println("Insert your name below");
Scanner scan = new Scanner(System.in);
String Person = scan.nextLine();
switch(Person) {
case "Parzival":
System.out.println(specialWelcome1);
System.out.println(joinLogin1);
switch(scan.nextLine()) {
case "Kill":
System.out.println("What is the password?");
if(scan.nextLine().equals("OASIS kill"))
System.out.println("Shutting down...");
break;
case "Join Game":
System.out.println("Joining..."); break;
}
break;
default:
System.out.println(Welcome1 + " " + Person);
}
}
}