好吧,我创建了这个未完成的程序,它允许您将学生姓名和测试分数插入到字符串中。但我的可能是,我尝试使用 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);
}
}
最佳答案
将此 static String full_name;
放在类中声明 private static Scanner input2;
的位置下。使用全局变量不一定是良好的编程习惯,但出于您的目的,它可能会完成工作。
关于java - 字符串 - 全局设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28709266/