How to adjust characters in JAVA [duplicate] - java

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 #

Related

How to match line size with regex?

I have the following code, trying to match pyramids of increasing * count, surrounded by an equivalent number of spaces on either side.
//pyramid
var p = " * \n" +
" *** \n" +
" ***** \n" +
" ******* \n" +
" ********* \n" +
"***********\n";
//not a pyramid - rows 2 and 3 do not increase in width
var np = " * \n" +
" ***** \n" +
" ***** \n" +
" ******* \n" +
" ********* \n" +
"***********\n";
//pyramid with more width variation, non-point top
var pspace = " ** \n" +
" **** \n" +
" ********** \n" +
" ************** \n" +
" **************** \n" +
"**********************\n";
final var REGEX = "((?<S>\\s*)(?<star>\\**)\\k<S>\\R(?=$|((?<S2>\\s*)(?<extra>\\*+)\\k<star>\\k<extra>\\k<S2>\\R)))+";
System.out.println("p is a pyramid: "+Pattern.matches(REGEX, p));
System.out.println("np is a pyramid: "+Pattern.matches(REGEX, np));
System.out.println("pspace is a pyramid: "+Pattern.matches(REGEX, pspace));
Output:
p is a pyramid: true
np is a pyramid: false
pspace is a pyramid: true
The final thing I want to do is make sure that all "lines" of the input string are of equal length. At this point, I got completely stuck, as I couldn't really find anything but fixed-length String bounds (i.e. X{min, max}). So, here's what I'm wondering:
How can I make sure that all the lines within my string are pyramids (increasing number of stars from first line to last line (done), separated by new lines (done), centered within the spaces (done), and equal length lines (???))?
How can I simplify my regex to reduce the overuse of named capturing groups?
Regular expressions are incapable of doing the type of counting you are trying to accomplish, so you have to use a mixed strategy. Break up the string on newline boundaries then use a regular expression to match the leading and trailing spaces and the asterisks between them. But you will then have to see if the lengths of these matches meet your requirements by seeing how long these strings are using the length method that String objects possess:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class test
{
public static void main(String[] args) {
String p = " * \n" +
" *** \n" +
" ***** \n" +
" ******* \n" +
" ********* \n" +
"***********\n";
String[] lines = p.split("\n");
Pattern pattern = Pattern.compile("^(\\s*)(\\*+)(\\s*)$");
int lastLength = 0;
boolean isPyramid = true;
for (String line : lines) {
Matcher m = pattern.matcher(line);
m.find();
String spaces1 = m.group(1);
String spaces2 = m.group(3);
String asterisks = m.group(2);
int len = asterisks.length();
if (len <= lastLength || spaces1.length() != spaces2.length()) {
isPyramid = false;
break;
}
else {
lastLength = len;
}
}
System.out.println("p is a pyramid: " + isPyramid);
}
}

How to tokenize the string with and without delimiter in single split

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

Having trouble printing to same line

