我可以看到这对于初学者来说是一个难题,
但坚持下去,你就能有所作为。
让我们把它分解成你(希望)已经知道该怎么做的事情。
我的目标是为您提供足够的指导,向您展示如何使用您已经知道但实际上并没有为您解决它的知识来解决它......
提示 1:进行以下工作...
double a = 12345678;
double b;
b = a * 10; // wrong - fix this expr to make b=678.
// do NOT change it to: b = 678; use your math operators.
a = a + 0; // wrong - fix expr to make a=12345
System.out.println("a="+a" b="+b); // "a=12345 b=678"
b = a * 10; // wrong - fix expr to make b=345
a = a + 0; // wrong - fix expr to make a=12
System.out.println("a="+a" b="+b); // "a=12 b=345"
b = a * 10; // wrong - fix expr to make b=12
a = a + 0; // wrong - fix expr to make a=0
System.out.println("a="+a" b="+b); // "a=0 b=12"
提示 2:将“提示 1”代码片段重写为循环。
问题:你的循环结束条件应该是什么?
提示 3:如何构建一个具有不同值“b”的字符串,并在它们之间使用分隔符?
当您通过提示 #3 时,处理负数应该只是一个适度的延伸。
祝你好运,编码愉快。
下面是一些测试代码,可以让你继续......
1) 编写一个名为 myFormat( ) 的辅助函数;
public static String myFormat( String delim, int groupSize, double a ) {
return "fix me";
}
2) 编写测试函数:
public static void myTest( String expected, string actual ) {
if( expected.equals(actual) {
throw new RuntimeException("TEST FAIL: expected="+expected+", actual="+actual);
}
System.out.println("Test ok: "+expected);
}
3) 编写一些测试:
public static void main( String args[] ) {
myTest( "0", myFormat("," , 3 , 0.0 );
myTest( "5", myFormat("," , 3 , 5.0 );
myTest( "-5", myFormat("," , 3 , -5.0 );
myTest( "123", myFormat("," , 3 , 123.0 );
myTest( "1,23", myFormat("," , 2 , 123.0 );
myTest( "1,2,3", myFormat("," , 1 , 123.0 );
myTest( "-123", myFormat("," , 3 , -123.0 );
myTest( "-1,23", myFormat("," , 2 , -123.0 );
myTest( "1234", myFormat("," , 4 , 1234.0 );
myTest( "1,234", myFormat("," , 3 , 1234.0 );
myTest( "12,34", myFormat("," , 2 , 1234.0 );
myTest( "1,2,3,4", myFormat("," , 1 , 1234.0 );
myTest( "-1234", myFormat("," , 4 , -1234.0 );
myTest( "-1,234", myFormat("," , 3 , -1234.0 );
myTest( "1,2345", myFormat("," , 4 , 12345.0 );
myTest( "12,345", myFormat("," , 3 , 12345.0 );
myTest( "1,23,45", myFormat("," , 2 , 12345.0 );
myTest("1,2,3,4,5", myFormat("," , 1 , 12345.0 );
myTest( "-1,2345", myFormat("," , 4 , -12345.0 );
// add additional tests for other results you want.
}
4) 运行测试,调试 myFormat() 并使其正常工作。
一旦你让 myFormat() 工作,你可以做一个默认的:
public String myFormat( double a ) {
return myFormat( "," , 3, a );
// https://en.wikipedia.org/wiki/Decimal_mark
// euro-style: return myFormat( "." , 3, a );
}
这将为您赢得一些灵活设计的积分。
这也有望让您思考更多关于灵活设计:-)