前提・実現したいこと
文字を入力して、それと全く同じ文がindex_word.txtにあれば、それが存在する文と同じ行のoutput_word.txtを出力。
これをendかexitと入力されるまで繰り返す。
発生している問題・エラーメッセージ
aとかbと入力すると、
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 4 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:372) at java.base/java.util.ArrayList.get(ArrayList.java:458) at Mathmagic.baseTalk(Mathmagic.java:24) at Mathmagic.main(Mathmagic.java:16)
となる。それ以外正常。
該当のソースコード
java
1import java.io.BufferedReader; 2import java.io.InputStreamReader; 3import java.io.IOException; 4import java.io.File; 5import java.util.ArrayList; 6import java.util.List; 7import java.util.Scanner; 8import java.io.FileNotFoundException; 9 10class Mathmagic { 11 public static void main(String []args){ 12 System.out.println("Please write here."); 13 List input = Scanner(library.file); 14 List output = Scanner(library.file2); 15 16 baseTalk(input,output); 17 18 } 19 private static void baseTalk(List input, List output){ 20 String str = ""; 21 while (!(str.equals("end")||str.equals("exit"))) { 22 str = BufferedReader(); 23 if(input.contains(str)&&input.size()==output.size()){ 24 System.out.println(output.get(output.indexOf(str))); 25 } 26 else System.out.println("error:Not defined"); 27 } 28 } 29 30 private static String BufferedReader(){ 31 String str = null; 32 try { 33 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 34 str = br.readLine(); 35 }catch (IOException ignored){ 36 37 } 38 return str; 39 } 40 private static List Scanner(File file){ 41 List<String> input = new ArrayList<>(); 42 try(Scanner sc = new Scanner(file)){ 43 while (sc.hasNextLine()){ 44 input.add(sc.nextLine()); 45 } 46 }catch (FileNotFoundException e){ 47 e.printStackTrace(); 48 } 49 return input; 50 } 51} 52 53class library{ 54 static File file = new File("word_input.txt"); 55 static File file2 = new File("word_output.txt"); 56}
input_word.txtとoutput_word.txtの内容は全く同じで、以下の通り。
a b
試したこと
input_word.txtにのっているaとかbを入力したときのみエラー。
のっていない場合は正常。
endとexitで終了させることは可能。
しかし、解決策は分からない。
補足情報(FW/ツールのバージョンなど)
Windows10,Java12
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。