Having trouble printing to same line - java

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

Related

Printing elements of the array on the same line, when a single element uses "\n" replacement to draw a letter

I found an assignment where I am supposed to print user input as big letters written with '#'.
As in
user input: "ta"
output:
########## #
# # #
# # #
# #######
# # #
# # #
I've written below code and it works fine however it prints a everything on a new line due to
system print line I am replacing "," with "\n" so obviously it goes to a new line in order to draw
the letter properly, and there is a system print in the for loop ( instead of system print )
so it would look proper when printing the letters under each other. However is there a way to print the letters one after another rather than under each other? If I am replacing "," with /n can I get back to the first "print line" before printing element [1] instead of [0]?
Any suggestions would be appreciated.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Please input a sentence you would like to convert: ");
Scanner sc = new Scanner(System.in);
String sentence = sc.next();
String alphabet = "abcdefghijklmonpqrstuvwxyz";
char[] sentenceArray;
sentenceArray = sentence.toCharArray();
for (int i = 0; i < sentenceArray.length; i++) {
for (int j = 0; j < alphabet.length(); j++) {
if (sentenceArray[i] == alphabet.charAt(j)) {
System.out.println(Arrays.toString(letters[j]).replace(",", "\n").replace("[", "")
.replace("]", ""));
}
}
}
}
private static String[][] letters =
{
{
" # ",
" # # ",
" # # ",
" ####### ",
" # # ",
"# # "
},
{
"####### ",
"# # ",
"####### ",
"# # ",
"# # ",
"####### "
},
{
" ###### ",
" # # ",
"# ",
"# ",
"# # ",
" ##### "
},
{
"####### ",
"# # ",
"# # ",
"# # ",
"# # ",
"###### "
},
{
"######### ",
"# ",
"######## ",
"# ",
"# ",
"######### "
},
{
"######### ",
"# ",
"######## ",
"# ",
"# ",
"# "
},
{
" ###### ",
" # # ",
"# ",
"# ###### ",
"# # ",
" ##### "
},
{
"# # ",
"# # ",
"######### ",
"# # ",
"# # ",
"# # "
},
{
" ### ",
" # ",
" # ",
" # ",
" # ",
" ### "
},
{
" ##### ",
" # ",
" # ",
" # ",
" # # ",
" ### "
},
{
"# # ",
"# # ",
"##### ",
"# # ",
"# # ",
"# # "
},
{
"# ",
"# ",
"# ",
"# ",
"# ",
"######### "
},
{
"# # ",
"# # # # ",
"# # # ",
"# # ",
"# # ",
"# # "
},
{
"# # ",
"# # # ",
"# # # ",
"# # # ",
"# # # ",
"# # "
},
{
" ###### ",
" # # ",
"# # ",
"# # ",
"# # ",
" #### "
},
{
"######## ",
"# # ",
"####### ",
"# ",
"# ",
"# "
},
{
" ###### ",
" # # ",
"# # ",
"# # ",
"# ## ",
" #### # "
},
{
"######## ",
"# # ",
"####### ",
"# # ",
"# # ",
"# # "
},
{
" ###### ",
"# ",
" ###### ",
" # ",
"# # ",
" ##### "
},
{
"##########",
" # ",
" # ",
" # ",
" # ",
" # "
},
{
"# # ",
"# # ",
"# # ",
"# # ",
" # # ",
" ### "
},
{
"# # ",
"# # ",
" # # ",
" # # ",
" # # ",
" # "
},
{
"# # ",
"# # ",
"# # ",
"# # # ",
" # # # # ",
" # # "
},
{
"# # ",
" # # ",
" # ",
" # # ",
" # # ",
"# # "
},
{
"# # ",
" # # ",
" # ",
" # ",
" # ",
" # "
},
{
"######### ",
" # ",
" # ",
" # ",
" # ",
"######### "
}
};
}
Do not use Arrays.toString() for this. The letters are 6 lines tall, so your outermost loop has to iterate those 6 lines. Inside that you iterate the letters of the user input.
Like this:
Loop 6 lines: for (int line = 0; line < 6; line++)
Loop the letters of the user input: for (char letter : sentenceArray)
Print the appropriate "line" for the letter using print: TODO by You!
End the line: println()
Work out everything you need to print before printing anything, then you can print the top of all letters in the first row, then the second of all letters at once etc.
sentenceArray = sentence.toCharArray();
String[] rowsToPrint = new String[6];
for (int i = 0; i < 6; i++) {
rowsToPrint[i] = "";
}
for (int i = 0; i < sentenceArray.length; i++) {
for (int j = 0; j < alphabet.length(); j++) {
if (sentenceArray[i] == alphabet.charAt(j)) {
for (int k = 0; k < 6; k++){
rowsToPrint[k] = rowsToPrint[k] + letters[j][k];
}
}
}
}
for (int k = 0; k < 6; k++){
System.out.println(rowsToPrint[k]);
}

