gpt4 book ai didi

java - 我必须为一个程序编写两个方法,当用户提示宽度和高度时计算矩形的面积和周长?

转载 作者:行者123 更新时间:2023-11-30 03:09:47 26 4
gpt4 key购买 nike

import java.util.Scanner;

public class InteractiveRectangle
{
public static void main(String[] args)
{

int height = readPositiveInteger("Enter the height");

int width = readPositiveInteger("Enter the width");

printRectangleDetails(height, width);
}

/**
* Read in an integer and return its value
* @param the prompt to be shown to the user
*/
public static int readInteger(String prompt)
{

Scanner scan = new Scanner(System.in);

System.out.println(prompt);

while (!scan.hasNextInt()) // while non-integers are present...
{
scan.next(); //...read and discard input, then prompt again

System.out.println ("Bad input. Enter an integer");
}

int firstInteger = scan.nextInt();

return firstInteger;

}

/**
* Read in an integer greater than 0 and return its value
* @ param the prompt to be shown to the user
*/
public static int readPositiveInteger(String prompt)
{
int input = 0;

Scanner scan = new Scanner(System.in);

boolean first = false;

while (!scan.hasNextInt())
{
int quantity = scan.nextInt();

if (quantity > 0)
{
first = true;

quantity = scan.nextInt();

}
else if (quantity <= 0)
{
System.out.println("Bad input. Enter a positive integer.");
}

}
return input;
}

/**
* Returns the area of a rectangle
* @param height the height of the rectangle
* @param width the width of the rectangle
*/

public static int area (int height, int width)
{
return height * width;
}

/**
* Returns the perimeter of a retangle
* @param height the height of the rectangle
* @param width the width of the rectangle
*/
public static int perimeter (int height, int width)
{
return (height * 2) + (width * 2);
}

/**
* Prints the area, the perimeter, the length and the width
* @param heigth the height of the rectangle
* @param width the width of the rectangle
*/
public static void printRectangleDetails (int height, int width)
{
System.out.println("The height is " + height);

System.out.println("The width is " + width);

System.out.println("The area is " + area(height, width));

System.out.println("The perimeter is " + perimeter(height, width));
}
}

到目前为止,这是我的程序,但我在 readPositiveInteger 方法方面遇到了一些问题,我还必须编写一个方法,询问用户是否想要另一个矩形,如果需要,则输入“y”,如果需要,则输入“n”不使用 while 循环。谢谢您

最佳答案

使用do-while让您的代码至少执行一次然后询问用户是否想再次计算结果

char ch = 'y';
do{
int height = readPositiveInteger("Enter the height");
int width = readPositiveInteger("Enter the width");
printRectangleDetails(height, width);
System.out.print("Do you want to calculate other rectangle (y/n) ? : ");
Scanner reader = new Scanner(System.in);
char = reader.next().charAt(0);
}while(ch=='y' || ch=='Y');

关于java - 我必须为一个程序编写两个方法,当用户提示宽度和高度时计算矩形的面积和周长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33854017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com