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

Type mismatch: cannot convert from double to int

需要写一个程序来计算所有数字的和,然后在总和以5结尾时给出结果或者8.Please帮助更正此代码!

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");
        }
        }
        }

除了此代码不会产生您提到的错误之外,该代码还有其他问题。我试着解决它们。

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");
    }
}

而不是做

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

where sum%8 will be true for the value 16 so you can try this

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

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

同时查看 Yash 的答案,因为您的代码也有其他问题。

+永远不要用大写字母写变量名("Reminder")!!!!

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

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in= new Scanner(System.in);
        int customerID = in.nextInt();
        int sum = 0;
        while(customerID > 0) {
            int Reminder = customerID % 10;
            sum = sum + Reminder;
            customerID = customerID / 10;   
        }
        if(sum % 5 == 0 || sum % 8 == 0) {
            System.out.println("Lucky Customer");
        } else {
            System.out.println("Unlucky Customer");
        }
        if(sum <0) {
            System.out.println("Invalid Input");
        }
    }
}