![](/img/trans.png)
[英]How to Read Text File From a Scanner and Convert Into an Int Array Java
[英]Using scanner to read text file and make a string for the words and an int array for the numbers Java
输入我的文件名后,它可以编译但不执行任何操作。
这是用于解码程序的,其中文本文件中有一个字符串(关键字短语),并且有一个数字代码,您必须通过在字符串的索引中查找来解码它们。
示例文本文件:
六种完美质量的黑色珠宝令州长大为惊讶
35 10 10 33 9 24 3 17 41 8 3 20 51 16 38 44 47 32 33 10 19 38 35 28 49
使用数字作为关键短语的字符索引,将其解码为“在黎明时攻击桥梁” 。
空格和重复的字母也计算在内。
public static void main (String[] args)
{
sc = new Scanner( System.in );
System.out.print("File name? ");
try
{
String fileName = sc.next().trim(); //requests file name then takes out spaces
sc = new Scanner( new File(fileName) );
String key = "";
while (sc.hasNext()) // looks for data
{
if (sc.hasNextLine()) //if data is a string
key = sc.nextLine(); //it is stored as key
}
int codeLen = 0;
while ( sc.hasNext() )
{
if ( sc.hasNextInt() ) // if the data is an integer
codeLen++; //calculates # of integers
}
int[] code = new int[codeLen]; //creates array of the size of the number of intergers in file
int num;
while ( sc.hasNext() )
{
if ( sc.hasNextInt() )
{
num = sc.nextInt(); //each number found is stored
for(int x = 0; x < codeLen; x++){
code[x] = num; //adds num to the array
}
}
}
System.out.println(secretcodeM(key, code)); // prints out secret message
}
}
catch ( FileNotFoundException ex )
{
System.out.println("File not found." );
System.out.println("Run the program again." );
}
不太重要,但以防万一。
public static String secretcodeM(String key, int[] code){
int codeLen = code.length;
StringBuilder secret = new StringBuilder(codeLen);
for (int x= 0; x < codeLen; x++) //goes through code
{
int index = code[x]; //finds the numbers in code and stores as index
char a = key.charAt(index); //finds the character in the index in key
secret.append(a); // add a to secret
}
return secret.toString();
}
如果您能说出问题所在,可以请您帮忙吗?
这是我的代码:
String fileName = "PathToFile";
List<String> strings = new ArrayList<String>();
//read file to an ArrayList
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
strings.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String code = strings.get(0);
String key = strings.get(1);
//cast String key to int[]
String[] numbers = key.split(" ");
int[] keyArr = new int[numbers.length];
for(int i = 0; i < numbers.length; i++) {
keyArr[i] = Integer.parseInt(numbers[i]);
}
然后您可以调用secretcodeM(code, keyArr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.