你如何对java中的Scanner生成的值进行算术运算?

时间:2016-09-18 03:10:00

标签: java

我真的想知道如何使用扫描仪类添加,乘法或除法,因为每次运行代码时它总是给我0。

public static void main(String[] args) {
int NumPerHamper;
double ItemCost;
int NumHampersMade;
int NumItemsLeftOver;
int ValuePerHamper;
    int NumAvalable;
double ValueAllotedHampers;
double NumAllotedPerHamper;
double ValueAllHampers;
double ValueItemsLeftOver;
int ItemLeftOver;

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter the number of items avalible");
    ValuePerHamper = sc.nextInt();
    System.out.println("Enter the number of avaliable mac and cheese");
    NumAvalable = sc.nextInt();
    NumHampersMade = NumAvalable/ValuePerHamper;

   // System.out.println("Items left over");
    //NumPerHamper = sc.nextInt();
   // System.out.println("");

    System.out.println(NumHampersMade);


}

}

2 个答案:

答案 0 :(得分:1)

将除数转换为更大的数据类型,例如int a 7,b = 9; double ave = a /(double)b。要么v

答案 1 :(得分:0)

这是因为整数除法总是向下舍入,因为int不能有小数。尝试使用double。

double ValuePerHamper, NumAvalable, NumHampersMade;
Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of items avalible");
ValuePerHamper = sc.nextDouble();
System.out.println("Enter the number of avaliable mac and cheese");
NumAvalable = sc.nextDouble();
NumHampersMade = NumAvalable/ValuePerHamper;

System.out.println(NumHampersMade);