Console output alignment - java

Hi I'm trying to align output to the console window in Java using NetBeans.
ATM I have a collection of MP3Tracks (classes) in an arraylist. The user is able to sort the track by artist, album & track name etc after the sort the reordered list is via the console:
System.out.println(vector);
My MP3Track class overrides toString():
#Override
public String toString(){
return(String.format("Track No: %-8s Track Title: %-25s Artist Name: %-15s Album Name: %-20s Track Length: %-10s", trackNo , trackTitle, artistName, albumName, trackLength + "\n"));
}
This solution works for all but the first line which is line and the first and last digit output is []. I would like all lines to line up and to remove both [] at the beginning and end. I'm a first year Software Engineering student and this in my first assignment in Java so please excuse my inexperience!
I would very much appreciate some suggestion here.
Many thanks in advance..

You are printing your vector using
System.out.println(vector);
it calls vector's toString() method to get its String representation and Java's String representation for Collections is formatted like:
[element1.toString(), element2.toString, ... ]
You can just iterate over your vector and print your MP3Tracks:
for (MP3Track mp3Track : vector) {
System.out.println(mp3Track);
}
And remove the \n at the end of your the string representation of MP3Track, it would be nicer that way.
Alternatively, you create a subclass of Vector class and override its toString() method and use it but that would be overkill imo.

You should not rely on toString() to present data to the end-user. toString is meant for debug purposes. The braces are there because the array's toString prints them.
When you want to present data to the user, you should use an external viewer class, that prints things just like they should be printed, according to you.
This, or you can create a List implementation that delegates to a JavaSE collection and overrides toString, but I'd really dislike this way of doing things.
Something like:
public class TrackViewer {
private static final String FORMAT
= "Track No: %-8s Track Title: %-25s "
+ "Artist Name: %-15s Album Name: %-20s "
+ "Track Length: %-10s\n";
private String getTrackLine(Track t) {
return String.format(FORMAT,
t.getTrackNo(),
t.getTrackTitle(),
t.getArtistName(),
t.getAlbumName(),
t.getTrackLength());
}
public void listTracks(Iterable<Track> tracks) {
StringBuilder bdr = new StringBuilder();
for (Track t : tracks) {
bdr.append(getTrackLine(t));
}
System.out.print(bdr.toString());
}
}

Related

How can I capture recurring user inputs in a loop and then display them all at the end of the program?

