2014-02-05 50 views
0

所以我必須編寫一個程序,如果你有一個數字,程序可以判斷它是奇數/偶數還是完美的(意思是這些因數的總和等於數字本身)。到目前爲止,我有以下幾點:Number Runner Program

import java.util.Scanner; 
public class NumberRunner2 
{ 
public static void main(String[] args) { 
int[] numbers = new int[]{3, 21, 532, 1111, 199, 291, 19}; 
{ 
    int x; 
    System.out.println("Enter an integer to check if it is odd or even "); 
    Scanner in = new Scanner(System.in); 
     x = in.nextInt(); 

    if (x % 2 == 0) 
     System.out.println("Even."); 
     else 
    System.out.println("Odd"); 
    } 
    } 
} 

而且

public class Number2 
{ 
    private Integer number; 
    public Number2() 
{ 
} 
    public Number2(int num) 
{ 

} 
    public void setNumber(int num) 
{ 

} 
    public int getNumber() 
{ 
    return 0; 
} 
public boolean isOdd() 
{  
    return false; 
} 
    public boolean isPerfect() 
{ 

    int total=0; 
    return (number==total); 
} 
public String toString() 
{ 

    return ""; 
}  
} 

的事情是,這兩個節目都待在一起,但我不知道怎麼辦。此外,我不知道如何將完美的數字函數放入我的代碼中。

+0

開始[這裏](http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html),你的Number類甚至沒有被使用,也沒有的方法做任何有意義的事情。 – turbo

回答

1

Object Oriented Programming(或OOP)中,您代表真實的物體,信息或概念 - 作爲對象。這很有幫助,因爲許多對象可以具有相同的屬性。

在你的練習中,你正在構建一個代表數字的類Num,它應該評估該數字的屬性。

要在您的代碼實際上構造這樣的號碼,你可以使用調用類的構造函數:

// this can be a call in your main function, or anywhere in fact! 
Number two = new Number(2); // this represents the number "2" 

以後,您使用的方法從類對象,給予了該對象的屬性:

System.out.println("Is two odd? " + two.isOdd()); 

爲了做到這些事情,你寫了兩個類。一個被稱爲主類,它驅動程序(構造對象,向用戶執行打印以及更多...),另一個是更被動的類,即數字類,它表示一個數字(並且具有對數)。

將所有內容放在一起:

主類會是這個樣子(僅長):

import java.util.Scanner; 

public class Main { 

    public static void main(String[] args) { 
     Num two = new Num(2); 
     System.out.println("Is two odd? " + two.isOdd()); 

     // and scanner... 
     Scanner in = new Scanner(System.in); 
     Num x = new Num(in.nextInt()); 

     // add more methods and call them on x 
    } 
} 

而類會是這個樣子(再次,更長):

public class Num { 

    private int number; 
    public Num(int num) { 
     // save number in object's state. 
     this.number = num; 
    } 

    public boolean isOdd() { 
     // print if the number is odd or not 
     return this.number % 2 != 0; 
    } 

} 

另一個偉大的編程技巧是搜索:

當您遇到問題時,Google會提供所有答案。考慮一下可以唯一標識你的問題並在你的搜索中使用它們的術語(例如:「我如何在java中使用while循環?」可能與搜索「while循環java」相同)

你也可以開始使用Oracle的教程Learning the Java Language