我正在尝试比较两个数组,如果用户输入等于数组索引,那么它将仅打印数组索引/元素。
例如,如果用户输入为1,则阵列将仅打印第一行;如果用户输入为2,则阵列将打印第一和第二行,等等。
程序将打印错误12次。我想知道如何解决它。谢谢:D
我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TwelveDaysX {
public static void main(String[]args) {
/**
String text = readString("nameDays.txt");
System.out.println(text);
*/
Scanner input = new Scanner(System.in);
int[] numbers = new int [1];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
}
String[] words = readArray("nameDays.txt");
//System.out.println(words);
for (int i = 0; i < words.length; i++)
{
if(equalArrays(numbers, words))
System.out.println(words[i]);
else
System.out.println("Error :D");
}
}
public static String readString(String file)
{
String text = "";
try
{
Scanner s = new Scanner(new File(file));
while(s.hasNextLine())
{
text = text + s.nextLine() + " ";
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
return text;
}
public static String[] readArray(String file)
{
//Step 1: count how many elements are in the file
//Step 2: Create array and copy the elements in
int ctr = 0;
try
{
Scanner s1 = new Scanner(new File(file));
while(s1.hasNextLine())
{
ctr += 1;
s1.nextLine();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for(int i = 0; i < ctr; i++)
{
words[i] = s2.nextLine();
}
return words;
}
catch(FileNotFoundException e)
{
System.out.println("file not found");
}
return null;
}
public static boolean equalArrays(int[] a, String[] b)
{
if(a.length != b.length)
return false;
else
{
int i = 0;
while(i < a.length)
{
if(a[i] != 0)
return false;
i++;
}
}
return true;
}
}
我的文本文件名为Days.txt
One Patridge in a Pear Tree
Two Turtle Doves
Three French Hen
Four Calling Birds
Five Gold Rings
Six Geese-a-Laying
Seven Swans-a-Swimming
Eight Maids-a-Milking
Nine Ladies Dancing
Ten Lords-a-Leaping
Eleven Piper
Twelve Drummers Drumming