我目前正在大學裏參加我的第一個編程課,到目前爲止已經非常瞭解如何編寫基本的東西。這個最新的任務讓我感到困惑和困惑。簡單的Java程序,正方形和立方體的用戶輸入編號
我的任務是:
- 接受來自用戶(整數)數字輸入
- 打印出輸入的數字的平方和立方。
- 確保數字大於0.
- 重複上述三次。
- 如果輸入的數字是< = 0,則結束程序,告訴用戶原因。
我的問題是,我不確定變量是如何對於這一點,究竟如何添加循環重複上述過程3次進行設置。
這是我所有迄今爲止,不知道從哪裏去,任何幫助將不勝感激。謝謝
import java.io.*;
public class Assignment3 //class name here, same as file name
{
public Assignment3() throws IOException{ //constructor, place class name here
// use BufferedReader class to input from the keyboard
// declare a variable of type BufferedReader
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
//declare variable for input
String inputString;
// houseKeeping()
String yourNumber;
int number;
int totalSquare = 0;
int totalCube = 0;
int count;
int badNumber=0;
String squareCube = " Your number squared is" +square +"your number cubed is"+cube;
System.out.print("Enter a number: ");
inputString = input.readLine();
yourNumber = inputString;
}//end constructor
}
public static void main(String [] args) throws IOException
{
new Assignment3(); //class constructor name
}
你沒有使用循環。只需要調用'new Assignment3()'3次 –
如果你想將字符串'yourNumber'轉換爲一個整數,所以你可以將其平方和立方體,使用'Integer.parseInt' http://docs.oracle.com/ javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String) – djhworld
@PaulNikonowicz如果用戶輸入錯誤的數字,你想怎麼做? – Tom