have the text file containing a 2d array with a fixed row and column [6][3]
a 5 7
b 9 7
c 1 0
d 0 5
e 8 7
f 0 4
i need to put the data into array playerOne[][]
This is my code
try {
Scanner sc = new Scanner(new File("test.txt"));
while (sc.hasNextLine()) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 3; j++) {
String line = sc.next().trim();
if (line.length() > 0) {
playerOne[i][j] = line;
System.out.println(i+ " " +j+ " "+ line);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(Arrays.toString(playerOne));
}
i get an NoSuchElementException error, and it cannot print the array
instead of using nextLine use .next directly
.next will get the next value regardless to the next value line
try {
Scanner sc = new Scanner(new File("test.txt"));
while (sc.hasNext()) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 3; j++) {
String nextValue= sc.next().trim();
playerOne[i][j] = nextValue;
System.out.println(i+ " " +j+ " "+ nextValue);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(Arrays.toString(playerOne));
}
Related
Hi I am new on programing and I am having a problem I am trying to copy some things from a file to a array
and I just want to copy in the position 1,2,3 and 4 from the file. Example copy to the array 11 , G , 0 , 20.
FILE TEXT:
0;11;G;0;200;1
2;10;F;0;300;2
0;12;J;0;100;3
String[][] aa = new String[100][6];
try {
Scanner x = new Scanner(new File("Turmas.txt"));
x.useDelimiter("[;\n]");
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 6; j++) {
if (x.hasNext()) {
aa[i][j] = x.next();
}
}
}
x.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
String[][] aaa = new String[100][4];
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 4; j++) {
if (aa[i][j] == null) {
System.out.println("null " + i + " " + j);
}
else {
if (aa[i][0].equals(String.valueOf(SAVEID))) {
aaa[i][j] = aa[i][1];
aaa[i][j + 1] = aa[i][2];
aaa[i][j + 2] = aa[i][3];
aaa[i][j + 3] = aa[i][4];
}
}
}
}
System.out.println(aaa[0][0]);
System.out.println(aaa[0][1]);
System.out.println(aaa[0][2]);
System.out.println(aaa[0][3]);
If only 4 values are needed from the input array are needed, why not just read these specific values?
String[] result = new String[4];
try (Scanner input = new Scanner(new File("Turmas.txt")) // input closed automatically
.useDelimiter(";|\\R") // use character class \R to match line-feed characters
) {
if (input.hasNext()) {
input.next(); // skip the 1st token
for (int i = 0; i < result.length && input.hasNext(); i++) {
result[i] = input.next();
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
If it is needed to read the columns with indexes [1..4] from the file containing 6 columns per line, it is cleaner to read the source file line by line, split each line by ;, skip 1 column with index 0, and keep the 4 columns.
String[][] result = new String[100][4];
try (Scanner input = new Scanner(new File("Turmas.txt"))) {
for (int i = 0; i < result.length && input.hasNextLine(); i++) {
String[] parts = input.nextLine().split(";");
for (int j = 1; j < Math.min(result[i].length, parts.length); j++) {
result[i][j - 1] = parts[j];
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
This loop:
for(int j=0;j<4;j++)
runs again with a value of j = 1 after it completes the first iteration, so when it gets to the expression aaa[i][j+3] the second index evaluates to 4, which of course is illegal. I'm not sure why you used a for loop there, since you manually increment the index values as you assign the aaa values?
I have trouble compare 1D array with 2D array. I already import the txt file to 1D array and 2D array. The 1D array contains 20 correct answer (True and False). The 2D array contains 2000 student answers (100 students * 20 answers per student).
I want to design a program that shows the score for each student, which I already tried to program. Can you help me to figure out which part I did wrong?
The second part of the program is to print out for each question, how many student got right for each question?
Thank you so much!!
import java.io.*;
import java.util.Arrays;
public class Scores
{
public static void main(String[] args) {
try {
File AnswerFile = new File("/Users/shaovera/NetBeansProjects/Scores/QuestionAnswer.txt");
FileReader AnswerReader = new FileReader(AnswerFile);
BufferedReader answerreader = new BufferedReader(AnswerReader);
String[] words = new String[20];
for(int a = 0; a < words.length; a++) {
words[a] = answerreader.readLine();
System.out.println(words[a]);
}
answerreader.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
try {
File StudentFile = new File("/Users/shaovera/NetBeansProjects/Scores/StudentAnswer.txt");
FileReader StudentReader = new FileReader(StudentFile);
BufferedReader studentreader = new BufferedReader(StudentReader);
String[][] table = new String[100][20];
for (int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++) {
table[i][j] = studentreader.readLine();
System.out.print(table[i][j] + " ");
}
System.out.println("");
}
studentreader.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
int count=0;
int student=0;
String[] words = new String[20];
String[][] table = new String[100][20];
for (int column = 0; column < words.length; column++) {
for (int row = 0; row < 100; row++) {
if (words[row] == table[row][column]) {
count++;
student++;
System.out.print("student#" + student + ":" + count);
}
}
}
}
I think this correct code (I wrote comment in line when you have problems)
public static void main(String[] args){
String[]words= new String[20]; // before load from file
String[][]table =new String[100][20]; // before load from file
try{
File AnswerFile=new File("/Users/shaovera/NetBeansProjects/Scores/QuestionAnswer.txt");
FileReader AnswerReader = new FileReader(AnswerFile);
BufferedReader answerreader = new BufferedReader(AnswerReader);
for(int a=0; a<words.length;a++){
words[a]=answerreader.readLine();
System.out.println(words[a]);
}
answerreader.close();
}
catch (Exception ex){
ex.printStackTrace();
}
try{
File StudentFile=new File("/Users/shaovera/NetBeansProjects/Scores/StudentAnswer.txt");
FileReader StudentReader = new FileReader(StudentFile);
BufferedReader studentreader = new BufferedReader(StudentReader);
for (int i = 0; i <table.length; i++) {
for(int j=0;j < table[i].length; j++){
table[i][j]= studentreader.readLine();
System.out.print(table[i][j]+" ");
}
System.out.println("");
}
studentreader.close();
}
catch (Exception ex){
ex.printStackTrace();
}
for (int column = 0; column < words.length; column++) {
int student = 0;
for (int row = 0; row < table.length; row++) {
if (Objects.equals(words[column],table[row][column])) {
student++;
}
}
System.out.println("student#" + student + ":" + column);
}
}
I have a text document that contains a 5x5 table with these values
5 5
39 95 99 56 41
88 8 1 48 75
3 58 13 54 80
92 72 74 25 86
30 38 3 21 2
I have to add them into an array, and display the lowest value(which is 1) and tell the location of the lowest value(row 1 column 2).
public static void main(String[] args)
{
Scanner input;
File fileIn = new File("src/array2d/array2dtest1.txt");
System.out.println(fileIn.getAbsolutePath());
int[][] array = new int[5][5];
for(int row = 0;row<array.length;row++) {int[] column = array[row];
{
for(int columnIndex = 0; columnIndex<column.length; columnIndex++);
}
}
try
{
input = new Scanner(fileIn);
}
catch (FileNotFoundException e)
{
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
}
}
This code actually stores your input into an array.
public static void main(String[] args) {
Scanner input;
File fileIn = new File("src/array2d/array2dtest1.txt");
System.out.println(fileIn.getAbsolutePath());
int[][] array = new int[5][5];
try
{
input = new Scanner(fileIn);
String values = input.nextLine();
String[] value = values.split("\\s+");
int index = 0;
for(int row = 0;row < 5;row++)
{ index = row;
for(int col = 0 ; col < 5; col++){
array[row][col] = Integer.parseInt(value[index*5 + col]);
}
}
}
catch (FileNotFoundException e)
{
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
}
Using answer from #vikasn91, I edited it a bit to correctly assign the values to array, find the lowest number and its location in the array:
try {
input = new Scanner(fileIn);
int lowestCol = 0;
int lowestRow = 0;
int lowest = 0;
for (int row = 0; row < 5; row++) {
String values = input.nextLine();
String[] value = values.split("\\s+");
for (int col = 0; col < 5; col++) {
array[row][col] = Integer.parseInt(value[col]);
if (row == 0 && col == 0) {
lowest = array[row][col];
} else if (array[row][col] < lowest) {
lowestCol = col;
lowestRow = row;
lowest = array[lowestRow][lowestCol];
}
}
}
System.out.println("Lowest number: " + lowest);
System.out.println("Found in row: " + lowestRow + ", col: " + lowestCol);
} catch (FileNotFoundException e) {
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
public static void main(String[] args)
{
Scanner input;
File fileIn = new File("array2dtest1.txt");
System.out.println(fileIn.getAbsolutePath());
try
{
input = new Scanner(fileIn);
int row = input.nextInt();
int column = input.nextInt();
int min = Integer.MAX_VALUE;
int val;
int minR=0,minC=0;
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
val = input.nextInt();
if(val<min){
min = val;
minR = i;
minC = j;
}
}
}
System.out.println("Min Value is " + min + "\nat position (" + minR + "," + minC + ")" );
}
catch (FileNotFoundException e)
{
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
}
If you're using the Scanner, you don't need to split or parse integers directly. The default delimiter is space.
Scanner s = new Scanner(new FileReader("src/array2d/array2dtest1.txt"));
int numRows = s.nextInt();
int numCols = s.nextInt();
int[][] array = new int[numRows][numCols];
int least = Integer.MAX_VALUE;
int leastRow = -1;
int leastCol = -1;
for(int r = 0; r < numRows; r++) {
for(int c = 0; c < numCols; c++) {
if((array[r][c] = s.nextInt()) < least) {
leastRow = r;
leastCol = c;
}
}
}
Soo, I have to insert list of arrays into a specific text document.
The array list is inset by user at case 1 and it works well.
When I try call case 4 without any data, the file is created and also it's empty.
When I do this with an array list I get the Error message from catch.
How can I fix it?
Here is the call to function.
case 4: System.out.println("\nLungimea dintre doua orase alaturate\n");
try{
System.out.println("oabdobasoda");
salvareOras();
}catch (Exception e){
System.out.println("Eroare");
}
and here is the function.
public static void salvareOras()
{
for(int i = 0; i<drum.size()-1; i++){
for(int j = 0; i<drum.size(); j++){
if(drum.get(i).getPozitie() > drum.get(j).getPozitie()){
Oras aux = drum.get(i);
drum.add(i, drum.get(j));
drum.add(j, aux);
}
}
}
try {
FileOutputStream fOut = new FileOutputStream("distante.txt");
PrintStream ps = new PrintStream(fOut);
for(int i = 0; i <drum.size()-1; i++){
ps.println("d(" + drum.get(i).getNume()+","+drum.get(i+1).getNume()+")="+distOras(drum.get(i), drum.get(i+1)));
}
ps.close();
fOut.close();
} catch(IOException ex){
System.out.println("Nu s-a putut crea fisierul");
System.exit(1);
}
}
You made a minor mistake in your 2nd for loop:
for(int i = 0; i<drum.size()-1; i++){
//specifically on this line here:
for(int j = 0; i<drum.size(); j++){
//^//That is not j
if(drum.get(i).getPozitie() > drum.get(j).getPozitie()){
//that means ^ will throw an IndexOutOfBoundsException
Oras aux = drum.get(i);
drum.add(i, drum.get(j));
drum.add(j, aux);
}
}
}
Just change it to:
for(int i = 0; i<drum.size()-1; i++){
for(int j = 0; j<drum.size(); j++){
//^ j
if(drum.get(i).getPozitie() > drum.get(j).getPozitie()){
Oras aux = drum.get(i);
drum.add(i, drum.get(j));
drum.add(j, aux);
}
}
}
I have a program reading from a text file (currently 653 lines long) all separated by a comma. But when I go to save the file to a new location, it only saves 490 lines. It also seems that the last line in the newly created text file is cut in half. Any ideas on what might be the problem?
Here is the code that I used to open and sort the data in the list:
try {
scanner = new Scanner(file);
// Put the database into an array and
// Make sure each String array is 13 in length
while (scanner.hasNext()) {
line = scanner.nextLine();
word = line.split(",");
if (word.length < 13) {
String[] word2 = {"","","","","","","","","","","","",""};
for (int i = 0; i < word.length; i++) {
word2[i] = word[i];
}
dataBaseArray.add(word2);
}
else {
dataBaseArray.add(word);
}
}
}
catch (FileNotFoundException exc) {
JOptionPane.showMessageDialog(this, "File cannot be found.", "error finding file", JOptionPane.ERROR_MESSAGE);
}
// Splitting the database into vacant numbers/dead lines/vacant cubicles
for (int i = 0; i < dataBaseArray.size(); i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
vacantNums.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
deadLines.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
vacantCubs.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[7].equals("")) {
people.add(dataBaseArray.get(i));
}
else {
people.add(dataBaseArray.get(i));
}
}
// Resetting the DB Array to put the values back in it
dataBaseArray = new ArrayList<>();
// Ordering the arrays I want them to appear in the list
// Orering the people to appear in alphabetical order
Collections.sort(people, new Comparator<String[]>() {
#Override
public int compare(String[] strings, String[] otherStrings) {
return strings[7].compareTo(otherStrings[7]);
}
});
// Put the people in the DB Array
for (int i = 0; i < people.size(); i++) {
dataBaseArray.add(people.get(i));
}
// Put the vacant numbers in the AB Array
for (int i = 0; i < vacantNums.size(); i++) {
dataBaseArray.add(vacantNums.get(i));
}
// Put the vacant cubicles in the AB Array
for (int i = 0; i < vacantCubs.size(); i++) {
dataBaseArray.add(vacantCubs.get(i));
}
// Put the dead lines in the AB Array
for (int i = 0; i < deadLines.size(); i++) {
dataBaseArray.add(deadLines.get(i));
}
list = new String[dataBaseArray.size()];
// Add the DB Array to the list
for (int i = 0; i < list.length; i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
list[i] = "VACANT";
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
list[i] = "DEAD";
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
list[i] = "Vacant Cubicle";
}
else if (dataBaseArray.get(i)[7].equals("")) {
list[i] = dataBaseArray.get(i)[6];
}
else {
list[i] = dataBaseArray.get(i)[7] + ", " + dataBaseArray.get(i)[6];
}
}
// Populate the list
lstAdvance.setListData(list);
Here is what I used to save the file:
try {
saveFile = new FileWriter("Save Location");
String newLine = System.getProperty("line.separator");
for (int i = 0; i < dataBaseArray.size(); i++) {
for (int j = 0; j < dataBaseArray.get(i).length; j++) {
saveFile.append(dataBaseArray.get(i)[j] + ",");
}
saveFile.append(newLine);
}
}
catch (IOException exc) {
JOptionPane.showMessageDialog(this,"error", "error", JOptionPane.ERROR_MESSAGE);
}
Writing to a file is buffered. You have to close() or flush() your writer (saveFile) at the end of writing.
Even better: you should do close() on your writer in the finally block.
Try it using the FileWriter and BufferedWriter....
File f = new File("Your_Path");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
And yes..its very important to do bw.close() (Closing the Buffer)
See this question : Java FileWriter with append mode
The problem is that your FileWriter object needs to be "append mode" . Then, you append to the file with the "write" method rather than the "append" method. Use a finally catch clause to call "close" . You don't need to flush ( I dont think).