using printf for multiple formats - java

I have a question on how to use printf for multiple formats. I want something like this, where everything inside printf is spaced out evenly:
i i i i i
and this is how I used printf:
// display headers
System.out.printf("", "%15s", "%15s", "%15s", "%15s", "Car Type",
"Starting Miles", "Ending Miles", "Distance/Gallon",
"Gallons/Distance", "Miles/Gallon");
when I executed my program, the above wouldn't show up at all, I just go this:
run:
Gas & Mileage Calculations
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
BUILD SUCCESSFUL (total time: 0 seconds)

Just concatenate the formats:
System.out.printf("%15s%15s%15s%15s", "header 1", "header 2", ...);

The way you use printf() is wrong.
It's first parameter is String format, which will be the formatting string, which implements all further arguments.
Example:
String name = "Chris";
int age = 25;
System.out.printf("%s = %d", name, age);
This will print out "Chris = 25", because %s is converted into the variable name and %d into variable age. Check the API docs for more information.

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

Formatting a string value within a JOptionPane

I want to format a string, so instead of the value reading: 1.599999, it reads 1.59. For the rest of my program, I've been using: %.2f to format the JLabels, but when I try do that in a JOptionPane, it doesn't recognize it as format code, but as text.
EDIT:
amountEntered = JOptionPane.showInputDialog(finishPayInput, "Please enter the full total of: £%.2f" + convPrice);
amountEntered = JOptionPane.showInputDialog(finishPayInput,
String.format("Please enter the full total of: £%.2f", convPrice))
Split it out into a String variable and put it inline (I avoid putting it directly inline for smaller lines of code and easier debugging, personal preference though):
String fullTotal = String.format("Please enter the full total of: £%.2f", convPrice);
amountEntered = JOptionPane.showInputDialog(finishPayInput, fullTotal);

Replacing dynamic number of tags in string with dynamic values - Java

I've searched through this website and also google but I couldn't find a specific solution for this problem which I'm facing.
Language: Java
I have a string, let say:
String message = "I would like to have <variable>KG of rice and <variable>Litre of Milk. I only have $<variable>, is this sufficient?"
Now, user will be having three text fields which will be sorted in order to fill up the variables.
Constraints:
1) User may enter as many tag in the message
2) The number of text field which will appear is based on number of tag in the message
Is there anyway where I can replace the original message to this:
"I would like to have {0} KG of rice and {1} Litre of Milk. I only have ${2}, is this sufficient?"
I'm changing to {X} where X=order number. How to achieve this?
I've thought of using formatter, matcher but I'm getting to dead end all the time. So, can anyone help me on this?
Thank You
I am not entirely sure what you want to achieve, but if I understand the exact question correctly and you wish to replace the string <variable> in the user's input with {0}, {1}, {2} successively then I think this is the answer:
You can use a Matcher to match all occurrences of <variable>, and then iterate over the matches and use appendReplacement to replace them by {0}, {1}, {2}, etc.
So
Matcher m = Pattern.compile("<variable>").matcher(input);
StringBuffer sb = new StringBuffer();
for( int i = 0; m.find(); i++){
m.appendReplacement(sb, "{"+i+"}");
}
m.appendTail(sb);
Try this one.
String s = java.text.MessageFormat.format("I would like to have {0} KG of rice and {1} Litre of Milk. I only have ${2}, is this sufficient?",new String[]{"100","5","50"});
System.out.println(s);
Output
I would like to have 100 KG of rice and 5 Litre of Milk. I only have $50, is this sufficient?
String.format is handy instead of loops. Take a look at below:
String mesage = "I would like to have %d KG of rice and %d Litre of Milk. I only have $ %d is this sufficient?";
System.out.println(String.format(mesage, 5, 1, 10));
System.out.println(String.format(mesage, 10, 2, 50));
Refer https://www.javatpoint.com/java-string-format for different format specifiers: %d %s etc.
String mesage = "I would like to have " + kg +
"KG of rice and " + litre + "Litre of Milk. I only have $" + dollor + "
is this sufficient?";
You could use something like this:
int i = 0;
while(message.contains("<variable>")) {
message = message.replaceFirst("<variable>", "{" + i + "}");
i++;
}
This will result in:
I would like to have {0}KG of rice and {1}Litre of Milk. I only have ${2}, is this sufficient?

Getting Week for a given number from a String of the form `SunMonTueWedThuFriSat`

Ok, I am stumped here. I really looked into this and cant seem to find specifically what I am trying to do. I am two weeks into Java in school and new to programming so please pardon any errors I may make.
I am working on a string manipulation program and among other tasks in it I am to create a sting called names that holds SunMonTueWedThuFriSat, now I need to figure out how to grab and display in JOptionPane the 3 characters in that string that go with the numbers I am supposed to associate with them (0=Sun, 1=Mon, etc.) So if the user inputs 2 it should display Tue. I have a basic understanding on how to display those characters in a string, but for the life of me i cant seem to figure out how to associate those numbers with those characters. Every time I try to work something I keep getting errors and frustration.
Thanks for all your help!!!
If the days of the week has to be in a single string, you can parse the string for each 3 character substring, and store then in an ArrayList. Then, the provided number will match the index of the Day of the Week in the List.
You should be able to just use substring, since all the abbreviations are three characters.
String s = "SunMonTueWedThuFriSat";
Prompt the user to enter a number (0-6):
String in = JOptionPane.showInputDialog("Please input a number (0-6)");
Now convert it to a number
int choice = Integer.parseInt(in);
And select the right portion of the string:
String day = s.substring(choice*3, choice*3+3);
Now just show this day in a JOptionPane:
JOptionPane.showMessageDialog(null, "Information", "You chose: " + day,
JOptionPane.INFORMATION_MESSAGE));
Check HashMap.
For example:
HashMap<int, String> aWeekMap = new HashMap();
aWeekMap.put(0, "Mon");
aWeekMap.put(1, "Tue");
System.out.println(aWeekMap.get(0)); // prints Mon.
In memory you can visualize as following:
If you can use an array of string, it will be easier:
String[] names = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
int input = 2;
System.out.println("The day is " + names[input]);
use the follwing code
private ArrayList arr=new ArrayList();
arr.Add(0,names.subString(0,2);
arr.Add(0,names.subString(3,5);
arr.Add(0,names.subString(6,8);
arr.Add(0,names.subString(9,11);
arr.Add(0,names.subString(12,14);
arr.Add(0,names.subString(15,17);
arr.Add(0,names.subString(18,20);
and
JOptionPane.showInputDialog(null, "Please choose a name", "Example 1",
JOptionPane.QUESTION_MESSAGE, null, arr);

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