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

时间:2015-09-29 05:02:01

标签: java

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

Person: 
Weapon:
Room: Library

已为用户填写了库。其余的可以填写如下:

Person: Professor Plum
Weapon: Revolver
Room: Library

问题在于打印出的内容看起来不像我想要的。打印出来的内容如下:

Person: Weapon: 

人和武器印在同一条线上,用户只能填写武器。此外,在Weapons填满之前,Room不打印。无论如何,我可以让它看起来像我在上一个例子中列出的方式吗?

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();
}
}

4 个答案:

答案 0 :(得分:1)

您没有打印值。使用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

答案 1 :(得分:1)

sc.nextLine();

之后使用int selection = sc.nextInt();

这将给出欲望输出

答案 2 :(得分:0)

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

答案 3 :(得分:0)

这就是造成这个问题的原因:

int selection = sc.nextInt();

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

相关问题