gpt4 book ai didi

java - 方法——继续

转载 作者:行者123 更新时间:2023-11-29 10:04:22 30 4
gpt4 key购买 nike

import java.util.Scanner;
public class InteractiveRectangle
{
public static void main(String[] args)
{
do
{
int length = readInteger ("For Length ");
System.out.println();
int width = readInteger ("For Width ");
printRectangleDetails(length,width);// existing code goes here
}
while (keepGoing());

System.out.println("Goodbye, friend");
}


/**
* returns the details of the rectangle
* @param height the height of the rectangle
* @param width the width of the rectangle
*/
public static void printRectangleDetails (int length, int width)
{
System.out.println ("This is the length of the rectangle " + length);

System.out.println ("This is the width of the rectangle " + width);

System.out.println (("This is the perimeter of the rectangle " + (length + width)));

System.out.println (("This is the area of the rectangle " + (length * width)));
}

/**
* Read in an integer and return its value
* @param the prompt to be shown to the user
*/
public static int readInteger(String prompt)
{
System.out.println (prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");

while (!scan.hasNextInt()) // while non-integers are present
{
scan.next();
System.out.println ("Bad input. Enter an integer.");
}
int input = scan.nextInt();
return input;
}

/**
* Read a positive integer and return its value
* @param the prompt to be shown to the user
*/
public static int readPositiveInteger(String prompt)
{
System.out.println (prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
boolean positive = false;

while (scan.hasNextInt() && positive == false)
{
int input = scan.nextInt();
if (input > 0)
{
positive = true;
{
return input;
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();

}

}
return 0;
}

/**
* Ask the user whether or not to spawn another rectangle
* and returns the result as a boolean
*/
public static boolean keepGoing()
{
Scanner scan = new Scanner(System.in);
boolean inputRead = false;
boolean result = false;
System.out.println ("Do you want to process another rectangle?");
scan.next();
String input = scan.next();

if (input == "y")
{
inputRead = true;
result = true;

}
else if (input == "n")
{
inputRead = true;
result = false;

}
else
{
System.out.println("Bad input please try again!");
scan.nextLine();
}
return result;

}

我希望程序询问用户是否要生成另一个矩形,并继续下去,直到用户用“n”回答这个问题。 Atm 当我运行程序时,矩形只产生一次,所以我认为我的 keepGoing 方法有问题。任何帮助,将不胜感激,谢谢!

最佳答案

if (input == "y")

总是用equals()比较字符串

你需要

if ("y".equals(input))

if ("y".equalsIgnoreCase(input))//也将允许 Y

相应地更改其他检查。

关于java - 方法——继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13523948/

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