2012-11-15 65 views
1

在一小時前發佈關於先前問題並在4分鐘內得到響應,這是瘋狂的生病再次嘗試我的運氣。程序有5種方法,目前正在製作所有這些方法,以便它們不會全部放在這裏(因爲事先的響應而引入此問題)現在正在獲得我的最後一種方法,它們實際上除了使打印語句正常工作外。該方法不完整,它不僅需要查找所述數字的因素,而且還必須將它們存儲在數組中,將它們加起來並確定數字是否完美。最後一個未顯示的方法將打印出每個數字的實際數組(如果有)。 「testperfect」是我遇到的問題,在eclipse中,我得到一個錯誤,說這個方法必須返回布爾類型的結果。 。 。任何形式的幫助,將不勝感激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; 
    } 
} 
} 
} 
+0

通過testPerfect()方法的所有路徑都必須返回結果。您應該在for循環之後返回一個合適的值? – pauli

回答

1

所有的代碼路徑必須返回你的回報型

試想一下,如果你的for循環在所有因爲你的i值的未執行和perfect,在這種情況下,你的函數不會返回任何東西。

是不允許的。

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

我的愚蠢的錯誤,我想我不確定如何問我想問的問題,而不是隻是要求有人做我的工作,這是不可接受的,但與布爾人的工作方式直言不諱,我不確定如何讓它不僅返回最後的真/假的數字是完美的,並將所有的因素輸出到一個數組......你的帖子確實回答了我的思路不清的問題,所以我應該檢查它的答案? – user1826373

+0

@ user1826373如果確實解決了所述問題,您可以將其標記爲如此。 :) –