类型不匹配:无法从double转换为int

时间:2017-11-15 07:23:58

标签: java loops addition

需要编写程序来计算所有数字的总和,然后在总和vaue以5或8结束时给出结果。请帮助更正此代码!

import java.util.Scanner;
public class Main {

    public static void main(String[] args) {

        Scanner in= new Scanner(System.in);
        int customerID = in.nextInt();
        while(customerID > 0) 
        {
        int Reminder = customerID % 10;
        int sum = sum+ Reminder;
        customerID = customerID / 10;
        }
        if(sum%5||sum%8)
        {
        System.out.println("Lucky Customer");
        }else
        {
        System.out.println("Unlucky Customer");
        }
        if(sum <0)
        {
        System.out.println("Invalid Input");
        }
        }
        }

4 个答案:

答案 0 :(得分:2)

而不是

if(sum%5||sum%8)
    {
    System.out.println("Lucky Customer");
    }
  

其中总和%8对于值16为真,所以你可以尝试这个

int rem=sum%10;
if(rem==5||rem==8)
{
      System.out.println("Lucky Customer");
}

答案 1 :(得分:1)

除了此代码不会产生您提到的错误之外,代码还存在其他问题。我试图解决这些问题。

public static void main(String[] args) {
    Scanner in= new Scanner(System.in);
    int customerID = in.nextInt();
    int sum = 0;
    // sum needs to be initialized outside the while loop
    // or else you wouldn't be able to use it outside it
    while(customerID > 0) {
        int Reminder = customerID % 10;
        sum = sum+ Reminder;
        customerID = customerID / 10;
    }
    if(sum%5 == 0 || sum%8 == 0) {
        //You cannot use int as a condition in if
        System.out.println("Lucky Customer");
    } else {
        System.out.println("Unlucky Customer");
    }
    if(sum <0) {
        System.out.println("Invalid Input");
    }
}

答案 2 :(得分:1)

只有当您的输入包含点(例如:&#34; 3.0&#34;)时,此代码才会抛出此异常。因此要么传递int值(例如:&#34; 3&#34;),要么使用scanner.nextDouble()然后将其转换为int。

另请参阅Yash的答案,因为您的代码也存在其他问题。

+永远不要用大写字母写出变量名(&#34; Reminder&#34;)!!!!

答案 3 :(得分:1)

请更正您的代码以删除一些编译错误...

import org.apache.hadoop.fs._
import org.apache.hadoop.io._

val md5sum = MD5Hash.digest(FileSystem.get(hadoopConfiguration).open(new Path("locale_file"))).toString