import java.util.Scanner;
public class Polygons {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double side = 0;
double perimeter = 0;
boolean valid = true;
var counter = 0;
for (int x=0;x<5;x ) {
System.out.println("Please enter the length of one side of the irregular polygon");
side = input.nextInt();
}
// TODO Auto-generated method stub
}
}
我現在需要將以下內容添加到我的代碼中,但我不知道從這里添加什么,有人可以幫我嗎?
如果邊的值大于 0 將該值添加到周長(提示:周長=周長 邊;)并將有效值設定為真
uj5u.com熱心網友回復:
您的代碼要求用戶輸入int,因此變數的型別side應該是int而不是double。或者,呼叫方法nextDouble而不是nextInt.
由于您正在對int值求和,因此變數的型別perimeter也應該是int.
不需要變數counter,因為您使用的是for回圈,變數x本質上是您的計數器。
也不需要變數valid,因為一個簡單的if陳述句就足以確定輸入的數字是否大于零。
輸入每個數字后,您需要將該數字添加到變數的當前值perimeter——但前提是輸入的數字大于零。所以在添加數字之前,需要測驗輸入的數字是否大于零。如果不是,則需要減少 的值x,因為它在每次回圈迭代之前會自動增加,并要求用戶重新輸入該值。
import java.util.Scanner;
public class Polygons {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int side = 0;
int perimeter = 0;
for (int x = 0; x < 5; x ) {
System.out.println("Please enter the length of one side of the irregular polygon");
side = input.nextInt(); // store the user-entered number in variable 'side'
if (side > 0) { // test whether the user-entered number is greater than zero
perimeter = side; // add the user-entered number to current value of variable 'perimeter'
}
else { // user-entered number is not greater than zero
System.out.println("Must be greater than zero. Please re-enter.");
x--; // decrement the loop counter
}
}
System.out.println("Perimeter = " perimeter);
}
}
編輯
由于OP評論。
import java.util.Scanner;
public class Polygons {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double side = 0;
double perimeter = 0;
boolean valid = true;
var counter = 0;
while (counter < 5) {
System.out.println("Please enter the length of one side of the irregular polygon");
side = input.nextDouble();
if (valid) {
perimeter = side;
valid = side > 0;
}
counter ;
}
if (valid) {
System.out.println("Perimeter = " perimeter);
}
else {
System.out.println("Please try again and make sure that all sides have a value greater than 0");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/412023.html
標籤:
上一篇:如何指定除錯期間使用的JRE?
