This question already has answers here:
How can I pad a String in Java?
(32 answers)
Closed 9 years ago.
Within a method, I have the following code:
s = s + (items[i] + ":" + numItems[i]+" # "+prices[i]+" cents each.\n");
Which outputs:
Candy: 5 # 50 cents each.
Soda: 3 # 10 cents each.
and so on . . .
Within this line, how do I get the 5, 3, etc . . to line up with each other so that it is:
Candy: 5 # 50 cents each.
Soda: 3 # 10 cents each.
This is part of a toString() method, so I can't do it with a System.out.printf
String.format() and the Formatter classes can be used.
Following code will output something like this
/*
Sample Text #
Sample Text#
*/
Code
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%1$" + n + "s", s);
}
public static void main(String args[]) throws Exception {
System.out.println(padRight("Sample Text", 15) + "#");
System.out.println(padLeft("Sample Text", 15) + "#");
}
Some more snippet for formatting
String.format("%5s", "Hi").replace(' ', '*');
String.format("%-5s", "Bye").replace(' ', '*');
String.format("%5s", ">5 chars").replace(' ', '*');
output:
***Hi
Bye**
>5*chars
Apart from this Apache StringUtils API has lot of methods like rightPad, leftPad for doing this.
Link
You can use the tab character \t in your toString()
Heres an example:
System.out.println("Candy \t 5");
System.out.println("Soda \t 10");
Candy 5
Soda 10
So in your case
s = s + (items[i] + ": \t" + numItems[i]+" # "+prices[i]+" cents each.\n");
You can maybe use the \t for inserting a tab.
try this
s = s + (makeFixedLengthString(items[i]) + ":" + numItems[i]+" # "+prices[i]+" cents each.\n");
public String makeFixedLengthString(String src){
int len = 15;
for(int i = len-src.length(); i < len; i++)
src+=" ";
return src;
}
Related
Assume i have a single string content as follows
Input:
FTX+AAA+++201707141009UTC'
FTX+BBB+++201707141009UTC'
FTX+CCC+++201707141009UTC?:??'
PISCO US LTS;?:V.D??'
SOUZA?:GB?:GB'
FTX+ZZZ+++201707141009UTC'
Expected Output:
Number of segments: 4
Input:
FTX+AAA+++201707141009UTC'
FTX+CCC+++201707141009UTC?:??'
PISCO US LTS;?:V.D??'
FTX+ZZZ+++201707141009UTC'
Expected Output:
Number of segments: 3
Basically i want to consider as same line when the delimiter ' comes with a question mark. The line delimiter is '
How to tokenize and get the count the segments in Java ???
Thanks in advance.
You can use a negative lookbehind in a regex:
String input = "FTX+AAA+++201707141009UTC'\n"
+ " FTX+BBB+++201707141009UTC'\n"
+ " FTX+CCC+++201707141009UTC?:??'\n"
+ " PISCO US LTS;?:V.D??' \n"
+ " SOUZA?:GB?:GB'\n"
+ " FTX+ZZZ+++201707141009UTC'";
String[] tokens = input.split("(?<!\\?)'\\s*");
System.out.println(tokens.length);
4
But, in the second example I would expect two segments, not three...
Another alternative to the above - but again demonstrating that the second example you post may be wrong because the third line ends with a ?' which, by your definition should not be a break.
public void test() {
test("FTX+AAA+++201707141009UTC'" +
"FTX+BBB+++201707141009UTC'" +
"FTX+CCC+++201707141009UTC?:??'" +
"PISCO US LTS;?:V.D??'" +
"SOUZA?:GB?:GB'" +
"FTX+ZZZ+++201707141009UTC'");
test("FTX+AAA+++201707141009UTC'" +
"FTX+CCC+++201707141009UTC?:??'" +
"PISCO US LTS;?:V.D??'" +
"FTX+ZZZ+++201707141009UTC'");
}
private void test(String s) {
String[] split = s.split("(?<!\\?)'");
System.out.println(split.length+"->"+Arrays.toString(split));
}
prints
4->[FTX+AAA+++201707141009UTC, FTX+BBB+++201707141009UTC, FTX+CCC+++201707141009UTC?:??'PISCO US LTS;?:V.D??'SOUZA?:GB?:GB, FTX+ZZZ+++201707141009UTC]
2->[FTX+AAA+++201707141009UTC, FTX+CCC+++201707141009UTC?:??'PISCO US LTS;?:V.D??'FTX+ZZZ+++201707141009UTC]
I think what he/she want is this:
String a = "FTX+AAA+++201707141009UTC'"
+ "FTX+BBB+++201707141009UTC'"
+ "FTX+CCC+++201707141009UTC?:??'"
+ "PISCO US LTS;?:V.D??' "
+ "SOUZA?:GB?:GB'"
+ "FTX+ZZZ+++201707141009UTC'";
String result[] = a.split("'");
List<String> stringList = new ArrayList<String>(Arrays.asList(result));
for (int i = 0; i < stringList.size(); i++) {
if (!stringList.get(i).startsWith("FTX") && i != 0) {
stringList.set(i-1, stringList.get(i-1) + stringList.get(i));
stringList.remove(i);
i--;
}
}
for (int j = 0; j < stringList.size(); j++) {
System.out.println(stringList.get(j));
}
FTX+AAA+++201707141009UTC
FTX+BBB+++201707141009UTC
FTX+CCC+++201707141009UTC?:??PISCO US LTS;?:V.D?? SOUZA?:GB?:GB
FTX+ZZZ+++201707141009UTC
This question already has answers here:
How can I pad a String in Java?
(32 answers)
Closed 6 years ago.
I am new to Java and I am trying make the hashtags to adjust to my text. For example, if I write "message hello, how are you?" I want it to print with capital letters and that the hashtags adjust themselves depending on how many characters I print. Do you have any suggestions on what I can use to make this happen?
public void addMessage() {
System.out.println("Write message followed by a text: ");
String message = readString();
System.out.println("############################################################");
System.out.println("# #");
System.out.println("#" + message.substring(7).toUpperCase() + " #");
System.out.println("# #");
System.out.println("############################################################");
}
All you need to do is calculate length of your string and output hashs specified amount of times.
The code below should be helpful.
String hashs(int len) {
return new String(new char[len]).replace("\0", "#");
}
int textLen = message.length();
System.out.println(hashs(len + 2));
System.out.println("#" + message.toUpperCase() + "#");
System.out.println(hashs(len + 2));
Something like this:
public void addMessage() {
System.out.println("Write message followed by a text: ");
String message = readString();
System.out.println(createHashes(input.length() + 2));
System.out.println("#" + createSpaces(input.length()) + "#");
System.out.println("#" + input.toUpperCase() + "#");
System.out.println("#" + createSpaces(input.length()) + "#");
System.out.println(createHashes(input.length() + 2));
}
private String createHashes(final Integer numberOfHashes) {
return new String(new char[numberOfHashes]).replace("\0", "#");
}
private String createSpaces(final Integer numberOfSpaces) {
return new String(new char[numberOfSpaces]).replace("\0", " ");
}
Example input/output:
input: Hey, you!
output:
###########
# #
#HEY, YOU!#
# #
###########
input: How you doin'?
output:
################
# #
#HOW YOU DOIN'?#
# #
################
You can use the Formatter.
String[] strings = {"one", "two", "three"};
for(String item: strings){
System.out.printf("#%20s #\n", item.toUpperCase());
}
That way the string print will always have the same width. For this example the output is:
# ONE #
# TWO #
# THREE #
I have a code that basically reads from a text file. There is a leading plus sign when it outputs because the answer is printed in a loop. How do I get rid of that singular leading plus sign? All I can think to do is to convert the ENTIRE THING to a string and then take out the first three indexes but that's way too complicated. Is there a simple way to just rearrange the logic and do it?
My code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package importtextfiles;
/**
*
* #author Hana
*/
import java.io.*;
import java.util.*;
public class InputNumData {
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("C:\\Users\\Hana\\SkyDrive\\CompSci\\Programming\\importTextFiles\\meow.txt"));
int maxIndx = -1; //so the first index is 0
String text[] = new String[1000];
while(sf.hasNext()){
maxIndx++;
text[maxIndx] = sf.nextLine();
System.out.println(text[maxIndx]);
}
sf.close();
String answer = "";
int sum;
for(int j=0; j<=maxIndx; j++){
Scanner sc = new Scanner(text[j]);
sum = 0;
answer = "";
while(sc.hasNext()){
int i = sc.nextInt();
answer = answer + " + " + i;
sum = sum + i;
}
answer = answer + " = " + sum;
System.out.println(answer);
}
}
}
My output:
run:
12 10 3 5
18 1 5 92 6 8
2 9 3 22 4 11 7
+ 12 + 10 + 3 + 5 = 30
+ 18 + 1 + 5 + 92 + 6 + 8 = 130
+ 2 + 9 + 3 + 22 + 4 + 11 + 7 = 58
BUILD SUCCESSFUL (total time: 0 seconds)
meow.txt:
12 10 3 5
18 1 5 92 6 8
2 9 3 22 4 11 7
Just change this line to
answer = answer.isBlank() ? i : answer + " + " + i;
For more details on how it works refer this.
Take your while loop, and fix the first value:
//Set up first value
int i = sc.nextInt(); //might want to check for hasNext() here
answer = i;
sum = sum + i;
while(sc.hasNext())
{
i = sc.nextInt();
answer = answer + " + " + i;
sum = sum + i;
}
First thing is not to use concatenation in a loop. Something like:
String result = ""
for (...) {
result = result + "some additonal data";
}
Creates several intermediate string objects and that's bad practice. It should be replaced with:
StringBuilder sb = new StringBuilder();
for (...) {
sb.append( "some additional data" );
}
result = sb.toString();
Which allows you to add strings without creating a new string object until you have finished appending.
Now that we are using a StringBuilder, you can have several solutions to the initial plus problem. The first, which would also work with the non-recommended string concatenation, is to keep a flag that tells you if this is the "first operand". Change your while loop to:
StringBuilder sb = new StringBuilder();
boolean firstOperand = true;
while(sc.hasNext()){
int i = sc.nextInt();
if ( firstOperand ) {
firstOperand = false;
} else {
sb.append( " + " );
}
sb.append( i );
sum = sum + i;
}
answer = sb.toString();
Another way, which is possible with a StringBuilder is to remove the extra " + " after you finish the loop. In this case, it's better to add the " + " after each operand, so that the extra one will be at the end. It's more efficient to delete from the end of a StringBuilder than from its beginning:
StringBuilder sb = new StringBuilder();
while(sc.hasNext()){
int i = sc.nextInt();
sb.append( i ).append( " + " );
sum = sum + i;
}
if ( sb.length() > 0 ) {
sb.setLength( sb.length() - 3 );
}
answer = sb.toString();
String s = new String("5");
System.out.println(1 + 10 + s + 10 + 5);
output of the following function is 115105 how ?
"+" is left associative so
1 + 10 => 11(int)
11 + s => "115"(String)
"115" + 10 => "11510"(String) 10 is converted to String
"11510" + 5 = "115105"(String) 5 is converted to String
Your code effectively functions as integer summation as long as it's possible, because the evaluation process goes from left to right. Once the String is encountered, the function switches to concatenation.
1 + 10 + "5" + 10 + 5
= (1 + 10) + "5" + 10 + 5
= 11 + "5" + 10 + 5
= 115105
String s = new String("5");
System.out.println(1 + 10 + s + 10 + 5);
Since expressions are evaluated from left to rignt your code is same as
System.out.println((((1 + 10) + "5") + 10) + 5);
So first (1 + 10) is evaluated and since it is simple integer addition you are getting 11 so your code becomes
System.out.println(((11 + "5") + 10) + 5);
Now (11 + "5") is evaluated and since one of arguments is String, it is being concatenated and result will also be String. So 11 + "5" becomes "11"+"5" which gives us String "115".
So after that our code is same as
System.out.println(("115" + 10) + 5);
and again in ("115" + 10) one of arguments is String so we are getting "115"+"10" which gives us another String "11510".
So finally we are getting to the point where we have
System.out.println("11510" + 5);
which is same as
System.out.println("115105");
(1 + 10)and 10 and 5 are regarded as three strings in your code
Java casts the integers as a string when you include a string in the addition, it becomes concatenation. Try
import java.io.*;
import java.util.*;
import java.lang.*;
public class mainactivity {
public static void main(String a[]) {
String s = new String("5");
System.out.println((1 + 10) + s + (10 + 5));
}
}
This should output 11515.
I am noticing odd behavior, at least to me, in my program.
Incorrect output:
public static void main(String[] args)
{
while(count < 3)
{
System.out.println("Count: " + count);
System.out.println("" +(count*2)+1);
count++;
}
}
Yields the following print statements:
Count: 1
21
Count: 2
41
Whereas this program:
public static void main(String[] args)
{
while(count < 3)
{
System.out.println("Count: " + count);
System.out.println((count*2)+1 + "");
count++;
}
}
yields this output:
Count: 1
3
Count: 2
5
My question is does Java 7 do something special when you put the empty string, "", at the front of a arithmetic expression that it does not do when the empty string follows that arithmetic expression?
The + operator has two meanings.
number + number means addition; string + anything means string concatenation.
The + operator is left-associative.
Therefore, "" + a + b" is parsed as ("" + a) + b
You have a problem with brackets.
("" +(count*2)) + 1
and
(count*2 + 1) + ""
are not the same.