好的,所以我创建了这个未完成的程序,允许您将学生姓名和考试成绩插入到字符串中。但我可能是,我试图使用if语句,以便用户能够键入数字并选择他们想要做的事情。
我试图在用户插入名称和测试分数之后这样做,他们可以选择打印出名称和测试分数,或者他们可以退出或插入其他名称但我不能因为字符串未设置全局。
有谁知道怎么做?谢谢,
package week14;
import java.util.Scanner;
public class Task4 {
private static Scanner input;
private static Scanner input2;
public static void main (String [] args){
input2 = new Scanner (System.in);
System.out.println("Student Mark Program");
System.out.println("\nHere are your options:");
System.out.println("\n1. Insert Student name and mark");
System.out.println("2. Quit");
int choice = input2.nextInt();
System.out.println();
if (choice == 1){
opt1();
}
else if (choice == 2){
quit();
}
}
public static void opt1(){
input = new Scanner(System.in);
String firstname;
String surname;
int score1;
System.out.print("Enter the students first name: ");
firstname = input.next();
System.out.print("Enter the students surname: ");
surname = input.next();
String full_name;
full_name = firstname + " " + surname;
System.out.println("Please enter students score: ");
score1 = input.nextInt();
System.out.println("Name : " + full_name);
System.out.println("Score: " + score1);
System.out.println();
System.out.println("\nHere are your options:");
System.out.println("\n1. Insert Another Student name");
System.out.println("2. Get student name");
System.out.println("3. Get student name and mark");
System.out.println("4. Quit");
int choice = input.nextInt();
System.out.println();
if (choice == 1){
opt6();
}
else if (choice == 2){
opt2();
}
else if (choice == 3){
opt3();
}
System.out.println();
input.close();
}
public static void opt2(){
System.out.println("Name : " + full_name);
}
public static void opt3(){
}
public static void opt4(){
}
public static void opt5 (){
}
public static void opt6 (){
}
public static void quit(){
System.out.println("You have quit the program");
System.exit(0);
}
}
答案 0 :(得分:1)
将此static String full_name;
放在您在班级中声明private static Scanner input2;
的位置。使用全局变量不一定是良好的编程习惯,但为了您的目的,它可能会完成工作。
答案 1 :(得分:0)
好吧,我会初始化一个新的全局变量,将你的full_name设置为并将其作为一个存取方法返回。
public static String getName()
{
return (nameOfString);
}
另外,我看到你想要另外一个命令来改变你的名字,你可以用settor方法做到这一点。
public static void setName(String newName)
{
originalString = newName;
}