Problems with Output in Java

I have no idea why my output is not coming out correct. For example, if the input is "Running is fun" then the output should read "Is running fun". However, the output I am getting is "Iunning".
import java.util.Scanner;
public class Problem1 {
public static void main( String [] args ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String sentence = sc.nextLine();
int space = sentence.indexOf(" ");
String firstWord = sentence.substring(0, space + 1);
String removedWord = sentence.replaceFirst(firstWord, "");
String newSentence = removedWord.substring(0,1).toUpperCase() +
firstWord.substring(1).toLowerCase();
System.out.println("");
System.out.println( newSentence );
}
}
removedWord.substring(0,1).toUpperCase() this line adds the capitalized first letter of the second word in the sentence. (I)
firstWord.substring(1).toLowerCase(); adds every letter of the first word to the end of the sentence. (unning)
Thus this creates the output of Iunning. You need to add the rest of removedWord to the String, as well as a space, and the first letter of firstWord, as a lower case letter at the space in removedWord. You can do this more by using indexOf to find the space, and then using substring() to add on firstWord.toLowerCase() right after the index of the space:
removedWord = removedWord.substring(0, removedWord.indexOf(" ")) + " " +
firstWord.toLowerCase() +
removedWord.substring(removedWord.indexOf(" ") + 1,
removedWord.length());
String newSentence = removedWord.substring(0,1).toUpperCase() +
removedWord.substring(1, removedWord.length());
Output:
Is running fun
Your problem is that
firstWord.substring(1).toLowerCase()
Is not working as you expect it to work.
Given firstWord is “Running“ as in your example, then
”Running“.substring(1)
Returns ”unning“
”unning“.toLowerCase()
Obviously returns ”unning“
The problem is at String newSentence. You not make the right combination of firstWord and removedWord.
This is how should be for your case:
String newSentence = removedWord.substring(0, 1).toUpperCase() // I
+ removedWord.substring(1,2) + " " // s
+ firstWord.toLowerCase().trim() + " " // running
+ removedWord.substring(2).trim(); // fun
EDIT(add new solution. credits #andy):
String[] words = sentence.split(" ");
words[1] = words[1].substring(0, 1).toUpperCase() + words[1].substring(1);
String newSentence = words[1] + " "
+ words[0].toLowerCase() + " "
+ words[2].toLowerCase();
This works properly:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String sentence = sc.nextLine();
int space1 = sentence.indexOf(' ');
int space2 = sentence.indexOf(' ', space1 + 1);
if (space1 != -1 && space2 != -1) {
String firstWord = sentence.substring(0, space1 + 1);
String secondWord = sentence.substring(space1 + 1, space2 + 1);
StringBuilder newSentence = new StringBuilder(sentence);
newSentence.replace(0, secondWord.length(), secondWord);
newSentence.replace(secondWord.length(), secondWord.length()+ firstWord.length(), firstWord);
newSentence.setCharAt(0, Character.toUpperCase(newSentence.charAt(0)));
newSentence.setCharAt(secondWord.length(), Character.toLowerCase(newSentence.charAt(secondWord.length())));
System.out.println(newSentence);
}
}

How to adjust characters in JAVA [duplicate]

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 #

Java String.format() syntax

I'm trying to print the following output on the screen.
#
##
###
####
#####
######
This is my code,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = Integer.parseInt(sc.nextLine());
for(int i= 1; i <= num; i++){
String spc = String.format("%" + (num - i) + "s", " ");
String hash = String.format("%" + i + "#", "#");
System.out.println(spc+hash);
}
}
I get the following error,
Exception in thread "main" java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = #
at java.util.Formatter$FormatSpecifier.failMismatch(Formatter.java:4298)
at java.util.Formatter$FormatSpecifier.printString(Formatter.java:2882)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2763)
at java.util.Formatter.format(Formatter.java:2520)
at java.util.Formatter.format(Formatter.java:2455)
at java.lang.String.format(String.java:2940)
at Solution.main(Solution.java:13)
I can understand my String.format has not been done right, but the docs are confusing on printing the character # Any help appreciated.
You could try like this:
for (int i = 1; i <= num; i++) {
String spc = (i == num) ? "" : String.format("%" + (num - i) + "s", " ");
String hash = String.format("%" + i + "s", "#").replace(' ', '#');
System.out.println(spc + hash);
}
Output:
#
##
###
####
#####
######
I guess you wanted to write:
String hash = String.format("%" + i + "s", "#");
Reading the error message helped me in finding this error, though you didn't marked where line 13 is.
Try this
for(int i= 1; i <= num; i++)
{
if((num-i)>0)
{
String spc = String.format("%" + (num - i) + "S", " ");
String hash = String.format("%" + i + "s", "#");
System.out.println(spc+hash);
}
}
I came across the same output. Here is one solution. Just in case someone stumbles again.
Instead of creating # and spaces separately, We can define width to the format method. Refer Java String Format Examples
String hash = "";
for (int i = 1; i <=n; i++) {
hash+="#";
System.out.println(String.format("%"+n+"s",hash));
}

Java split line not working

this is my code
//Numbers (Need errors on sort and numbers)
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n"))
{
//split the already split line with "n thename "
String[] LineSplit2 = line.split("n " + LineSplit[0] + " ");
String text = "var " + LineSplit[1] + "=" + LineSplit2[0] + ";";
text = text.replace("\n", "").replace("\r", "");
JAVASCRIPTTextToWrite += text;
}
}
the line of text is
n number 1
the output should be
var number = 1;
but the output is
var number=n number = 1;
can some one please tell me how to fix this? the code looks right but doesn't work :(
String line = "n number 1";
String JAVASCRIPTTextToWrite="";
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n"))
{
//split the already split line with "n thename "
String[] LineSplit2 = line.split("n " + LineSplit[1] + " ");
System.out.println( LineSplit[1]);
System.out.println( LineSplit2[0]);
String text = "var " + LineSplit[1] + "=" + LineSplit2[1] + ";";
text = text.replace("\n", "").replace("\r", "");
JAVASCRIPTTextToWrite += text;
System.out.println(JAVASCRIPTTextToWrite);
}
}
String number = "n number 1";
Sting[] temp = number.split(" ");
StringBuilder sb = new StringBuilder("var ");
sb.append(temp[1]);
sb.append(temp[2]);
perform this operation if your condition satisfied
String line = "n number 1";
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n")) {
//split the already split line with "n thename "
String LineSplit2 = line.substring(line.lastIndexOf(" ") + 1 , line.length());
String text = "var " + LineSplit[1] + "=" + LineSplit2 + ";";
//text = text.replace("\n", "").replace("\r", "");
System.out.println(text);
}
}
Output:
var number=1;
I do not know what is your purpose for split the string twice. Just for the out put you want, I think the solution below is enough. Please look at the code below whether is you want:
String line = "n number 1";
String JAVASCRIPTTextToWrite = "";
//Numbers (Need errors on sort and numbers)
if(line.contains("n")) {
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit.length == 3) {
StringBuilder text = new StringBuilder();
text.append("var ");
text.append(LineSplit[1]);
text.append("=");
text.append(LineSplit[2]);
text.append(";");
JAVASCRIPTTextToWrite += text.toString().replace("\n", "").replace("\r", "");
System.out.println(JAVASCRIPTTextToWrite);
}
}

Categories