h*******9 发帖数: 68 | 1 刚刚开始学java,这周就要交网上作业,可是有个地方怎么试都不对,请各位好心人帮
帮忙!
我写了一个getFNSN(FN,SN);, 来模块化我的代码,可是应用起来下一行出来的总是原
始值,而不是用户的输入值,试来试去不知道怎样改才好。急死人了!
Result of adding 0.00 and 0.00 is 0.00.
部分相关代码如下:
{
public static void main(String[] args) {
float FN=0;
float SN=0;
{out.printf( "Please enter two numbers to add, separated by a space: ");
getFNSN(FN,SN);
out.printf("Result of adding %5.2f and %5.2f is %5.2f.n",FN, SN, FN+ SN);
}
static void getFNSN (float fn, float sn){
do {Scanner In = new Scanner(System.in);
try {
fn = In.nextFloat();
sn = In.nextFloat();
break;
}
catch (final InputMismatchException e) {
out.println("You have entered an invalid choice. Try again."
);
In.nextLine();
continue;
}
} while (true);}
}
结果:
What would you like to do? 1
Please enter two numbers to add, separated by a space: 2 3
Result of adding 0.00 and 0.00 is 0.00.
Press enter key to continue … | W***o 发帖数: 6519 | 2 this: static void getFNSN()
Since the return type is void, it does not return the user input to the main
() method. You need to pass the user input from getFNSN() to main() method.
For example, use an array of size two and of type float to to pass the
values back to main().
Alternatively, you can also put this line "out.printf("Result of adding %5.
2f and %5.2f is %5.2f.n",
FN, SN, FN+ SN);" inside your getFNSN() method.
hope this helps
【在 h*******9 的大作中提到】 : 刚刚开始学java,这周就要交网上作业,可是有个地方怎么试都不对,请各位好心人帮 : 帮忙! : 我写了一个getFNSN(FN,SN);, 来模块化我的代码,可是应用起来下一行出来的总是原 : 始值,而不是用户的输入值,试来试去不知道怎样改才好。急死人了! : Result of adding 0.00 and 0.00 is 0.00. : 部分相关代码如下: : { : public static void main(String[] args) { : : float FN=0;
| l**********r 发帖数: 79 | 3 这个跟return type 无关, 你这是典型的c思维写java代码。 但是java 有一个神器,
就是包装。
package microbenchmark;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SC {
Objects obje;
public SC(){
obje=new Objects();
}
private class Objects{
float fn=0;
float sn=0;
public Objects(){
fn=0;
sn=0;
}
public void setFN(float value){
fn=value;
}
public void setSN(float value){
sn=value;
}
public float getFN(){
return fn;
}
public float getSN(){
return fn;
}
}
public static void main(String[] args) {
SC instance =new SC();
Objects value=instance.obje;
System.out
.print("Please enter two numbers to add, separated by a
space: ");
getFNSN(value);
System.out.println("Result of adding " + value.getFN() + " and " +
value.getSN() + " is "
+ String.valueOf(value.getFN() + value.getSN()) + ".");
}
static void getFNSN(Objects value) {
do {
Scanner In = new Scanner(System.in);
try {
value.setFN(In.nextFloat());
value.setSN(In.nextFloat());
break;
} catch (final InputMismatchException e) {
System.out
.println("You have entered an invalid choice. Try
again.");
In.nextLine();
continue;
}
} while (true);
}
} | l**********r 发帖数: 79 | 4 java的基本类型都是值传递, 但是构造的类型, 就不是了。 所以任何问题,只要封
装好解决了。 这是java的一个缺点。 | l**********r 发帖数: 79 | 5 这版面人真懒。 这程序里有个bug。 都没人看出来。 |
|