我在执行以下任务时遇到问题:
创建一个程序,提示用户输入两个值:电影评级和他或她的年龄。使用决策结构,根据输入的评级和年龄确定是否允许用户在影院中观看电影。最后,将此决定的结果显示给用户。
这是我的代码,在发布之前我在NetBeans中执行了Alt + Shift + F:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package age;
/**
*
* @author Jason
*/
import java.util.Scanner;
public class Age {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String user_age;
System.out.print("Enter your age: ");
user_age = user_input.next();
String mrating;
System.out.print("Enter the movie rating: ");
mrating = user_input.next();
}
{
if ( user_age < 13 + mrating = G);{
System.out.print( "You are of the right age for this movie");
}
else{
System.out.print(" You are not of correct age for this movie");
}
if ( user_age >= 13 + mrating = PG13);{
System.out.print( "You are of the right age for this movie");
}
else{
System.out.print(" You are not of correct age for this movie");
}
if ( user_age >= 17 + mrating = R);{
System.out.print( "You are of the right age for this movie");
}
else{
System.out.print(" You are not of correct age for this movie");
}
}
}
如果我将Age括号移到if
语句开始之前。我可以让显示器询问用户的年龄和评级,然后程序结束,没有结果。如果我将括号放在那里,程序就会完全错误。我是Java新手,我很困惑,我一直在为这本书和网站工作,但我开始感到困惑。此外,user_age
和mrating
收到错误消息,表示未使用变量。
答案 0 :(得分:1)
首先,您无法将String
(例如user_age
)与整数进行比较。在与另一个整数比较之前,使用Integer.parseInt(String)
转换为int
。
其次,您不应使用==
来比较两个字符串值。使用equals
方法比较两个字符串值。
第三,使用&&
布尔运算符在条件中表示“和”,而不是+
。
第四步,删除紧跟每个if语句条件的分号。否则,如果条件为真,编译器将认为;
是要执行的块。
可能还有其他错误;这是我发现的第4个。
答案 1 :(得分:0)
您需要确保所有代码都在main()
方法中。这是使用Alt-Ctrl-F格式化代码的一个原因。如果您检查代码中的大括号,您会看到main()
在if
语句之前结束。您可以通过删除if
语句之前的结束和打开大括号来解决此问题。
您的代码中可能还有其他问题。如果您需要帮助修复它们,请发布完整的编译器错误,以便我们为您提供帮助。
答案 2 :(得分:-1)
由于这是作业,我不会完全帮助....你必须确保你的程序的逻辑正确性...
我已经解决了所有编译错误......很多语法问题......请通过一些初学Java书。
下面的会让你开始......
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package age;
/**
*
* @author Jason
*/
import java.util.Scanner;
public class Age
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
System.out.print("Enter your age: ");
int user_age = Integer.parseInt(user_input.next());
String mrating;
System.out.print("Enter the movie rating: ");
mrating = user_input.next();
if (user_age < 13 && mrating == "G")
{
System.out.print("You are of the right age for this movie");
}
else
{
System.out.print(" You are not of correct age for this movie");
}
if (user_age >= 13 && mrating == "PG13")
{
System.out.print("You are of the right age for this movie");
}
else
{
System.out.print(" You are not of correct age for this movie");
}
if (user_age >= 17 && mrating == "R")
{
System.out.print("You are of the right age for this movie");
}
else
{
System.out.print(" You are not of correct age for this movie");
}
}
}