java中带for循环的回车(初学者)
我正试着做一个像这样的直方图java中带for循环的回车(初学者),java,junit,Java,Junit,我正试着做一个像这样的直方图 #################### ################ ########################## ############ 这是我的密码 public String generateHistogramA(List<Thingy>things) { String a=""; String b=""; for(int i=0;i<things.size();i++) {
####################
################
##########################
############
这是我的密码
public String generateHistogramA(List<Thingy>things)
{
String a="";
String b="";
for(int i=0;i<things.size();i++)
{
a="";
for(int j=0;j<=things.get(i).count;j++)
{
a=a+"#";
}
b+=a+System.getProperty("line.separator");
}
System.out.print(b);
return b;
}
当我在main中使用该方法时,它的结果与Junit测试相同..但是当我运行它时,测试没有通过..我不知道它出了什么问题。。
请…如果有人知道发生了什么。。。
谢谢
试验结果如下所示:
junit.framework.AssertionFailedError:预期的:但是是:就像是思考的食物一样 这更接近于我会怎么做。找出为什么会有学习的机会;-)
public String generateHistogramA(列出事物)
{
字符串newLine=System.getProperty(“line.separator”);
StringBuilder sb=新的StringBuilder();
为了(事物:事物)
{
对于(int j=0,count=thingy.count;j当assertEquals
失败时,它会给您一个比较以查看差异。您能给我们演示一下吗?为什么不在断言之前立即使用调试器检查result
和expResult
?为了避免系统的整个问题。getProperty…
,您可以使用S字符串格式(“此处为我的字符串%n”)
和%n
将替换为正确的行分隔符。它也较短。实际上,我发现string newLine=System.getProperty(“line.separator”);
比string newLine=string.format(“%n”)更容易理解;
,即使我大脑的某些部分知道它们是等效的。@DavidWallace我必须使用这个Junit测试,因为这是老师要求的。.最初的测试使用System..lineSeparator(),但因为我的计算机不支持平台1.7,我将它改为System.getProperty(“line.separator”)…并尝试了String.format(“%n”)和“\n”…测试仍然失败。。
@Test
public void testGenerateHistogramA() {
System.out.println("generateHistogramA");
Histogram instance = new Histogram();
String expResult = "##############################################################################################################"+System.getProperty("line.separator")+"####################"+System.getProperty("line.separator")+
"########################################"+System.getProperty("line.separator")+
"################################################################################################################################################################" +System.getProperty("line.separator")+
"################################################################################"+System.getProperty("line.separator");
String result = instance.generateHistogramA(things);
assertEquals(expResult, result);
}
public String generateHistogramA(List<Thingy> things)
{
String newLine=System.getProperty("line.separator");
StringBuilder sb=new StringBuilder();
for(Thingy thingy: things)
{
for(int j=0, count=thingy.count; j<count; j++) sb.append('#');
sb.append(newLine);
}
return sb.toString();
}