2个月大的程序员在这里。
尝试创建一个接受3个学生分数的程序。输出将是他们取得的名称,标记和等级。 我的问题是,我只希望程序接受3个特定名称(例如Lisa,Lorraine,Susan),如果其他人输入其他名称,我希望它显示“无效”
另外 如您所见,我只能在用户输入正确的标记时显示学生姓名。 (“Hi Lisa,你的标记是”+标记)所以如果我输入另一个名字和相同的标记,它将显示相同的输出。 我该如何解决?
CODE:
package studentmarks;
import java.util.Scanner;
public class StudentMarks
{
public static void main(String[] args)
{
int mark;
int passmark = 50;
String name;
Scanner sc = new Scanner(System.in);
System.out.println(" Enter your name "); //ask user for name
name = sc.nextLine(); //accept input
System.out.println("Now please enter your mark"); //ask user to enter mark
mark = sc.nextInt(); //accept mark
if (mark == 60) //if mark = 60
{
System.out.println(" Hi Lisa, your mark is " + mark ); //output
}
if (mark ==12)
{
System.out.println("Hi Lorraine, you scored a mark of " + mark);
}
if (mark== 50)
{
System.out.println("Hi susan, you have scored a mark of " + mark);
}
if (mark < passmark)
{
System.out.println("FAIL");
}
if (mark >= passmark)
{
System.out.println("PASS");
}
}
感谢您抽出宝贵时间阅读本文。
答案 0 :(得分:0)
您需要验证步骤。您永远不会根据有效的值检查输入的name
。试试这个:
public static void main(String[] args)
{
// Initial setup stuff here
// ...
System.out.println("Enter your name:"); //ask user for name
name = sc.nextLine(); //accept input
boolean validName = validateName(name);
if(validName)
{
System.out.println("Now please enter your mark:"); //ask user to enter mark
mark = sc.nextInt(); //accept mark
System.out.println("Hi " + name + ". You scored a " + mark + ".");
String result = "pass";
if (mark < passmark)
{
result = "fail";
}
System.out.println("You " + result + ".");
}
else
{
System.out.println(name + " is not a valid entry.");
}
}
public boolean validateName(String name)
{
if(name.equalsIgnoreCase("Lisa") || name.equalsIgnoreCase("Lorraine") || name.equalsIgnoreCase("Susan")
{
return true;
}
return false;
}