Java -Modify my To String method - java

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.

Related

Splitting a String and then displaying a portion of that split (last name part)

Hey I'm having an issue with the following problem. I understand how to split the formalName variable (a first " " last name) but now I'm having trouble just displaying the last name so I can generate the formalName ("Mr./Ms. " lastName) can anyone help?
Complete the generateFormalName method so that… you return the formal
name (Mr. or Ms. + last name) given a full name and gender (Strings)
as parameters.
--You can assume a valid name & gender (any case allowed) is passed in. Example 1: ("Bob Smith", "MaLE") passed in should generate "Mr.
Smith" Example 2: ("Maggie May", "feMALE") passed in should generate
"Ms. May"
Tip 1: You are given a String formalName initialized to the empty
String -- you will want to concatenate other Strings onto this to
produce the full formalName.
Tip 2: Write your algorithm in English first.
Tip 3: Think of all of the methods at your disposal and which could be
helpful.
split() function returns you an array of strings. You need to get second element from the array. You can try something like this:
String fullName = "John Smith";
String lastName = fullName.split(" ")[1];
String formalName = "Mr./Ms. " + lastName;

Extra java input validation for strings

I want to make this so that short inputs can still be detected, such as "Londo" and "Lon", but want to keep it small and use it without basically copying and pasting the code, any tips? thank you.
if (Menu.answer1.equals("London"))
{
if (location.equals("London")) {
System.out.print(location + " ");
System.out.print(date + " ");
System.out.print(degrees + "C ");
System.out.print(wind + "MPH ");
System.out.print(winddirection + " ");
System.out.print(weather + " ");
System.out.println("");
}
You can use startsWith()
String city = "London";
if (city.startsWith("Lon")) {
// do something
}
Also if you need to check some substring, you can use contains method:
Menu.answer1 = "London";
Menu.answer1.contains("ondo"); // true
If you want to check against a fixed set of alternatives, you may use a list of valid inputs using contains:
List<String> londonNames = Arrays.asList("London", "Londo", "Lon");
if (londonNames.contains(Menu.answer1)) {
...
}
You can use (case-insensitive) regex to do the same, e.g.:
(?)Lon[a-z]{0,3} where
(?) = case insensitivity
Lon = Initial 3 characters
[a-z]{0,3} = any number of alphabets between 0 and 3
Here's an example:
String regex = "(?)Lon[a-z]{0,3}";
System.out.println("London".matches(regex));
System.out.println("Lond".matches(regex));
System.out.println("Lon".matches(regex));
If the underlying problem is that the user can enter one of several names, and you want to allow abbreviations, then a fairly standard approach is to have a table of acceptable names.
Given the user input, loop through the table testing "does the table entry start with the string typed by the user?" (like one of the previous answers here). If yes, then you have a potential match.
Keep looking. If you get a second match then the user input was ambiguous and should be rejected.
As a bonus, you can collect all names that match, and then use them in an error message. ("Pick one of London, Lonfoo, Lonbar").
This approach has the advantage (compared to a long chain of if-then-else logic) of not requiring you to write more code when all you want to do is have more data.
It automatically allows the shortest unique abbreviation, and will adjust when a once-unique abbreviation is no longer unique because of newly-added names.

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

Console output alignment

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

String equality in Java using ArrayList of HashMaps? I am using .equals()

I'm trying to remove items from a List of HashMaps, and when looking at the console output, it's plainly clear that the strings being compared are equal, and I am using the .equals(String x) method to compare, however the output of this continually shows false, and nothing gets removed from the list. Could anyone give me a hint as to what I'm doing wrong here?
public void removeWord(String wd) {
Log.println(Log.INFO, "Initial Size", "Initial size" + String.valueOf(allWords.size()));
for (int x = 0; x < allWords.size(); x++) {
Log.println(Log.INFO, "Current Word", allWords.get(x).get("Long") + " " + wd);
Log.println(Log.INFO, "Equality?", String.valueOf(allWords.get(x).get("Long").toUpperCase().equals(wd)));
if (allWords.get(x).get("Long").toUpperCase().equals(wd)) {
allWords.remove(x);
Log.println(Log.INFO, "Removed something", "Removed Something!!!!");
clearAdapter();
}
}
Log.println(Log.INFO, "Size of list", "Size of list" + String.valueOf(allWords.size()));
}
You are comparing the uppercase value of the String mapped to "Long" to the original value of wd. Unless wd is being passed in as uppercase you could be off. Try using equalsIgnoreCase and also make sure that both strings don't have leading or trailing spaces by calling trim. I hope that helps!
When you solve the problem, which may be caused by extraneous invisible characters in the string or the values - try comparing lengths in your logs as well - you should use an iterator to go over allwords and the iterator's remove method, or you may get an inconsistent iteration.

Categories