我正在尝试编写一个菜单来处理我的类以进行分配。我有我想尝试的课程但是我似乎在创建菜单时遇到了问题。
switch(choice)
{
case 1:
System.out.print("Please enter a filename: ");
filename = option.next();
//creating objects of the file manager to open the required files
FileManager e = new FileManager("Z:\\Java\\College\\Robo-Reader\\src\\"+filename+".txt");
FileManager e1 = new FileManager("Z:\\Java\\College\\Robo-Reader\\src\\punctuation.txt");
//creating connection to the files
e.connectToFile();
e1.connectToFile();
//Reading the files
String[] fileToBeRead= e.readFile();
String[] punctMarks = e1.readFile();
//closing the files
e.closeReadFile();
e1.closeReadFile();
fileRead++;
break;
case 2:
if(fileRead == 0)
{
System.out.println("No file was read. Please open a file to correct this error:");
}
else
{
FindLan t3 = new FindLan(fileToBeRead);
t3.cLang();
}
break;
case 3:
if(fileRead == 0)
{
System.out.println("No file was read. Please open a file to correct this error:");
}
else
{
//Creating the object for the remove punctuation class
RemovePunct t1 = new RemovePunct(punctMarks, fileToBeRead);
//Calling the EndArray(Remove) method to clean an array of punctuation marks
String[] cleanWords = t1.EndArray();
for(int i=0; i<10; i++)
{
System.out.println(cleanWords[i]);
}
}
default:
System.out.println("Option is not available");
}
所以我需要能够在案例2和3中使用案例1中的变量,但我需要在案例1中初始化它们以获得数组的长度。
到目前为止,我尝试使用try / catch块,但似乎无法解决问题。关于如何在其他情况下使用案例一的初始化值而不必在案例2/3中给出值的任何其他想法?
主要目标是能够使用在案例1中定义的数组,从filemanager类获取它们的大小和元素,并在其他2个案例中使用它们而不必定义大小或元素。
答案 0 :(得分:2)
将变量声明移到switch语句之外,如下所示:
FileManager e = null;
FileManager e1 = null;
String[] fileToBeRead;
String[] punctMarks;
switch(choice)
{
case 1:
System.out.print("Please enter a filename: ");
filename = option.next();
//creating objects of the file manager to open the required files
e = new FileManager("Z:\\Java\\College\\Robo-Reader\\src\\"+filename+".txt");
e1 = new FileManager("Z:\\Java\\College\\Robo-Reader\\src\\punctuation.txt");
//creating connection to the files
e.connectToFile();
e1.connectToFile();
//Reading the files
fileToBeRead= e.readFile();
punctMarks = e1.readFile();
//closing the files
e.closeReadFile();
e1.closeReadFile();
fileRead++;
break;
case 2:
if(fileRead == 0)
{
System.out.println("No file was read. Please open a file to correct this error:");
}
else
{
FindLan t3 = new FindLan(fileToBeRead);
t3.cLang();
}
break;
case 3:
if(fileRead == 0)
{
System.out.println("No file was read. Please open a file to correct this error:");
}
else
{
//Creating the object for the remove punctuation class
RemovePunct t1 = new RemovePunct(punctMarks, fileToBeRead);
//Calling the EndArray(Remove) method to clean an array of punctuation marks
String[] cleanWords = t1.EndArray();
for(int i=0; i<10; i++)
{
System.out.println(cleanWords[i]);
}
}
default:
System.out.println("Option is not available");
}