Читать два файла и сравните каждую строку по элементуJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Читать два файла и сравните каждую строку по элементу

Сообщение Anonymous »

Я хочу прочитать два файла и сравнить каждый элемент обоих файлов. Все строки файлов такие: 17-995-364, ruh, konrad, julia < /em>
У меня есть два класса: < /p>

public class Student {
public String name;
public Student (String name) {
this.name = name;
}
public static String[] toString(String name)
{
String s1 = ""; String s2 = ""; String s3 = ""; String s4 = "";
int position = 0;
for(int i = 0; name.charAt(i) != name.length(); i++)
{
if (name.charAt(i) == ',') {++position; continue;}
if (position == 0) s1 += name.charAt(i);
if (position == 1) s2 += name.charAt(i);
if (position == 2) s3 += name.charAt(i);
if (position == 3) s4 += name.charAt(i);
}
String[] s = new String[4];
return s;
}
}
< /code>

и < /p>

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
* This class reads-in a *.csv file.
* -
*/
public class CSVReader {

/**
* This method reads-in a *.csv file and
* saves each element as entry
* of a bidimensional array.
*
* @param filename track to the file, z.b. ".Root/test/echo.csv"
* @return {@code String[][] s} where {@code s[j]} is the j-th value
* in the i-th line
*/
public static String[][] readCSV(String filename) {
ArrayList result = new ArrayList();

BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; br != null; ++i)
{
for (int j = 0; j < 4;)
{
if (result.charAt(i) == ',') {++j; continue;}
result[j] += name.charAt(i);
}
}
try {
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {
result.add(line.split(cvsSplitBy));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result.toArray(new String[result.size()][]);
}
}
< /code>

Класс CSVReader не завершен, и основной класс тоже: < /p>

/**
*Основной класс программы Java.
*
* /< /p>

public class main {< /p>

public static void main(String[] args) {

/**
* Read in "./Root/files/echo.csv" und "./Root/files/file1.csv"
* and output the respective warning on System.out
*/
String[][] codeexpert = CSVReader.readCSV("./Root/files/file1.csv");
String[][] echo = CSVReader.readCSV("./Root/files/echo.csv");
for (int i = 0, i != file1.end ; ++i)
{
System.out.println(readCSV(file1(i));
}
System.out.println(codeexpert);
System.out.print(echo);
}
< /code>

} < /p>

Я хочу выполнить функцию сортировки, но до этого вывод в основном классе должен быть правильным. На данный момент у меня есть ошибки компиляции. Функция сортировки не проблема для меня, если я получу элементы, как я хотел бы. Кроме того, я должен использовать Tostring Fonction ученика класса. Как я могу разрешить ошибки компиляции в основном классе и является ли метод readscv, как это?./Root/src/Main.java:16: error: ';' expected
for (int i = 0, i != file1.end ; ++i)

./Root/src/Main.java:16: error: illegal start of expression
for (int i = 0, i != file1.end ; ++i)

./Root/src/Main.java:16: error: ';' expected
for (int i = 0, i != file1.end ; ++i)

./Root/src/Main.java:16: error: illegal start of expression
for (int i = 0, i != file1.end ; ++i)

./Root/src/Main.java:16: error: ')' expected
for (int i = 0, i != file1.end ; ++i)

./Root/src/Main.java:16: error: ';' expected
for (int i = 0, i != file1.end ; ++i)

