bad operand types for binary operator >=, -, *

后端 未结 4 1030
遥遥无期
遥遥无期 2021-01-29 07:36

I\'m having trouble figuring out how to fix these errors I keep getting for my code

import java.util.Scanner;

public class Unit02Prog1 {

    public static void         


        
4条回答
  •  广开言路
    2021-01-29 07:49

    What you are doing wrong

    if (numWords >= 50) {
    

    numWords is a string, and >= only works on numbers.

    How to fix

    You have 2 options for fixing this:

    • Read the number in as a String and convert it to a number

      temp = input.nextLine();
      numWords = Integer.parseInt(temp);
      

      This way means you can check manually, and do not need to catch an exception if the number is wrong.

    • Read the number in as a number straight away

      numWords = input.nextInt();
      

      This way is less code, but you will need to catch a NumberFormatException if the input is not an integer.

    Other notes

    • You use input.next() a lot, depending on your inputs you may want to use nextLine instead
    • You may want to use System.out.printf to clean up your printing code

提交回复
热议问题