How to column break in java

Viewed 107

Expected Output

Enter exam score:             Enter grade:
Math:                         Math:
Science:                      Science:
History:                      History:                 

                                                                    

How to get this output?

My output

Enter exam score:                
Math:                                     
Science:                                        
History:

Enter Grade:
Math:
Science:                                                        
History:

How do I enter input in the next column?

2 Answers

Sounds like you're looking for System.out.printf() where you can use %- to add padding to your strings to make them even when printing. You can adjust the exact amount of spacing by changing the 30, but this should work for you:

String mathStr = "Math:";
String scienceStr = "Science:";
String historyStr = "History:";
System.out.printf("%-30s%s\n", "Enter exam score:", "Enter grade:");
System.out.printf("%-30s%s\n", mathStr, mathStr);
System.out.printf("%-30s%s\n", scienceStr, scienceStr);
System.out.printf("%-30s%s\n", historyStr, historyStr);

Edit: Added variables to show OP it works with those as well.

OK, so I think you want to provide a way for the user to enter the data in a columnar display on a console.

That is difficult. The problem is that when the terminal driver is in normal ("cooked") mode, the console only accepts the user's input and sends it to your program when the user types ENTER. And that causes the console display driver to go to the next line.

To solve this, you have to do one of the following:

But I would recommend that you don't do this. If you want a "fancy" input screen for your users to enter input, implement it in Swing, or JavaFX, or using a web (HTML + CSS + Javascript) interface. If you need to accept input from the console, make it look like this:

Enter exam score (0-100) followed by a grade (A-F):
Math: 99 A
Science: 88 B  
History: 21 F
Related