带计数器的乘数,将答案显示为零

时间:2016-08-04 22:48:46

标签: java

我正在尝试制作一个时间表计数器。它应该输出

1 x 5是5 2 x 5是10 3 x 5是15 高达10 x 5是50

输入为5,计数器取自for循环中的i。

它正在计算数字,但我无法得到它来计算结果,我看不出我错过了什么。任何帮助将不胜感激

以下代码

import java.util.Scanner;
public class Program {

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    int input = kb.nextInt();
    Math math1 = new Math(0,0);
    for(int i = 0; i <= 10; i++){
        math1.setNum2(i);
        math1.multiplier();
        System.out.println(input + " times " + i + " is " + math1.getResult());
    }
} //main

} // class Program

public class Math {

private int num;
private int num2;
private int result;
//constructor//
public Math(int num, int num2){
    this.num = num;
    this.num2 = num2;
    this.result = result;
}

//get//
public int getNum(){
    return this.num;
}

public int getNum2(){
    return this.num2;
}

public int getResult(){
    return this.result;
}
//set//
public void setNum(int value){
    this.num = value;
}

public void setNum2(int value){
    this.num2 = value;
}
//other//
public void multiplier(){
    this.num = num;
    result = num * num2;
}
} // class Math

3 个答案:

答案 0 :(得分:1)

无论你在做什么,你似乎都会乘以零。 Math math1 = new Math(0,0);暗示* 0。您需要在代码中使用您的输入。正如亚瑟提到的那样,Math math1 = new Math(input, 0)

答案 1 :(得分:1)

你总是乘以0.因此你的结果。

在主方法中更改您的代码,如下所示:

 // use the input that you took
 //let's take 5
 Math math1 = new Math(0,0);
 math1.setNum(input);

之后请确保在Math课程中使用它。

更新构造函数:

public Math(int num, int num2){
    this.num = num;
    this.num2 = num2;
}

result此处无关。

但问题来了,如何获得result

对于那个改变乘数的方法如下:

public void multiplier(){
    this.result = num * num2;
}

答案 2 :(得分:0)

你将所有东西乘以0队友。您会看到传递给Math类对象的参数。

尝试以下几行:

Scanner in = new Scanner(System.in);
int number = in.nextInt(); // I suppose this is where the user enters the numbers say 5.
Math math = new Math(number, 0);
for(int i=1; i<=10; i++){
   math.setNum2(i);
   math.multiplier();
   System.out.println(input + " times " + i + " is " + : math.getResult());
}

这应该可以帮到你。