I am trying to write a piece of code that calculates the factorial of a given number. However, when I run the code an error appears. It says “error: bad operand types for binary operator ‘<=’ and ‘*’. I am not sure what I am doing wrong, nor do I understand what the error signifies. What do you suggest?
import java.util.Scanner; class Main { public static void main(String args[]) { System.out.println("Enter Number"); Scanner fact = new Scanner(System.in); String num = fact.nextLine(); for (int i = 1; i <= num; i++){ fact = fact*i; } System.out.println("Factorial is = "+fact); } }
Answer
This error is very common. You’re comparing i <= num, in other words, (an int) <= (a string). To fix this, simply get the length of the string instead.
for (int i = 1; i <= num.length(); i++){ <insert code here> }
However, if you’re expecting the factorial number as the user input, you would need to keep it as an int.
Scanner inputScanner = new Scanner(System.in); int num = Integer.parseInt(inputScanner.nextLine()); int fact = 1; for (int i = 1; i <= num; i++){ fact = fact*i; }