./Root/src/Main.java:18: error: ')' expected
System.out.println(readCSV(file1(i));
< /code>

7 ошибок < /p>

Мне нужно, чтобы это было: < /p>

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;

/**
* Helper functions for testing
*/
public class MatchingTest {

/**
* Current Project Directory.
*/
public final static String curDir = Paths.get("").toAbsolutePath().toString() + "/Root/";

static ByteArrayOutputStream outContent = new ByteArrayOutputStream();
static ByteArrayOutputStream errContent = new ByteArrayOutputStream();

/**
* Copies the test files to the files directory, overwriting existing files
*
* @param dir Directory in which test files are stored
* @param test_prefix E.g. "00", "01", etc
*/
public static void copy_testfiles(String dir, String test_prefix) {

try {

// Paths to test files
Path test_echo = Paths.get(curDir + dir + test_prefix + "_echo.csv");
Path test_codeexpert = Paths.get(curDir + dir + test_prefix + "_codeexpert.csv");

// Target path
Path target_echo = Paths.get(curDir + "files/echo.csv");
Path target_codeexpert = Paths.get(curDir + "files/codeexpert.csv");

Files.copy(test_echo, target_echo, StandardCopyOption.REPLACE_EXISTING);
Files.copy(test_codeexpert, target_codeexpert, StandardCopyOption.REPLACE_EXISTING);

} catch (IOException e) {
throw new RuntimeException("Could not copy test files", e);
}
}

/**
* Reads the file containing the expected output and returns it as a String
* @param dir Directory in which test files are stored
* @param test_number
* @return Contents of ./dir/[test_number]_output.txt
*/
static String output(String dir, String test_number) {
try {
Path test_output = Paths.get(curDir + dir + test_number + "_output.txt");
return new String(Files.readAllBytes(test_output));
} catch (IOException e) {
throw new RuntimeException("Could not open test solution file", e);
}
}

/**
* This method compares the output to the correct solution.
* It should be able to differentiate between lines that don't match the formating,
* lines that are misordered and lines that shouldn't be in the oputput at all
*
* @param expected Answer that we expect
* @param actual Submitted answer
*/
static void compare(String expected, String actual) {
// Split strings into lines and save in a collection
List expected_lines = Arrays.asList(expected.split("(\r\n|\r|\n)", -1));
List actual_lines = Arrays.asList(actual.split("(\r\n|\r|\n)", -1));

String name = "[a-zA-Z'-]+( [a-zA-Z'-]+)?";
String pattern1 = name + " is enrolled to " + name + " in Echo, but registered with " + name + " in CodeExpert.";
String pattern2 = name + " is enrolled to " + name + " in CodeExpert, but registered with " + name + " in Echo.";
String pattern3 = name + " is in CodeExpert but not in Echo.";
String pattern4 = name + " is in Echo but not in CodeExpert.";
String pattern = "((" + pattern1 + ")|(" + pattern2 + ")|(" + pattern3 + ")|(" + pattern4 + "))";

// Special case: A case with no misassigned students should produce no output
if (expected.equals("")) {
assertEquals("There should be no output if there are no misassigned students.", expected, actual);
}

// Check all lines
for (int i = 0; i < actual_lines.size(); ++i) {

if (expected_lines.get(i) != actual_lines.get(i)) {

if (!actual_lines.get(i).matches(pattern)) {
// Line is malformed
assertEquals("Line " + i + " is malformed", expected_lines.get(i), actual_lines.get(i));
}

if (expected_lines.contains(actual_lines.get(i))) {
//Line is correct, but at wrong position
int expected_line = expected_lines.indexOf(actual_lines.get(i));
if (actual_lines.contains(expected_lines.get(i))) {
// Expected line for this position is there but at wrong position
assertEquals("Wrong order in output, " +
"line " + i + " should be at position " + expected_line,
expected_lines.get(i), actual_lines.get(i));
} else {
// Expected line is missing
assertEquals("Missing output item on line " + i, expected_lines.get(i), actual_lines.get(i));
}
} else {
// Line should not appear in output
assertEquals("Line " + i + " should not be part of output", expected_lines.get(i), actual_lines.get(i));
}
}

}

}

/**
* Verify that there was no output to System.err
*/
static void checkErr() {
assertEquals("There should be no output on err", "", errContent.toString());
}

/**
* Redirect the output from the console to a Stream we can save
*/
@Before
public void setUpStreams() {
outContent.reset();
errContent.reset();
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}

/**
* Restore routing of output to the console
*/
@After
public void restoreStreams() {
System.setOut(System.out);
System.setErr(System.err);
}

/**
* This test is simply here to workaround a Codeboard.io issue
*/
@Test
public void dummyTest() {
// empty test passes
}
}


Подробнее здесь: https://stackoverflow.com/questions/498 ... by-element
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»