I'm trying to write a code where you enter an integer in the console, and then the integer you entered is shown bigger, made up of letters (like ascii art).
So let's say the input is 112. Then the output will be
# # #####
## ## # #
# # # # #
# # #####
# # #
# # #
##### ##### #######
My code will have the same output, just not in the same line :(
It will print one number under the other.. From my code you can see why:
import java.util.Scanner;
public class Tester {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String any = input.nextLine();
String[] sArray = any.split("");
for(int i=0; i<sArray.length; i++){
if(sArray[i].equals("1")){
System.out.println(" # ");
System.out.println(" ## ");
System.out.println("# # ");
System.out.println(" # ");
System.out.println(" # ");
System.out.println(" # ");
System.out.println("#####");
}
if(sArray[i].equals("2")){
System.out.println(" ##### ");
System.out.println("# #");
System.out.println(" #");
System.out.println(" ##### ");
System.out.println("# ");
System.out.println("# ");
System.out.println("#######");
}
}
}
}
I somehow have to print all at once, not single output with println as my code..
Maybe there is an easy way to solve that, preferably without changing my entire code? I can imagine it could be done with a 2d array as well, but not sure. Hints are very welcome too. And this is no homework.
Dirty but works:
private static final Map<Integer, String[]> art = new HashMap<Integer, String[]>() {{
put(1, new String[] {
" # ",
" ## ",
" # # ",
" # ",
" # ",
" # ",
" ##### " });
put(2, new String[] {
" ##### ",
"# #",
" #",
" ##### ",
"# ",
"# ",
"#######" });
}};
public static void main(String[] args) {
int[] input = { 1, 1, 2 };
for (int row = 0; row < 7; row++) {
for (int num : input) {
System.out.print(art.get(num)[row] + " ");
}
System.out.println();
}
}
I skipped the scanner code and assumed an input of 1 1 2.
Output
# # #####
## ## # #
# # # # #
# # #####
# # #
# # #
##### ##### #######
Use String or StringBuilder to store each line and last print all strings.
import java.util.Scanner;
public class Tester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String any = input.nextLine();
String[] sArray = any.split("");
String str1 = "";
String str2 = "";
String str3 = "";
String str4 = "";
String str5 = "";
String str6 = "";
String str7 = "";
for (int i = 0; i < sArray.length; i++) {
if (sArray[i].equals("1")) {
str1 += " # ";
str2 += " ## ";
str3 += "# # ";
str4 += " # ";
str5 += " # ";
str6 += " # ";
str7 += "#####";
}
if (sArray[i].equals("2")) {
str1 += " ##### ";
str2 += "# #";
str3 += " #";
str4 += " ##### ";
str5 += "# ";
str6 += "# ";
str7 += "#######";
}
}
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
System.out.println(str6);
System.out.println(str7);
}
}
Suggested logic:
place the strings, line by line, in arrays:
private static final String[] ONE = { " # ",
" ## ",
... };
run two nested for loops:
for (int i = 0; i < heightOfPrintedDigits; i++) {
for (String number : sArray) {
... //use print here but finish with an empty println("") to insert a new line
}
}
Use string arrays to store the multi-line representation of each number, and then use a map to store all the numbers. A string number can serve as the key, which would return a string array representation for that string number.
final int NUM_HEIGHT = 7;
String any = "1 1 2";
String[] one = new String[] {
" # ",
" ## ",
"# # ",
" # ",
" # ",
" # ",
"#####"};
String[] two = new String[] {
" ##### ",
"# # ",
" # ",
" ##### ",
"# ",
"# ",
"####### "};
Map<String, String[]> map = new HashMap<>();
map.put("1", one);
map.put("2", two);
String[] numbers = any.split("\\s");
for (int i=0; i < NUM_HEIGHT; ++i) {
StringBuilder line = new StringBuilder();
for (String number : numbers) {
line.append(map.get(number)[i]);
line.append(" ");
}
System.out.println(line);
}

What's Wrong? Number Of Words In a Sentence Java

int numOfWords = str.length() - str.replace(" ", "").length();
Why does that not work? If str is equal to "Hello bye", numOfWords should equal 2, but when ran numOfWords equals 0. Any help would be greatly appreciated!
You are only replacing one blank, so the output will be 1 (at least this is what is produce in my JVM)
If you want to know the number of words then either add 1 to this number or use
str.split(" ").length;
Why dont you use :
int numOfWords = str.split(" ").length;
I hope out put is much clear
public static void main(String[] args) {
String str = "Hello bye";
System.out.println("Length of Input String = " + str.length() + " for String = " + str);
System.out.println("Length of Input String with space removed = " + str.replace(" ", "").length() + " for String = "
+ str.replace(" ", ""));
int numOfWords = str.length() - str.replace(" ", "").length();
System.out.println(numOfWords);
}
Output
Length of Input String = 9 for String = Hello bye
Length of Input String with space removed = 8 for String = Hellobye
1

Formatting within a string [duplicate]

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

Categories