I have a simple program consisting of two methods. The first is a menu that asks if the player wants to make a suggestion or exit the game. If they choose to make a suggestion, the second method is called. The second method is suppose to print a form for the user to fill out. So it's suppose to look like this:
Person:
Weapon:
Room: Library
Library is already filled out for the user. The rest can be filled out like this:
Person: Professor Plum
Weapon: Revolver
Room: Library
The problem is that what's printed out doesn't look like what I want. What's printed out looks like this:
Person: Weapon:
Person and Weapon are printed on the same line and the user is only able to fill out Weapons. Moreover, Room doesn't printout until Weapons is filled. Is there anyway I can make it look the way I laid out in the previous example?
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();
}
}
You are not printing the values. Use System.out.println()
to print those values.
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]);
Output:
Person: Professor Plum
Weapon: Revolver
Room: Library
Use sc.nextLine();
after int selection = sc.nextInt();
This will give desire output
System.out.println will print on a new line where System.out.print will print and the same line. you should use System.out.println() instead of System.out.print()
this is what's causing the issue:
int selection = sc.nextInt();
replace it with sc.nextLine() for example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.