java居中的命令_用JAVA把语句排列成左对齐、右对齐、居中

展开全部

我来试试……

主要使用StringBuilder的replace(start, end, str)方法, 把一个字符串中先填满空格,再计算位置,替换成你要的字符。注意636f70793231313335323631343130323136353331333363386165:这里有个小坑:在新建一个StringBuilder的时候,虽然看上去里面已经填充了字符,但实际上是空的;假如不从头到尾填充空格(" "),在replace()时Java会认为字符串的长度是0,从而出现java.lang.StringIndexOutOfBoundsException: start > length()

最后,sample里面的antidisestablishmentarianistic长达30个字符,而测试数据中给的行长是20,需要考虑(假如字词长度大于输入的20,则需要加长行长)。

最后的代码:(还有一点:题目的import里面包括了java.util.Arrays,但我代码没用,不知道会不会被认为是没有观察题意而判错。也许是我多心了)import java.util.ArrayList;

import java.util.List;

public class Assign1Q2 {

protected static char[] justify(char[] inputText, int lineWidth, char just) {

StringBuffer sb = new StringBuffer("");

List words = new ArrayList();

for (int i=0; i

if (inputText[i] != ' ' && inputText[i] != '\n') {

sb.append(inputText[i]);

} else {

inputText[i] = '\n';

words.add(sb.toString());

sb = new StringBuffer(""); //clear content

}

}

words.add(sb.toString()); //add last word because the last char is not space/'\n'.

for (int i=0; i

if (words.get(i).length() >= lineWidth) {

lineWidth = words.get(i).length();

}

}

char[] output = null;

StringBuilder sb2 = new StringBuilder("");

StringBuilder line = null;

for (String word: words) {

line = new StringBuilder("");

for (int i=0; i

line.append(" ");

}

switch (just) {

case 'l':

line.replace(0, word.length(), word);

break;

case 'r':

line.replace(lineWidth-word.length(), lineWidth, word);

break;

case 'c':

int rest = lineWidth-word.length(); //all the spaces' length

int begin = 0;

if (rest % 2 != 0) {

begin = (int)(rest/2)+1;

} else {

begin = rest/2;

}

line.replace(begin, begin+word.length(), word);

break;

}

line.append('\n');

sb2.append(line);

}

output = sb2.toString().toCharArray();

return output;

}

}

最后效果:The

quick

brown

antidisestablishmentarianistic

fox

jumps

over

the

lazy

dog

The

quick

brown

antidisestablishmentarianistic

fox

jumps

over

the

lazy

dog

The

quick

brown

antidisestablishmentarianistic

fox

jumps

over

the

lazy

dog

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值