我应该写一个程序来计算一所房子的总建筑面积。该程序提示用户输入至少一个房间的长度和宽度,如果用户想要输入更多的房间尺寸,则需要与用户进行验证。
它不起作用。谁来帮帮我?
import java.util.*;
public class FloorSpace
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double length = 0.0, width = 0.0, floorSpace = 0.0;
char ans;
do
{
System.out.print("Enter length: ");
length = input.nextDouble();
System.out.print("Enter width: ");
width = input.nextDouble();
floorSpace = length * width;
floorSpace += floorSpace;
System.out.print("Do you want to enter more room dimensions? (y/n): ");
ans = input.nextLine().charAt(0);
}
while (ans == 'y');
System.out.println("\nTotal floor space is " + floorSpace);
}}
哦,天哪,我刚发现我的计算公式有问题。谁能帮帮我。
发布于 2012-12-07 20:54:51
您每次都会将floorSpace设置为length * width,然后自行递增该值(实际上就是将其乘以2)。
替换
floorSpace = length * width;
floorSpace += floorSpace;使用just
floorSpace += length * width发布于 2012-12-07 20:52:07
而不是:
ans= input.nextLine().charAt(0);使用:
ans = input.next().charAt(0);要修复您的公式,请使用:
floorSpace += length * width;并删除:
floorSpace = length * width;因此,最终的解决方案如下所示:
import java.util.*;
public class FloorSpace
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double length = 0.0, width = 0.0, floorSpace = 0.0;
char ans;
do
{
System.out.print("Enter length: ");
length = input.nextDouble();
System.out.print("Enter width: ");
width = input.nextDouble();
floorSpace += length * width;
System.out.print("Do you want to enter more room dimensions? (y/n): ");
ans = input.next().charAt(0);
}
while (ans == 'y');
System.out.println("\nTotal floor space is " + floorSpace);
}
}发布于 2012-12-07 20:59:42
试试这个:
import java.util.*;
public class FloorSpace
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double length = 0.0, width = 0.0, floorSpace = 0.0;
char ans='n'; //not for default
do
{
System.out.print("Enter length: ");
length = input.nextDouble();
System.out.print("Enter width: ");
width = input.nextDouble();
floorSpace += length * width;
System.out.print("Do you want to enter more room dimensions? (y/n): ");
if (input.hasNext()){
ans = input.next().charAt(0);
}
}
while (ans == 'y');
System.out.println("\nTotal floor space is " + floorSpace);
}
}问候
https://stackoverflow.com/questions/13763401
复制相似问题