I am a beginner to Java and have written a 260+ line code, menu-driven, procedural-type program. Unfortunately, I must abide by the rules that pertain to Academic Conduct of my university and I cannot paste what code I have here at this exact moment in time, although I will do my best to explain my conundrum in the hopes that more knowledgeable folk can point me in the right direction. I don't necessarily expect solutions in the form of code. My countless Internet searches have been fruitless and I'm kind of lost and frustrated, even with all my reading materials, countless search query combinations and hours poring over forums, including this one.
Basically, my program is almost finished. It's a reservations system that has a few menus asking for user input. There are a few do-while iterations and conditional statements that allow the user to return back to the main menu once they've entered their inputs, along with some basic error validation.
My main issue is with the final submenu; I enter three values using Scanner (all strings) and I can even print those three values to the console prior to being returned to the main menu. If I enter that same submenu again and enter three different inputs, it overwrites the previous set of inputs. Now, I understand that this is to be expected each time the "nextLine" method is invoked but I must capture each individual set of inputs for a reservations summary at the end of the program.
I've tried to store the values in both single and multidimensional arrays along with for (foreach?) loops but they simply fill up the entire index range with the same three values. I've also tried string concatenation, StringBuilder and ArrayLists but the continuous overwriting of those values makes it near impossible for me to achieve anything meaningful with them. Ideally, I just want to enter the values, preserve them somehow, enter and save more values and then retrieve them all at the very end of the program so I can display them using formatted Strings. The maximum number of entries I can make in the submenu is 10. At the risk of asking a vague question, what method would strike you as being the most suitable here? Once I know what tree I have to bark up, I can simply research my way to an answer. This "100 different ways of reaching the same satisfactory outcome" nature of Java - and dare I say programming languages in general - is rather overwhelming for a beginner like me.
An ArrayList would be suitable for the situation. It allows you to add new items to it dynamically, which is exactly what you are trying to do here, isn't it?
But first, I suggest you encapsulate the "three values" that you kept talking about into a class. From what you said, they represent some information about reservations. I'll call this class Reservation:
class Reservation {
// name these variables properly!
private String someValue1;
private String someValue2;
private String someValue3;
#Override // this returns a formatted string representation of a reservation
public String toString() {
return "someValue1: " + someValue1
+ "\nsomeValue2: " + someValue2
+ "\nsomeValue3: " + someValue3;
}
public Reservation(String someValue1, String someValue2, String someValue3) {
this.someValue1 = someValue1;
this.someValue2 = someValue2;
this.someValue3 = someValue3;
}
}
Now you can create an ArrayList<Reservation>:
// put this outside of any method
static ArrayList<Reservation> reservations = new ArrayList<>();
Whenever the user goes to the submenu, you will do something like this, right?
String someValue1 = scanner.nextLine();
String someValue2 = scanner.nextLine();
String someValue3 = scanner.nextLine();
After those lines, create a Reservation:
Reservation reservation = new Reservation(someValue1, someValue2, someValue3);
And put it into the reservations list:
reservations.add(reservation);
When you want to print all the reservations, you just:
for(Reservation r : reservations) {
System.out.println(r);
System.out.println();
}
Not sure I understand the issue, but it seems like you could add your input values to a List<String[]>
List<String[]> data = new ArrayList<>();
// get your first 3 data, add them to the list
data.add(new String[] {"value 1", "value 2", "value 3"});
// get your first 3 new data, add them to the list
data.add(new String[] {"value 4", "value 5", "value 6"});
Then you can print them out
for(String[] values: data) {
System.out.println(values[0] + " | " + values[1] + " | " + values[2] );
}
Outputs
value 1 | value 2 | value 3
value 4 | value 5 | value 6

JAVA Array of values need to store in multiple fields based on size

I am Trying to split this string into array format and trying to store in the field name1,name2.. based on the size of the values and the name filed must have only 26 characters.
Name:
Bommiraj Sitaramanjaneyulu Rajasekhara Srinivasulu Laxminarayana Siva
Venkata Sai
Expected Result: name1= Bommiraj Sitaramanjaneyulu ,name2=Rajasekhara srinivasulu,name3=Laxminarayana Siva Venkata,name4=sai,name5="".
Actual result: name field 1:Bommiraju Rajasekhara Siva,name field 2:Venkata Sai
String Testname=nameFormat(" Bommiraj Sitaramanjaneyulu Rajasekhara Srinivasulu Laxminarayana Siva Venkata Sai ");
String formatedName=name.trim().replaceAll("\\s{2,}", " ");
String[] splitedName = formatedName.split("\\s+");
String name1="";
String name2="";
String name3="";
String name4="";
String name5="";
for (String string : splitedName) {
if (name1.length()==0) {
name1+=string;
}else if (name1.length()>0 && name1.length()<26){
if (string.length()+name1.length()<26) {
name1+=" "+string;
}
}else if (name2.length()==0) {
name2+=string;
}else if (name2.length()>0 && name2.length()<26) {
if (string.length()+name2.length()<26) {
name2+=" "+string;
}
}
}
If you count up the size of the first name, Bommiraju Sitaramanjaneyulu, there are 26 characters and a space. Your if statements are <26 so will only work up to 25 characters without whitespace.
More generally, I would recommend storing the names as a String[] and tracking where you are up to. In your current code, a name might go to string2, but a shorter, later name can go to string1, which I assume is not what you wish to do. What I would recommend, depending on your exact needs, would be to start on string[0], and fill it up until the current string doesn't fit, then move onto string[1] and fill that up, etc.

Java -Modify my To String method

