我是Java的新手,并且练习我尝试制作一个使用某些值(主要是字母)生成新的随机单词的程序。该程序旨在从文本文件中获取这些值。下一步是定义包含其类型的每个字母的清单(Arrays
)(首先通过为每个int
的长度定义变量(array
),然后填充每个数组用正确的字母(String
))。在检查我的进度时,我意识到我的代码并没有更新库存长度(cInv和vInv)。
这是代码的相关部分:
static File language;
static Scanner scanFile;
static Scanner scanInput = new Scanner(System.in);
static int cInv;
static int vInv;
//Getters go here
public static void setLanguage(File language) {Problem.language = language;}
public static void setCInv(int CInv) {Problem.cInv = cInv;}
public static void setVInv(int VInv) {Problem.vInv = vInv;}
//Asks for the file with the language values.
public static void takeFile() throws FileNotFoundException {
String route = scanInput.nextLine();
setLanguage(new File(route));
BufferedReader br;
br = new BufferedReader(new FileReader(language));
}
//Gathers the language values from the file.
public static void readFile() throws FileNotFoundException {
takeFile();
scanFile = new Scanner(language);
//Defines the inventory sizes. It seems the failure is here.
if (scanFile.hasNextInt()) {setCInv(scanFile.nextInt());}
if (scanFile.hasNextInt()) {setVInv(scanFile.nextInt());}
}
public static void main(String[] args) throws FileNotFoundException {
readFile();
//The following line is for checking the progress of my coding.
System.out.println(cInv);
}
这是它读取(或应该阅读)的文本文件的相关部分:
---Phonemes---
Consonants: 43
Vowels: 9
它的输出为0
我已尝试在文件的最开头键入43,我也尝试在输入中输入数字,但我仍然保持0。有人知道我错过了什么或做错了吗?
答案 0 :(得分:0)
首先,在重新分配相同的静态变量时更改分配。
public static void setCInv(int CInv) {Problem.cInv = CInv;}
public static void setVInv(int VInv) {Problem.vInv = CInv;}
第二,您需要移动文件中的所有标记以识别数字并更新相应的变量。
//Gathers the language values from the file.
public static void readFile() throws FileNotFoundException {
takeFile();
scanFile = new Scanner(language);
int num = 0;
scanFile.nextLine(); //Skip ---Phonemes---
setCInv(getInt(scanFile.nextLine()));
setVInv(getInt(scanFile.nextLine()));
}
public static int getInt(String str){
System.out.println(str);
int num =0;
Scanner line = new Scanner(str);
//Splits the scanned line into tokens (accessed via next()) and search for numbers.
//Similar thing could have been done using String.split(token);
while(line.hasNext()){
try{
num = Integer.parseInt(line.next());
return num;
}catch(NumberFormatException e){}
}
return num;
}