gpt4 book ai didi

java - 无法使我在嵌套循环中创建的菜单正常运行

转载 作者:行者123 更新时间:2023-11-30 10:22:01 25 4
gpt4 key购买 nike

我正在尝试创建需要使用大量菜单的程序(作为初学者,这些东西真的开始让我不知所措,但这是我类(class)的一个项目)。这是我目前所拥有的:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;


public class GroupUs {

public static void main(String[] args) {


String fileName = "CompConClass.txt"; //File includes class roster

System.out.println("Hello, would you like to access the class that you have on file or would you like to create a new class?");

int choice = mainMenu();
int choice2 = subMenu();

while (choice != 0) {
if (choice == 1) {

subMenu(); //calls subMenu method

if (choice2 == 1 ) {

try {
BufferedReader br = new BufferedReader(new FileReader(fileName));

String line = null; //create a line variable
while ((line = br.readLine()) != null) { //this will read the file line by line

System.out.println(line); //displays every line
}

} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}


}


} else if (choice == 2) {
System.out.println("test");
}

choice = mainMenu();

}

}

public static int mainMenu() {
Scanner scan = new Scanner(System.in); // Reading from System.in
System.out.println( "Press 0 to quit.\n"
+ "Press 1 to access the class that you have on file.\n"
+ "Press 2 to create a new class.\n"
);
return scan.nextInt(); // Scans the next token of the input as an int.
}

public static int subMenu() {
Scanner scan = new Scanner(System.in); // This method will give the teacher the ability to view the roster from the file or add students on to that file
System.out.println( "What would you like to do to the class on file?\n"
+ "Press 1 to view the students.\n"
+ "Press 2 to add another student.\n"
+ "Press 3 to remove a student."
);
return scan.nextInt(); // Scans the next token of the input as an int.
}

具体来说,我在这部分代码上遇到了问题

  if (choice == 1) {  

subMenu(); //calls subMenu method

if (choice2 == 1 ) {

try {
BufferedReader br = new BufferedReader(new FileReader(fileName));

String line = null; //create a line variable
while ((line = br.readLine()) != null) { //this will read the file line by line

System.out.println(line); //displays every line
}

} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}

发生的事情是程序最初通过向用户呈现我创建的第一个 mainMenu 方法开始良好。当我输入数字 1 打开我的 subMenu 方法时,它也能正常工作。但是,当我在子菜单的一侧再次按 1(这次是显示文件中的花名册)时,它只是再次打印出子菜单。我再次按 1,然后它会根据需要显示花名册。我不明白为什么我无法在第一次显示它。

最佳答案

int choice2 = subMenu();

while (choice != 0) {
if (choice == 1) {

subMenu(); //calls subMenu method

您调用了 subMenu() 方法两次,这就是它被运行两次的原因。

关于java - 无法使我在嵌套循环中创建的菜单正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47544838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com