java—我是否正确地创建了布尔类?如何修复“表达式的非法开始”和“;”我的代码中预期的错误?

1szpjjfi  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(452)

我试图写一个程序,将从一个用户的整数输入和打印出它的因素。我试图通过创建一个类factorgenerator和方法nextfactor和hasmorefactors来实现这一点。
nextfactor方法必须返回整数,hasmorefactors必须返回布尔值。
对于如何声明返回布尔值的方法,我有点困惑。因为,我想如果我能做到这一点,我的大部分错误可能会消失。请指导我,我需要修复什么,因为我花了很多时间试图修复代码和查找布尔方法,但没有达到任何地方。

import java.util.Scanner;
import java.lang.Boolean;
public class myProgram 
{

    public static void main(String args[]) 
    {
      Scanner in = new Scanner(System.in);
      System.out.print("Enter an integer: ");
      int num = in.nextInt();
      FactorGenerator myFacGenerator = new FactorGenerator(num);
      while (myFacGenerator.hasMoreFactors())
            System.out.println(myFacGenerator.nextFactor);

    }

    public int FactorGenerator(int number)
    {
           int number = num1;
           return num1;

    }

    public int nextFactor(int num1) // method that returns the factors of the input number 
    {

    int i;
    System.out.format("Factors of %d\n " + num1);

        for (i = 1; i <= num1; i++) 
        {

            if (num1 % i == 0) 
            {

               return i;

            }
        }
    }

    public Boolean hasMoreFactors(boolean b) // method that is meant to check if there are any more factors left. This method returns boolean 
     {
       Boolean b1 = num1.equals(i);

       return b1;

     }
}

`一些错误消息包括:

MyProgram.java:27: error: illegal start of expression
     public int nextFactor(int num1) //Returns integer
     ^
MyProgram.java:27: error: ';' expected
     public int nextFactor(int num1) //Returns integer
                          ^
MyProgram.java:27: error: ';' expected
     public int nextFactor(int num1) //Returns integer
                                   ^
MyProgram.java:45: error: illegal start of expression
    public Boolean hasMoreFactors(boolean b); // Returns boolean
    ^
MyProgram.java:45: error: ';' expected
    public Boolean hasMoreFactors(boolean b); // Returns boolean
                                 ^
MyProgram.java:45: error: ';' expected
    public Boolean hasMoreFactors(boolean b); // Returns boolean
                                           ^
6 errors
q43xntqr

q43xntqr1#

请尝试以下操作:

public int nextFactor(int num){
        for(int i = 2; i <= num; i++){
            if(i == num){
                return 1; // returns 1 if its a prime number
            }else (num % i == 0) { 
                return 1; // returns lowest factor
            }
        }
        return 0; // return 0 if all paths fail
    }

    public boolean hasMoreFactors(int num){
        return (nextFactor(num) > 1); //if greater than 1(Not a prime), it has more factors
    }

相关问题