2017-03-11 23 views
0
public class OblongTester 
{ 
    public static void main(String [] args) 
    { 
    // declare variables 
    Oblong myOblong = new Oblong(); 

    // use methods to set instance variables 
    myOblong.setHeight(10); 
    myOblong.setWidth(25); 

    // use methods to retrieve values of instance variables 
    System.out.println("Width: " + myOblong.getWidth()); 
    System.out.println("Height: " + myOblong.getHeight()); 
    System.out.println("Area: " + myOblong.calculateArea()); 

    } 
} 

我需要的是,而不是固定值的setHeight和setWidth我想用戶能夠輸入的高度和寬度,然後爲區域取值的高度和寬度它們相乘併產生輸出區域例如你如何改變這個,所以它接受來自用戶的輸入

輸入高度:10 輸入寬度:5 面積:50.0

希望這是明確的我要問什麼。上次我在關節上換了一個沒有特定的包裹。

問候,

馬克

+0

您可以使用掃描儀類爲該http://www.javatpoint.com/Scanner-class –

回答

2

使用Scanner

public class OblongTester 
{ 
    public static void main(String [] args) 
    { 
    // declare variables 
    Oblong myOblong = new Oblong(); 

    // use methods to set instance variables 
    Scanner sc = new Scanner(System.in); //create a scanner 

    System.out.println("Enter the height: "); 
    int height = sc.nextInt(); //get height 

    System.out.println("Enter the width: "); 
    int width = sc.nextInt(); //get width 

    myOblong.setHeight(height); 
    myOblong.setWidth(width); 

    System.out.println(); 

    // use methods to retrieve values of instance variables 
    System.out.println("Width: " + myOblong.getWidth()); 
    System.out.println("Height: " + myOblong.getHeight()); 
    System.out.println("Area: " + myOblong.calculateArea()); 

    } 
} 
+0

這也可能是很好的提及'Scanner.nextInt()'在讀取int時不會讀取換行符,因此如果在int讀取後有任何nextLine()語句,它們將只從nextInt()獲取換行符,其他輸入。爲了解決這個問題,你可以在readInt()之後插入一個未使用的readLine(),或者使用readLine()並解析爲一個int。 –

相關問題