Reputation: 9
How could I make some numbers right justified? I don't understand. I'm really new to Java. :-/ For example whenever I try to make this code right justified it gives me errors. Here is some sample code I found:
import java.util.Scanner;
public class JFindAlphabete
{
static Scanner sc = new Scanner(System.in );
public static void main(String[] Theory)
{
JWaffles MyWaffles = new JWaffles();
MyWaffles.ProgramHeading();
System.out.println("Enter a string:" );
String SentenceContents = sc.nextLine( );
int SpaceCount = SentenceContents.length() - SentenceContents.replaceAll(" ", "").length( );
int VowelCount = SentenceContents.length() - SentenceContents.replaceAll("(?i)[aeiou]", "").length( );
int ConsonantCount = SentenceContents.length() - SentenceContents.replaceAll("(?i)(?=[a-z])[^aeiou]", "").length( );
int SpecialCharCount = SentenceContents.length() - SentenceContents.replaceAll("(?i)[^a-z ]", "").length( );
int WordCount = SentenceContents.trim().split("\\s+").length;
System.out.println("There are " + VowelCount + " vowels in this sentance" );
System.out.println("There are " + ConsonantCount + " consonants in this sentance" );
System.out.println("There are " + SpaceCount + " spaces in this sentance" );
System.out.println("There are " + SpecialCharCount + " special characters in this sentance");
System.out.println("There are " + WordCount + " words in this sentance" );
}
}
Upvotes: 1
Views: 107
Reputation: 726509
You can use System.out
's printf
method instead of println
, and use formatting options to right-adjust the values that you print:
System.out.printf("There are %5d vowels in this sentance\n" , VowelCount);
System.out.printf("There are %5d consonants in this sentance\n" , ConsonantCount);
and so on.
Upvotes: 1
Reputation: 8606
Use the System.out.format
class with, for instance, System.out.format("There are %2d vowels in this sentence", vowelCount)
You can read a good tutorial at http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Upvotes: 1
Reputation: 27539
Take a look at java.util.Formatter
.
It allows you to print according to a predefined format, including fixed width numbers (with space padding).
It's probably the closest you'll get to 'right-justifying' these numbers.
Upvotes: 0