I am currently using an toString() method to print out an array list. It works but the output comes out all wonky in the console when it prints out. I was wondering is anyone would point out to me where i am going wrong or even direct me to a tutorial that would help better explain his type of formatting.
Method i am using:
rental number, release and releaseYear are all ints.
film , fname, studio are all strings
public String toString()
{
//Returns a String
return String.format("DVDDetails [%s |\t\t %s \t\t | \t\t %s | %s | %s| %s| ]",rental, fFName, FAName, studio, releaseYear);
}
Because the fFname results in a string with varrying number of characters, it looks like that. The formater has no idea of the next line so the tab is only effective on its own line. you better off add spaces depending on the length of the string you have. count number of characters and add spaces. have a max value with the largest length of fFname and other strings values.
You can look in java documetns for inserting spaces in formatting. something like"%-20s %s"
Related
I have s string in which * can come at arbitrary number. The regex pattern I use doesnt split at the beginning. I do not want to do the String.substring() to remove the * in the beginning. It can be that I have something like "***place1*place2**place3*". Or something like placeStr=**
String placeStr="*place1*place2**place3*";
String[] places=placeStr.split("(\\*)+");
System.out.println("array size" + places.length);
Also while using String.split("(\\*)+")to remove the placeStr=** gives a wrong array size if the input string is something like ***. In this case I get array size as one. But I expect array size to be zero, since there is no places inside the array. What I want to count is the number of places.
If you don't want to deal with empty strings while doing split in case there are multiple stars in the beginning, just replace the stars in beginning and then just do a simple split.
Sample code,
public static void main(String[] args) {
String placeStr = "***place1*place2**place3*";
placeStr = placeStr.replaceAll("^[*]+", "");
String[] places = placeStr.split("[*]+");
System.out.println("places.length: " + places.length);
Arrays.asList(places).forEach(System.out::println);
}
Prints,
places.length: 3
place1
place2
place3
Let me know if this is what you wanted to do.
Editing answer to clarify about split:
Considering your code,
String placeStr="*place1*place2**place3*";
String[] places=placeStr.split("(\\*)+");
System.out.println("array size: " + places.length);
You will get,
array size: 4
because the first star in the string splits and gives empty string. But if you remove all the stars in the beginning of string and make your code like this,
String placeStr="place1*place2**place3*";
String[] places=placeStr.split("(\\*)+");
System.out.println("array size: " + places.length);
Then this will output array size as,
array size: 3
The last star(s) (or any char) characters in the string does not behave like the first characters, and upon splitting, they don't give empty string in the last array elements.
This is how splitting a string by a regex works in java. Let me know if you had some other expectation, may be due to which you are saying it is giving you wrong output.
Hope this clarifies.
Also, can you let me know what you want to achieve logically?
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
I have a toString() method from my class that takes the information from the object and puts it into a string to be printed.
This is what it should look like:
Susan 70 <Average C
Alexander 80 >Average B
, but I'm having trouble formatting my toString() method. This is what it looks like this right now which is very unorganized.
public String toString() {
return ("\n" + fullName +
" " + relativeScore +
" " + testScore);
}
I would normally use printf, but since it's a return statement I can't use it. Any help would be much appreciated.
Depending on what you want to achieve, you could simply use String#format, for example:
System.out.println(String.format("%-10s %d %10s %5s", "Susan", 70, "<Average", "C"));
Which outputs
Susan 70 <Average C
For more details have a look at this example and Formatter
String.format method returns a new String object, so you can use it rather than printf, for instance:
public String toString() {
return String.format("%s\t%3d\t%s", fullName, relativeScore, testScore);
}
You could use String.format() and do it just like you would do with printf()
return String.format("whatever comes here");
you're doing it wrong way. Susan is 5 letter word and Alexander is 9 letter word. So if susan is followed by 10 white spaces then alexander should be followed by 10-9+5= 6 white spaces. You should consider the length of fullname in your code.
For example, say I want to write to a text file, and I want to line up my results into columns like so:
Peanut Butter Crunchy
Jelly Purple
Bread Wheat
Milk Whole
\t obviously doesn't line up the second column when the first words are different lengths. Is lining them up possible?
Yes, it is possible. You want to pad the strings to the right with white spaces. For example, if you specify that each column starts every 20 characters and your string is 12 characters, you need to add 8 whitespace characters to the end.
You could hand code a loop or you could use string.format(). I took a look around online and found this easy method which you can use. http://www.rgagnon.com/javadetails/java-0448.html
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
s is the string that you want to pad, n is the ideal length.
For example,
padRight("test", 10") -> "test "
To add to your code, just format each line. For example, for your first line, you could do
String line = padRight(peanutButterString, 20) + peanutButterAttribute
Make sure your values are in an array and you can easily loop through it and create the properly formatted string.
I'm writing a program that generates star wars names. The user inputs their first, last, mother's maiden name, birth city, and first car and the program gives a star wars name. I need the last two characters* of the user inputted last name. I know I can use substring, but I cannot get anything to work. The best I have is:
lastname.substring(lastname.length() -2)
which gives the first two letters of the last name, and not the last. Also, I cannot use lastname.substr(-2) because substr for some reason won't work (not sure why, this would be much easier).
Thanks for any help.
*EDIT: I hope I didn't confuse anyone, I need the last two characters of the last name.
Actually I see my problem now: my original last name variable is
String lastname = console.nextLine().substring(0,2).trim().toUpperCase();
which keeps the first two letters, so the reason I was getting the first two letters was because of this. I understand now. Is there a way to get the last two letters from this same variable?
So if the name was Michael, you just want Micha?
Try:
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
For example:
String lastName = "Michael";
String trimmedLastName = lastName.substring(0, lastName.length() - 2);
System.out.println(trimmedLastName); // prints Micha
The reason mine works and yours doesn't is because the first parameter of substring is where to start. So I start from the first letter, and end on the second last letter (not inclusive).
What yours does is start on the second last letter, and continue on until the end of the string.
However, if you wanted just el from Michael, you could do this:
String lastName = "Michael";
String trimmedLastName = lastName.substring(lastName.length() - 2);
System.out.println(trimmedLastName); // prints el
Try this out,
lastname.substring(lastname.length() -3,lastname.length() -1);
If you need the different ways, here:
StringBuffer myString = new StringBuffer(inputString);
myString.revert();
StringBuffer userInput = new StringBuffer(myString.subString(2));
String result = userInput.revert();
Have a nice day.
Because String is immutable so when you call subString it doesn't change the value of lastname.
I think you should do:
String genName = lastname.subString(lastname.lengh()-2);
lastname.substring(lastname.length() - 2) should return the last 2 letters.
lastname.substring(0, 2) returns the first two.
substring(index) is includive
substring(index1, index2) is inclusive, exclusive respectively.