1
4000または0
が各行に 1 つずつ含まれる入力ファイルを読み取るプログラムがあります。
プログラムは正常にコンパイルされますが、実行すると次のエラーが発生します。
ˇ˛0Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Project1.main(Project1.java:27)
何らかの理由で、テキスト ファイルを見ると、最初の行は a0
であり、プログラムが取得した最初の行を読み取るときはまだ何もありませんˇ˛0
。また、バッファリングされたリーダーを使用してみましたが、うまくいきませんでした。どなたかご意見をお聞かせください。ありがとうございました!
これが私のコードです:
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class Project1 {
public static void main(String[] args) {
int [] stream = new int[4000];
int [] received = new int[4000];
int corrupt = 0;
float standardDev = 0;
float [] averages = new float[4000];
float averagev = 0;
float voltage = 0;
try {
Scanner st = new Scanner(new File("CS 380 bit feed.txt"));
System.out.print(st.next());
FileWriter outFile = new FileWriter("output");
PrintWriter out = new PrintWriter(outFile);
int i=0;
Random rand = new Random();
stream[i]=st.nextInt();
if (stream[i] == 0)
voltage = (float) (2.49 * rand.nextFloat());
else
voltage = (float) ((2.5 * rand.nextFloat()) + 2.5);
if (voltage < 2.5)
received[i] = 0;
else
received[i] = 1;
averagev = voltage;
averages[i] = voltage;
if (stream[i] != received[i])
corrupt++;
i++;
while (i < 4000) {
stream[i]=st.nextInt();
if (stream[i] == 0)
voltage = (float) 2.49 * rand.nextFloat();
else
voltage = (float) ((2.5 * rand.nextFloat()) + 2.5);
averagev = ((averagev * i) + voltage)/(i+1);
if (voltage <= averagev)
received[i] = 0;
else
received[i] = 1;
if (stream[i] != received[i])
corrupt++;
i++;
}
averagev = 0;
int j = 0;
while (j < 4000) {
for (int k = 0; k<8; k++) {
out.print(received[j]);
averagev = averages[i] + averagev;
j++;
}
out.println(" " + averages[j]);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
averagev = averagev / 4000;
for (int k = 0; k<4000; k++)
standardDev = ((averagev - averages[k])*(averagev - averages[k])) + standardDev;
standardDev = standardDev/4000;
System.out.println("Errors: " + corrupt);
System.out.println("Percentage Corrupt: " + corrupt / 4000);
System.out.println("Average of Average Voltages: " + averagev);
System.out.println("Standard Deviation: " + standardDev);
}
}