【发布时间】:2015-07-14 14:43:59
【问题描述】:
为什么在我开始时会发生这种情况(?,我刚刚声明了变量的名称,我不确定那叫什么太累而无法知道)案例之外的变量,为什么不只是改变多变的。这不像我正在制作它的一个实例。为什么我必须做一个实例?这似乎是我应该能够做的一件简单的事情。我如何在不进行任何静态变量的情况下解决这个问题。
我在下面有一些我正在处理的代码,我想我把它全部留在里面,但是看看第三种情况,当我尝试运行它时,我在第二种情况下更改的内容不会影响变量,例如名称[] 和amouintOfNameds;
代码:
package comp1skeleton2015;
class InputOutput
{
public static void main (String args[])
{
AQAConsole2015 console = new AQAConsole2015();
AQAWriteTextFile2015 writeAQA = new AQAWriteTextFile2015();
AQAReadTextFile2015 readAQA = new AQAReadTextFile2015();
String doProgram = "yes";
while(doProgram.equals("yes"))
{
String[] names;
String fileOutput = "names.txt";
int amountOfNames = 0;
int amountOfNames2 = 0;
int x = 0;
names = new String[1];
names[0] = "";
console.println("Would you like to: ");
console.println("1 - Write names to a file ");
console.println("2 - Read names from a file ");
console.println("3 - Display these names ");
int option = console.readInteger("Please enter the corresponding number for the option: ");
switch (option)
{
case 1:
{
int numOfNames = console.readInteger("Please enter how many names you would like to enter ");
names = new String[numOfNames];
writeAQA.openFile(fileOutput);
for (int i = 0; i < numOfNames; i++)
{
String temp = console.readLine("Enter name " + i + ".");
writeAQA.writeToTextFile(temp);
}
writeAQA.closeFile();
}
break;
case 2:
{
readAQA.openTextFile(fileOutput);
boolean continueLoop = true;
while(readAQA.readLine() != null)
{
amountOfNames = amountOfNames + 1;
}
console.println (amountOfNames);
readAQA.closeFile();
readAQA.openTextFile(fileOutput);
names = new String[amountOfNames];
for(int i = 0; i < amountOfNames; i++)
{
names[i] = readAQA.readLine();
}
amountOfNames2 = amountOfNames;
readAQA.closeFile();
}
break;
case 3:
{
console.println (amountOfNames2);
console.println(names[1]);
for(int y = 0; y < amountOfNames; y++)
{
console.println(y + ": " + names[y]);
}
}
break;
default:
{
console.println("You have entered an incorrect option, please try again");
}
break;
}
//doProgram = console.readLine("yes to continue");
}
}
}
您非常喜欢阅读,我希望能帮助您度过难关,谢谢。
【问题讨论】:
-
在你的while循环中,你不断地初始化你的名字变量。在循环外声明并初始化“名称”。
-
单步调试器下的代码。当您认为变量应该更改时,请查看它们,并确保实际执行了部分代码。还要确保您不会无意中重新初始化要保留的数据。调试器是你的朋友 :)
标签: java while-loop scope initialization