因此,对于我的家庭作业,我必须编写一个程序,允许用户输入他们愿意为整体房屋支付的最高金额。这是要抓住的地方;我必须使用if-else语句和JOptionPane对话框。
所以我想到了以下代码:
import javax.swing.JOptionPane;
public class housingDecision {
public static void main(String[] args) {
//listed things that need to be identified
int houseMoney;
String input;
input = JOptionPane. showInputDialog("How much money do you have?");
//making the input be listed by the user
houseMoney = Integer. parseInt(input);
//set up so that if its more than the parameters, itll move on to the next if else statement
if (houseMoney >= 250000 && houseMoney <= 100000 );
{
input = "You can afford a Townhouse!";
}
if(houseMoney >= 250001 && houseMoney <= 400000);
{
input = "You can afford a Single Family House!";
}
if (houseMoney >= 400001 && houseMoney <= 800000);
{
input = "You can afford a Luxury House!";
}
if (houseMoney >= 800001);
{
input = "Wow! You can Afford a mansion!";
}
}
}
但是,输入整数时它不会运行。我需要更改什么,这样就不再成为问题了?
答案 0 :(得分:1)
似乎运行良好。话虽如此,它无法完成您要完成的任务。
.
之后有空格。value
设置为结果消息,然后对其执行任何操作。最重要的是,您需要在if
语句之后删除那些分号,因为这不会导致在条件上调用它们的块。
工作代码(没有Dialog输入)如下所示:
public class Main {
public static void main(String[] args) {
int houseMoney;
String input;
input = System.console().readLine("How much money do you have? > ");
houseMoney = Integer.parseInt(input);
if (houseMoney <= 250000 && houseMoney >= 100000) {
input = "You can afford a Townhouse!";
} else if(houseMoney >= 250001 && houseMoney <= 400000) {
input = "You can afford a Single Family House!";
} else if (houseMoney >= 400001 && houseMoney <= 800000) {
input = "You can afford a Luxury House!";
} else if (houseMoney >= 800001) {
input = "Wow! You can Afford a mansion!";
} else {
input = "You can't afford a house!";
}
System.out.println(input);
}
}
答案 1 :(得分:0)
此代码中有4个问题:
如果子句为true,则在if之后紧接着要运行的语句。只是一个单独的分号(;
)本身就是一条语句(no-nothing语句)。此外,在Java中,大括号也是合法的,因此,在您的代码中, ALL 代码将运行。
您要做的就是设置input
变量,仅此而已。设置输入变量并不能神奇地打印出东西。尝试System.out.println
,例如。
您的第一笔资料是否损坏;您有一个0太多或太少(条件询问输入是否既大于250k又小于100k;那当然总是错误的。)
因为没有'else'子句,如果没有一个条件成立,则解决其他问题后将一事无成。
修复所有这些问题,您的代码将可用。