簡體   English   中英

布爾返回問題/從放入數組的方法中獲取因素

[英]boolean return issue/getting factors from method put into an array

在一個小時前發布關於一個較早版本的問題並在4分鍾內得到答復之后,這是一個瘋狂的疾病,請再試一次我的運氣。 程序有5種方法,目前正在全部使用,因此它們將不會全部放在這(由於先前的響應而出現),現在的問題是使我的最后一種方法實際執行除使打印語句正常工作以外的其他功能。 該方法是不完整的,它不僅需要找到所述數字的因數,而且還必須將它們存儲在數組中,將它們加起來,然后確定數字是否理想。 最后一個未顯示的方法將打印出每個數字的實際數組(如果有一個)。 “ testperfect”是我遇到問題的方法,在日食中我收到一條錯誤消息,說此方法必須返回boolean類型的結果。 任何形式的幫助將不勝感激

import java.util.Scanner;

public class tgore_perfect 
{
 private static int count;
 private static int perfect;
 public static void main ( String args [])
 {
    count = getNum ();
    //System.out.print(count);
    boolean check = validateNum();
    //System.out.print(check);
    while (validateNum() == false)
    {
    System.out.print ("Non-positive numbers are not allowed.\n");
    count = getNum();
    }
    if (validateNum() == true)
    {
    for ( int i = 0; i < count; i++ )
    {
        perfect = getPerfect();
        testPerfect();

    }
}
}



public static int getNum () //gets amount of numbers to process
 {
     Scanner input = new Scanner ( System.in );
     int counter;

         System.out.println ("How many numbers would you like to test? ");
         counter = input.nextInt();
     return counter;
 }

 private static boolean validateNum() //checks user input
 { 
 if (count <= 0)
 {
     return false;
 }
 else
 {
     return true;
 }
 }

 public static int getPerfect() //gets number to process
 {
 Scanner input = new Scanner ( System.in);
 perfect = -1;
 System.out.print ("Please enter a possible perfect number: ");
 return perfect = input.nextInt();
 }

 public static boolean testPerfect() //tests the number to see if is perfect
{
     int sum = 0;
     int x = 0;

     for( int i = 1; i < perfect; i++ )
 {
     if((perfect % i ) == 0 )
     {
         x = i;
         sum += x;

     }
     if( x == perfect)
     {
         return true;
     }
     else 
     {
         return false;
     }
}
}
}

所有代碼路徑都必須返回您的return-type

想象一下,如果因為iperfect值而導致for循環根本沒有執行 ,在這種情況下,您的函數將不會返回任何內容。

是不允許的。

public static boolean testPerfect() //tests the number to see if is perfect
{
    //...code...
    for( int i = 1; i < perfect; i++ )
    {
        //..code..
    }
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM