繁体   English   中英

文本无法在控制台中正确打印

[英]Text doesn't print properly in console

我有一个由两种方法组成的简单程序。 第一个是询问玩家是否想提出建议或退出游戏的菜单。 如果他们选择提出建议,则调用第二种方法。 第二种方法是假设打印一个表单供用户填写。 所以它看起来像这样:

Person: 
Weapon:
Room: Library

库已为用户填写。 其余的可以这样填写:

Person: Professor Plum
Weapon: Revolver
Room: Library

问题是打印出来的东西看起来不像我想要的。 打印出来的内容是这样的:

Person: Weapon: 

人物和武器打印在同一行,用户只能填写武器。 此外,在武器填满之前,房间不会打印出来。 无论如何,我可以让它看起来像我在上一个例子中的布局吗?

import java.util.Scanner;

public class Main {

private String[] suggestions = new String[3];
private Scanner sc = new Scanner(System.in);
private String room = "Library";

public void menuSelection() {
    System.out.println("Please make a selection...\n");

    System.out.println("1. Make a suggestion");
    System.out.println("2. Exit game");

    int selection = sc.nextInt();

    if (selection == 1)
        makeSuggestion();
    else 
        System.exit(0);
}

public void makeSuggestion() {
    System.out.print("Person: ");
    suggestions[0] = sc.nextLine();

    System.out.print("Weapon: ");
    suggestions[1] = sc.nextLine();

    System.out.println("Room: " + room);
    suggestions[2] = room;
}

public static void main(String[] args) {
    Main main = new Main();
    main.menuSelection();
}
}

您没有打印值。 使用System.out.println()打印这些值。

System.out.print("Person: ");
suggestions[0] = sc.nextLine();
System.out.println(suggestions[0]);

System.out.print("Weapon: ");
suggestions[1] = sc.nextLine();
System.out.println(suggestions[1]);

System.out.print("Room: " + room);
suggestions[2] = room;
System.out.println(suggestions[2]);

输出:

Person: Professor Plum
Weapon: Revolver
Room: Library

使用sc.nextLine(); int selection = sc.nextInt();

这将给出欲望输出

System.out.println 将在 System.out.print 将在同一行上打印的新行上打印。 你应该使用 System.out.println() 而不是 System.out.print()

这就是导致问题的原因:

int selection = sc.nextInt();

例如,用 sc.nextLine() 替换它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM