我如何打印笑脸包围的给定角色?这是我到目前为止所做的,但它只打印一个长的水平字符串。
public class Smileys {
public static void main(String[] args) {
printWithSmileys("\\:D/");
printWithSmileys("92.");
}
private static void printWithSmileys(String characterString) {
for (int i = 0; i < characterString.length(); i++) {
int numberOfSmileys = characterString.charAt(i);
for (int j = 0; j < numberOfSmileys; j++) {
System.out.print(":)");
}
System.out.println("");
}
}
}
输出应该如下所示。
:):):):):)
:) \:D/ :)
:):):):):)
:):):):):)
:) 92. :)
:):):):):)
答案 0 :(得分:1)
private static void printWithSmileys(String characterString) {
for (int i = 0; i < characterString.length(); i++) {
int numberOfSmileys = characterString.charAt(i);
这里有编译错误String.charAt(int index)返回一个char,不能设置为int数据类型。
for (int j = 0; j < numberOfSmileys; j++) {
System.out.print(":)");
}
System.out.println("");
}
}
我想你想要的是......
for (int i = 0; i < 3; i++) {
System.out.print(":)")
for (int j = 0; j < characterString.length(); j++) {
if(i % 2 != 0){
if(j == 0 || j == characterString.length()-1){
System.out.print(":)");
}else{
System.out.print(characterString.charAt(j-1));
}
}else{
System.out.print(":)");
}
}
System.out.println("");
}
没有经过测试,但是开始的好地方。
答案 1 :(得分:1)
这是一个带注释的解决方案。玩得开心:))
public static void main(String[] args) {
printWithSmileys("\\:D/");
printWithSmileys("92.");
}
private static void printWithSmileys(String string) {
// Find the length of our line in smiley
// (smiley length is 2 so we divide by 2 and add one to round up)
int length = (string.length()+1)/2;
// Add one smiley on each side, plus 2 smiley
length += 2;
// Add one smiley for the two spaces surrounding our string
length += 1;
// Add one space if length is an odd number
if (string.length()%2 != 0)
string += " ";
//Print first line
printSmileyLine(length);
//Print middle line
System.out.print(":) ");
System.out.print(string);
System.out.print(" :)");
System.out.println("");
//Print last line
printSmileyLine(length);
}
/**
* Print length smiley
*/
private static void printSmileyLine(int length) {
for (int i=0; i<length; i++)
System.out.print(":)");
System.out.println("");
}