class Number { float num1; float num2; void addition(){ double addition=num1+num2; System.out.println("N1+N2结果为:" + addition); } void subtration(){ double subtration=num1-num2; System.out.println("N1-N2结果为:" + subtration); } void multiplication(){ float multiplication=num1*num2; System.out.println("N1*N2结果为:" + multiplication); } void division(){ float division=num1/num2; System.out.println("N1/N2结果为:" + division); } }
1 import java.util.Scanner; 2 3 public class Number_main { 4 5 public static void main(String[] args) { 6 Number num1=new Number(); 7 Number num2=new Number(); 8 Number num3=new Number(); 9 Number num4=new Number(); 10 11 Scanner input=new Scanner(System.in); 12 System.out.println("输入两个值来计算加减乘除:"); 13 float n1 = input.nextInt(); 14 Scanner input2=new Scanner(System.in); 15 System.out.println("输入第二个值:"); 16 float n2 = input.nextInt(); 17 18 num1.addition(); 19 num2.subtration(); 20 num3.division(); 21 num4.multiplication(); 22 23 } 24 25 }
输入两个值来计算加减乘除:
5
输入第二个值:
4
N1+N2结果为:0.00.0
N1-N2结果为:0.0
N1/N2结果为:NaN
N1*N2结果为:0.0
为什么会出现这样的情况?怎么样才能根据题目做出来,是我的想法有问题吗?
用Number类申明一个对象number,将你输入的值赋给对象的两个属性n1,n2,再调用对象的方法即可
谢谢大佬了。
你就没给你的Number对象的两个数字赋值过你说怎么可能得出正确答案?
ps:标题长的确显眼。。。。
咋弄。。。。我就在想怎么把输入的值赋给num1和num2
@窗外雨,夜微寒。: 简单点你把那两个字段public出来,要么去掉那两个字段,降到方法上
class Number
{
void multiplication(float num1,float num2){
float multiplication=num1*num2;
System.out.println("N1*N2结果为:" + multiplication);
}
//..依次类推
}
外边直接当入参传入就可以了,new那么多Number实例没用。
@Daniel Cai: 解决了谢谢大佬了。
根据面向对象的设计原则,你可以这样写:
public class Number {
float value;
Number addition(Number num){
double addition=this.value+num.value;
System.out.println("N1+N2结果为:" + addition);
return this;
}
Number subtration(Number num){
double subtration=this.value-num.value;
System.out.println("N1-N2结果为:" + subtration);
return this;
}
Number multiplication(Number num){
float multiplication=this.value*num.value;
System.out.println("N1*N2结果为:" + multiplication);
return this;
}
Number division(Number num){
float division=this.value/num.value;
System.out.println("N1/N2结果为:" + division);
return this;
}
Number(float f){
this.value = f ;
}
public static void main(String[] args) {
Number number1 = new Number(4);
Number number2 = new Number(5);
number1.addition(number2)
.subtration(number2)
.division(number2)
.multiplication(number2);
}
}
谢谢大佬。