2012-04-07 15 views
0

我有下面的類提供用戶輸入:Java類

class Area 
{ 
    //Get User Input for classes 
    int length; 
    int width; 

    public Area(int x,int y) 
    { 
     length = x; 
     width = y; 
    } 

    public int getArea() { 
     return width * length; 
    } 

    public static void main(String[] args) 
    { 
     Area folk = new Area(4,5); 
     System.out.println("Area of 4 * 5 is: " + folk.getArea()); 
    } 
} 

我有我用它來獲取用戶輸入的另一個類:

import java.util.Scanner; 

class Incoming 
{ 
    public static void main(String[] args) 
    { 
     Scanner reader = new Scanner(System.in); 
     System.out.println("Enter the first number"); 
     //get user input for a 
     int a = reader.nextInt(); 
     System.out.println("Input Value Is: " + a); 
    } 
} 

在第一類中,我想用戶提供輸入而不是預定義的值(即Area folk = new Area(4,5)

這怎麼能做到?

+2

um,..也許用用戶輸入的int也可以是構造函數的參數。換句話說,創建兩個int變量a和b,使用Scanner獲取用戶輸入,然後使用a和b調用Area構造函數。 – 2012-04-07 13:52:25

+0

你可以在這裏閱讀關於它的詳細教程:http://www.cs.utexas.edu/users/ndale/Scanner.html – dexametason 2012-04-07 13:55:16

+0

感謝氣墊船充滿鰻魚,工作。 – Gandalf 2012-04-07 14:01:32

回答

1

看起來您正在尋找一種方法來使用程序中其他地方提供的輸入Incoming

爲此,請移動代碼以從main方法中獲取輸入。在Incoming中聲明一個新方法,它返回一個int並放在那裏。

然後,在Areamain方法,創建Incoming一個實例,並調用新的方法來獲取一個int。這樣做兩次,然後將結果值傳遞給構造函數Area

0

我不確定你爲什麼在你的課上都有一個主。也許我誤解了一些東西,但是這會按照你想要的方式來解決它(我認爲)。

class Area 
{ 
    //Get User Input for classes 
    int length; 
    int width; 

    public Area(int x,int y) 
    { 
     length = x; 
     width = y; 
    } 

    public int getArea() { 
     return width * length; 
    } 

    public static void main(String[] args) 
    { 
     int x, y; 
     Incoming inc = new Incoming(); 
     x = inc.getInt(); 
     y = inc.getInt(); 
     Area folk = new Area(x,y); 
     System.out.println("Area of " + x + " * " + y + " is: " 
          + folk.getArea()); 
    } 
} 

而其他類:

import java.util.Scanner; 
class Incoming 
{ 
    public static int getInt(String[] args) 
    { 
     Scanner reader = new Scanner(System.in); 
     System.out.println("Enter the first number"); 
     //get user input for a 
     int a = reader.nextInt(); 
     return a; 
    } 
} 
+0

這兩個班都顯示了我正在嘗試做什麼。我有一個在這裏的鏈接在一起http://pastebin.com/J2Hf5xF0 – Gandalf 2012-04-07 14:04:57

0

怎麼樣:

掃描儀讀取器=新掃描儀(System.in);

Area folk = new Area(reader.nextInt(),reader.nextInt());

system.out.println(folk.getArea());