I need to modify my toString method. The instructions are "Modify the toString method so that, first of all, it sorts the list of paychecks and then, it iterates through them to print them one at a time. We don’t want to include the [] around the elements in the ouput." I already have a sort method I wrote which I can call via PayrollUtility.sortArray(array); My current toString() method is:
public String toString() {
return String.format("\n%-27s%s\n", "Employee ID:", employeeID) +
String.format("%-27s%s\n", "First Name:", firstName) +
String.format("%-27s%s\n", "Last Name:", lastName) +
String.format("%-27s%s\n", "Date of Birth:", dateOfBirth) +
String.format("%-27s%s\n", "Date Hired:", dateHired) +
String.format("%-27s%s\n", "Accrued Vacation Hours:", accruedVacationHours) +
String.format("%-27s%s\n", "Amount Paid Year to Date:", PayrollUtility.convertToCurrencyStringLeftAligned(yearToDate)) +
String.format("%-27s%s\n", "Paychecks Received:", listOfPaychecks);
}
My question is how do I remove the [] from displaying? Should I use a for loop to iterate through the list of paychecks?
Edit: I figured it out right after posting. Thank you guys for the speedy responses.
Yes, you should use a for loop to iterate through the list of paychecks and print each separately, or concatenate them into a new string.
The alternative would be to just continue to call the List's toString and remove the two brackets.
That can easily be done with a substring call.
But manual looping gives you finer control over how you want to print each individual entry, which is maybe something you want in the future, if just to break them into multiple lines.

Searching a String array to find portions of elements

I have a String array that has individuals names in it (example):
["John Smith", "Ramon Ruiz", "Bill Bradford", "Suzy Smith", "Brad Johnson"]
I would like to write a method that prompts a user to input (in form of String) a name OR portion of a name, and then lists all names that contain the string entered by the user, (I can fix the case issue easily).
ex:
Name: rad (meaning user enters "rad")
Output:
Bill Bradford
Brad Johnson
Does anyone have any ideas on this (one that also preserves white spaces)? If there already is a good example of this, feel free to link me. I was unable to find a good method in API.
I would use
for(String name : names) {
if(org.apache.commons.lang3.StringUtils.containsIgnoreCase(name, stringToLookFor)) {
// Do your thing
}
}
You can use .indexOf() it return -1 if it does not find a subString into a String.
for(String name : myArray)
{
if (name.indexOf("rad") != -1) {
// contains word
}
}

How to use String.format() in Java to replicate tab "\t"?

I'm printing data line by line and want it to be organized like a table.
I initially used firstName + ", " + lastName + "\t" + phoneNumber.
But for some of the larger names, the phone number gets pushed out of alignment
I'm trying to use String.format() to achieve this effect. Can anyone tell me the format syntax to use?
I tried String.format("%s, %s, %20s", firstName, lastName, phoneNumber), but that's not what I want. I want it to look like this:
John, Smith 123456789
Bob, Madison 123456789
Charles, Richards 123456789
Edit:
These answers seem to work for System.out.println(). But I need it to work for a JTextArea. I'm using textArea.setText()
Worked it out. JTextArea doesn't use monospaced fonts by default. I used setFont() to change that, and now it works like a charm. Thank you all for the solutions.
consider using a negative number for your length specifier: %-20s. For example:
public static void main(String[] args) {
String[] firstNames = {"Pete", "Jon", "Fred"};
String[] lastNames = {"Klein", "Jones", "Flinstone"};
String phoneNumber = "555-123-4567";
for (int i = 0; i < firstNames.length; i++) {
String foo = String.format("%-20s %s", lastNames[i] + ", " +
firstNames[i], phoneNumber);
System.out.println(foo);
}
}
returns
Klein, Pete 555-123-4567
Jones, Jon 555-123-4567
Flinstone, Fred 555-123-4567
Try putting the width into second placeholder with - sign for right padding as:
String.format("%s, %-20s %s", firstName, lastName, phoneNumber)
This will give the specified width to the second argument(last name) with right padding and phone number will start after the specified width string only.
EDIT: Demo:
String firstName = "John";
String lastName = "Smith";
String phoneNumber = "1234456677";
System.out.println(String.format("%s, %-20s %s",firstName, lastName, phoneNumber));
prints:
John, Smith 1234456677
The only alternative is loop the names list, calculate the maximum length of the String, and add whitespaces as needed after every name to ensure that all the numbers begin at the same column.
Using tabs has the disavantage that you cannot know a priori how many whitespace are equivalent to a tab, since it is dependent of the editor.

Categories