Java判断输入整数奇偶性时出现“bad operand types for binary operator '%'”错误求助
Hey there! Let's break down why you're getting that error and fix your code step by step.
错误根源
The error bad operand types for binary operator '%' pops up because you're trying to use the modulus operator % on an entire array (int[] num) and an integer (2). This operator only works between two numeric values (like int and int), not between an array object and a number.
Looking at your code, it seems you got a bit off track: you read an integer n, then created an array of length n, and tried to check the array itself for even/odd instead of using the actual number you input (or the elements of the array, if that's what you intended).
修正方案1:判断单个输入数字的奇偶性
If your goal is to just check the parity of the single integer you input, here's the fixed code:
import java.util.Scanner; class EvenOdd{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter an Integer number:"); int num = sc.nextInt(); // 直接用输入的数字做取模运算 if ((num % 2) == 0) { System.out.println("The number " + num + " is even"); } else { System.out.println("The number " + num + " is odd"); } } }
Key fixes here:
- Removed the unnecessary array
int[] num = new int[n];— you don't need an array to check one number - Used the input variable
numdirectly with% 2instead of the array - Got rid of the loop since we only need to check one number once
修正方案2:如果想输入n个数字并逐个判断奇偶性
If you actually wanted to read n different numbers and check each one's parity, here's how to adjust the code:
import java.util.Scanner; class EvenOdd{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("How many numbers do you want to check?"); int count = sc.nextInt(); for(int i=0; i<count; i++) { System.out.println("Enter number " + (i+1) + ":"); int num = sc.nextInt(); if ((num % 2) == 0) { System.out.println("The number " + num + " is even"); } else { System.out.println("The number " + num + " is odd"); } } } }
This version first asks how many numbers you want to check, then loops that many times to read each number and check its parity.
内容的提问来源于stack exchange,提问作者Abhishek Tiwari

