Related
I am looking to indent a print line in Java using format but I'm a little confused by the process.
I searched around and found this which presents the following option:
String prefix1 = "short text:";
String prefix2 = "looooooooooooooong text:";
String msg = "indented";
/*
* The second string begins after 40 characters. The dash means that the
* first string is left-justified.
*/
String format = "%-40s%s%n";
System.out.printf(format, prefix1, msg);
System.out.printf(format, prefix2, msg);
I implemented it in my own code in the following way:
public class Main {
public static void main(String[] args) {
// Take in user input for report title
System.out.println("Enter a title for this report");
String msg = "=> ";
String blank = "";
String format = "%-4s%s%n";
System.out.printf(format, blank, msg);
}
}
I tried removing the blank with the following:
public class Main {
public static void main(String[] args) {
// Take in user input for report title
System.out.println("Enter a title for this report");
String msg = "=> ";
String format = "%-4s%s%n";
System.out.printf(format, msg);
}
}
But I receive the following error in IntelliJ IDEA:
Exception in thread "main" java.util.MissingFormatArgumentException:
Format specifier '%s' at
java.base/java.util.Formatter.format(Formatter.java:2672) at
java.base/java.io.PrintStream.format(PrintStream.java:1053) at
java.base/java.io.PrintStream.printf(PrintStream.java:949) at
Main.main(Main.java:32)
My question is, why is that first string required? Is there a way to do it without declaring the "blank" variable I have? I apologize if this is answered somewhere, I searched but could not find it.
This is my desired output:
Enter a title for this report
=>
You just need to change your format string:
String format = "%8s%n";
Remove one %s as you are passing one less string compared to your example code and 8 is the indent for your second line.
Use the value 8 because 1 tab = 8 spaces.
This may work.
import java.util.Formatter;
public class Main {
public static void main(String[] args) {
System.out.println("Enter a title for this report");
String msg = "=>";
String output = String.format("%6s\n",msg); //7 th line
System.out.print(output);
}
}
In the 7th line I have specified (6s) means total string will be of length 6. msg is length of 2 then remaining 4 spaces will be assigned to left(if we mention "-6" 4spaces will be assigned to right) to the string msg
I'm working with a CSV file that in places, has multiple commas and pound signs. My question is about how to remove the multiple commas and the pound signs, while leaving a single comma between fields.
The part of this task I am on is, using only java and no external libraries to sort through the csv file sort the array by price. I am to input a number as an input parameter and return that number of rows, ordered by price.
What I have currently is around 1000 lines of data that looks like this:
18,5 Ramsey Lane,See,Amerighi,samerighih#trellian.com,,£307018.48,
I need to remove the double commas and the pound sign, but for the life of me haven't been able to get it to work.
This is the line I am using for the regex.
String currentLine = line.replaceAll("[,{2}|£]", "");
This outputs a line which looks like this:
100086 Norway Maple WayMadelleGeorgeotmgeorgeotrr#hao13.com417175.60
A larger chunk of the code looks like this and by no means is it nearly finished:
public String[] getTopProperties(int n){
String[] properties = new String[n];
String file = "data.csv";
String line = "";
String splitBy = ",";
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
String currentLine = line.replaceAll("[,{2}|£]", "");
System.out.println("Current line is: " + currentLine);
String[] user = currentLine.split(splitBy);
}
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}
Issue is it's now removed all the commas and where the price and double commas used to be, they now connect.
Could use some help finding some regex that keeps a single comma between each field, as well as removing the pound sign.
You could simplify this by parsing the CSV file into a 2D array and ignoring the empty column which results from the double comma. Then parsing the currency column is a snap: just ignore the first character.
In your regex .replaceAll("[,{2}|£]", ""); the square-brackets creates a character class, so this means "replace any characters ,, {, 2, }, |, or £ with nothing".
What you really want is to replace the sequence ,,£ with a single comma, which would be .replaceAll(",,£", ",")
In java script this would be...
var line="18,5 Ramsey Lane,See,Amerighi,samerighih#trellian.com,,£307018.48,";
console.log(' original line: ' + line);
console.log('replacement line: ' + line.replace(/,,£/, ","));
update
Converting this to Java as a stand-alone test program to demonstrate that this does work, I get the following:
public class so50419207
{
public static void main(String... args)
{
String input = "18,5 Ramsey Lane,See,Amerighi,samerighih#trellian.com,,£307018.48,";
String replaced = input.replace(",,£", ",");
System.out.println("original string: " + input);
System.out.println("replaced string: " + replaced);
}
}
Running this...
$ javac so50419207.java ; java so50419207
original string: 18,5 Ramsey Lane,See,Amerighi,samerighih#trellian.com,,£307018.48,
replaced string: 18,5 Ramsey Lane,See,Amerighi,samerighih#trellian.com,307018.48,
Tried the regex (,,)(£)? and tested it in ideone :
Please find the code below:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
final String regex = "(,,)(£)?";
final String string = "18,,5 Ramsey Lane,,See,Amerighi,,samerighih#trellian.com,,£307018.48,,\n"
+ "18,,5 Ramsey Lane,,See,Amerighi,,samerighih#trellian.com,,£307018.48,,\n"
+ "18,5 Ramsey Lane,,See,Amerighi,,samerighih#trellian.com,,£307018.48,,\n"
+ "18,,5 Ramsey Lane,,See,Amerighi,,samerighih#trellian.com,,£307018.48,,";
final String subst = ",";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
}
}
Output:
Substitution result: 18,5 Ramsey Lane,See,Amerighi,samerighih#trellian.com,307018.48,
18,5 Ramsey Lane,See,Amerighi,samerighih#trellian.com,307018.48,
18,5 Ramsey Lane,See,Amerighi,samerighih#trellian.com,307018.48,
18,5 Ramsey Lane,See,Amerighi,samerighih#trellian.com,307018.48,
I've made the code so it asks the user various questions, and if the input.trim().isEmpty() a message will be given to the user and will ask the user to input again. So if the user just writes blank spaces, message given. If the user gives a few blank spaces and some characters, it will accept.
Problem right now is that I want to capitalize the first letter of the Word, but it doesn't really work. Say if the user's input start with a letter then that will be capitalized. But if there's whitespace it wont capitalize at all.
So if input is:
katka
Output is:
katka
Another example:
katka
Output is:
Katka
Code is:
String askWork = input.nextLine();
String workplace = askWork.trim().substring(0,1).toUpperCase()
+ askWork.substring(1);
while (askWork.trim().isEmpty()){
String askWork = input.nextLine();
String workplace = askWork.trim().substring(0,1).toUpperCase()
+ askWork.substring(1);
}
I've tried different approaches but no success.
The problem is because of whitespace as all the indices you refer while converting to uppercase are not accurate.
So first trim() the String so you can clear all leading and trailing whitespace and then capitalize it.
better check empty string and all whitespace to avoid exception.
String askWork = input.nextLine().trim();
String capitalized = askWork.substring(0, 1).toUpperCase() + askWork.substring(1)
The trim() method on String will clear all leading and trailing whitespace. The trimmed String must become your new String so that all indices you refer to after that are accurate. You will no longer need the replaceAll("\\s",""). You also need logic to test for empty input. You use the isEmpty() method on String for that. I've written a toy main() that keeps asking for a word and then capitalizes and prints it once it gets one. It will test for blank input, input with no characters, etc.
public static void main(String[] args) throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String askWork = "";
while (askWork.isEmpty()) {
System.out.println("Enter a word:");
askWork = input.readLine().trim();
}
String workPlace = askWork.substring(0,1).toUpperCase() + askWork.substring(1);
System.out.println(workPlace);
}
Try trimming your input to remove the whitespace, before attempting to capitalize it.
String askWork = input.nextLine().trim();
String capitalized = askWork.substring(0, 1).toUpperCase() + askWork.substring(1)
However, if the input is only whitespace, this will result in an IndexOutOfBoundsException because after trim() is called askWork is set to the empty string ("") and you then try to access the first character of the empty (length 0) string.
String askWork = input.nextLine().trim();
if(askWork.isEmpty()) {
// Display error
JOptionPane.showMessageDialog(null, "Bad!");
else {
String capitalized = askWork.substring(0, 1).toUpperCase() + askWork.substring(1)
JOptionPane.showMessageDialog(null, "It worked! -- " + capitalized);
}
You will need to trim the input before you start manipulating its contents:
String askWork = input.nextLine().trim();
String workplace = askWork.substring(0,1).toUpperCase() + askWork.substring(1);
Another solution without substrings:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String askWork = input.nextLine().trim();
while (askWork.isEmpty())
askWork = input.nextLine().trim();
char[] workChars = askWork.toCharArray();
workChars[0] = workChars[0].toUpperCase();
String workplace = String.valueOf(workChars);
// Work with workplace
input.close();
}
I was wondering if someone can show me how to use the format method for Java Strings.
For instance If I want the width of all my output to be the same
For instance, Suppose I always want my output to be the same
Name = Bob
Age = 27
Occupation = Student
Status = Single
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
System.out.println(String.format("%-20s= %s" , "label", "content" ));
Where %s is a placeholder for you string.
The '-' makes the result left-justified.
20 is the width of the first string
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
If you want a minimum of 4 characters, for instance,
System.out.println(String.format("%4d", 5));
// Results in " 5", minimum of 4 characters
To answer your updated question you can do
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
prints
Name = Bob
Age = 27
Occupation = Student
Status = Single
EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.
#Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
For decimal values you can use DecimalFormat
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
and output will be:
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
For more details look here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
I was wondering if someone can show me how to use the format method for Java Strings.
For instance If I want the width of all my output to be the same
For instance, Suppose I always want my output to be the same
Name = Bob
Age = 27
Occupation = Student
Status = Single
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
System.out.println(String.format("%-20s= %s" , "label", "content" ));
Where %s is a placeholder for you string.
The '-' makes the result left-justified.
20 is the width of the first string
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
If you want a minimum of 4 characters, for instance,
System.out.println(String.format("%4d", 5));
// Results in " 5", minimum of 4 characters
To answer your updated question you can do
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
prints
Name = Bob
Age = 27
Occupation = Student
Status = Single
EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.
#Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
For decimal values you can use DecimalFormat
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
and output will be:
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
For more details look here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html