Filling a matrix with content from file - java

I'm getting an error on my code. The goal is to add the contents of a file to a matrix.Then ill eventually need to parse it to add it to a graph so that i can eventually perform a depth-first search on it. But until then i need to figure this error out. I can't figure out what exactly is causing the error. so any help would be nice.
Here is the error im getting:
Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at DelivA.<init>(DelivA.java:53)
at Prog340.actionPerformed(Prog340.java:120
Here is the class i wrote.
public DelivA(File in, Graph gr) {
inputFile = in;
g = gr;
// Get output file name.
String inputFileName = inputFile.toString();
String baseFileName = inputFileName.substring(0, inputFileName.length() - 4); // Strip off ".txt"
String outputFileName = baseFileName.concat("_out.txt");
outputFile = new File(outputFileName);
if (outputFile.exists()) { // For retests
outputFile.delete();
}
try {
output = new PrintWriter(outputFile);
} catch (Exception x) {
System.err.format("Exception: %s%n", x);
System.exit(0);
}
// --------------------------------Deliverable
// A-------------------------------------------//
FileReader f1 = null;
int c = 0;
int r = 0;
try {
f1 = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scanner = new Scanner(f1);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String splitLine[] = line.split(" ");
c = splitLine.length;
r++;
}
String[][] matrix = new String[c][r];
#SuppressWarnings("resource")
Scanner s1 = new Scanner(f1);
for (int row = 0; row < matrix.length; row++) {
String words = s1.next(); // will scan each row of the file
for (int col = 0; col < matrix[row].length; col++) {
char ch = words.charAt(col); // will put each character into array
matrix[row][col] = String.valueOf(ch);
}
}
}
}

Your problem is probably here:
String words = s1.next():
You are not verifying if there is any line available.
You should do something like this:
...
Scanner s1 = new Scanner(f1);
for (int row = 0; row < matrix.length; row++) {
if (scanner.hasNextLine()){
String words = s1.next(); // will scan each row of the file
...
Of course you should rethink the code logic accordingly...

Related

Having problems editing text files in java

Hey there somy code below is supposed to do one thing its hard to explain but i will try
for example this is the content of my txt file
atif12,123,0
kamran11,134,0
abh3,123,0
now if my username is kamran 11 and password is 134 which I entered so this program should turn the 0 to 500 and keep the rest as it is but my file gets updated and only shows this
kamran11,134,500
thus all is deleted and I don't know where I went wrong can someone correct me, please?
File file = new File("customer.txt");//this is the txtfile
ArrayList<String> lines = new ArrayList<>();
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
lines.add(in.nextLine());
}
} catch (FileNotFoundException eo) {
throw new RuntimeException("File not found");
}
String comp=username+","+pass;
try (FileWriter out = new FileWriter(file)) {
for (int i = 0; i < lines.size(); i++) { //iterate over lines
String comp2=lines.get(i);
System.out.println(comp2);
if(comp2.contains(comp)){
String[] parts = lines.get(i).split(","); //split line by commas
for (int j = 0; j < parts.length; j++) { //iterate over parts
if (j == 2) { //if I hit the first element in this line that is a zero
int temp = Integer.parseInt(parts[j]);
temp = temp + 500;
parts[j] = Integer.toString(temp);
break; //break out of the loop
}
}
for (int j = 0; j < parts.length; j++) { //iterate over all the parts and write them back
System.out.println("this work");
out.write(parts[j]);
if (j < parts.length - 1) { //only add a comma if it isn't at the end of the line
out.write(',');
}
}
if (i < lines.size() - 1) { //add a line break if it isn't the last line
System.out.println("this work1");
out.write('\n');
}
//break;
}
else{
System.out.println("this dont work");
}
}
out.flush(); //write everything to the file
} catch (IOException ep) {
throw new RuntimeException("IO exception occurred");
}
Based on our discussion here, and the information provided in this question, I believe you want the following:
File file = new File("customer.txt");
ArrayList<String> lines = new ArrayList<>();
Scanner sc = new Scanner(System.in);
String user = sc.nextLine(); //ask user for the username
String pwd = sc.nextLine(); //ask user for the password
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) { //read in all lines
lines.add(in.nextLine());
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
}
try (FileWriter out = new FileWriter(file)) {
for (int i = 0; i < lines.size(); i++) { //iterate over lines
String[] parts = lines.get(i).split(","); //split line by commas
if (parts[0].equals(user) && parts[1].equals(pwd)) { //if username and password match first and second parts of line, respectively
parts[2] = "500"; //set third part of line to 500
}
for (int j = 0; j < parts.length; j++) { //iterate over all the parts and write them back
out.write(parts[j]);
if (j < parts.length - 1) { //only add a comma if it isn't at the end of the line
out.write(',');
}
}
if (i < lines.size() - 1) { //add a line break if it isn't the last line
out.write('\n');
}
}
out.flush(); //write everything to the file
} catch (IOException e) {
throw new RuntimeException("IO exception occurred");
}

Copying a text file into a 2D char array in java

I'm working on reading a text file that contains an 5x6 character big ascii image. Here's what i've done so far:
...
Scanner fileReader = null;
try{
File file = new File(fileName);
fileReader = new Scanner(file);
int offset = 0;
char [][] pic = new char[5][6];
while (fileReader.hasNextLine()){
for (int u = 0; u < row; u++){
for (int i = 0; i < col; i++){
String line = fileReader.nextLine();
pic[u][i] = line.charAt(offset++);
}
}
return pic;
}
fileReader.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}...
This gives me a "no line found" message. I'm wondering if the scanner i use to ask the user the name of the file is a part of the problem. Here's what that looks like:
System.out.println("Hello! I load files.");
System.out.println("Please, enter file name:");
Scanner reader = new Scanner(System.in);
String fileName = reader.nextLine();
I've tried to close the reader after but it didn't change anything. Any help is much appreciated.
Several things :
First, you are attempting to read a line for each index of your array (that is row*col times).
Second, you should only read a line by row.
You may replace your whole while loop with this :
for (int u = 0; u < row && fileReader.hasNextLine(); u++) {
String line = fileReader.nextLine();
for (int i = 0; i < col; i++) {
pic[u][i] = line.charAt(offset++);
}
offset = 0;
}
return pic;
Also , you probably want to reset the value of offset after each processed "row".
Scanner fileReader = new Scanner (new File("file.txt"));
int i = 0;
char[][] pic = new char[5][];
while (fileReader.hasNextLine()){
String line = fileReader.nextLine();
pic[i] = line.toCharArray();
i++;
}
fileReader.close();
I tried it with seuqnce and worked:
Scanner fileReader = new Scanner(System.in);
System.out.println(fileReader.nextLine());
fileReader.close();
fileReader = new Scanner (new File("file.txt"));
int i = 0;
char[][] pic = new char[5][];
while (fileReader.hasNextLine()){
String line = fileReader.nextLine();
pic[i] = line.toCharArray();
System.out.println(line);
i++;
}
fileReader .close();
output:
sadsadd sadsadd
sadasdasdasdsad sadasdasdsadsa sadasdasdsadsadsa dAS dASd
Process finished with exit code 0

How a read a txt file in a array and then print in console some value in Java?

I have a problem. I have a txt file with some value, and I try to use eclipse to read and parse that txt file in a array and then put some condition to write that array in console. The text that I use to read txt file and parse in array is this:
public void Transaction(String filepath, String user)
{
String [] [] myArray = new String[100][3];
Scanner scanIn = null;
int Rowc = 0, Colc = 0;
String InputLine = "";
double xnum = 0;
String username, tranzactie, info;
try
{
scanIn = new Scanner ( new BufferedReader(new FileReader(filepath)));
while(scanIn.hasNextLine())
{
InputLine = scanIn.nextLine();
String[] InArray = InputLine.split(",");
for(int x = 0; x<InArray.length; x++)
{
myArray[Rowc][x] = InArray[x];
}
Rowc++;
}
for (int i = 0; i<Rowc; i++)
{
for (Colc = 0; Colc < 3; Colc ++)
{
System.out.print(myArray[i][Colc]+ ",");
}
System.out.println();
}
}catch (Exception e)
{
System.out.println("Error");
}
}
The txt file is this:
John,SoldInterogation
John,PayInvoice,He pay 30 EUR
Alex,PayInvoice,He pay 15 EUR
Alex,BankTransfer,He transfered 50 EUR
John,SoldInterogation
How can I write in the console just the transaction for john or Alex, or ... . What I must adding in my java code for do this? I must write only the transaction, this mean only the 2 column of the txt file, the user ( John, Alex) this musn't write in the console.
Just test if InArray is length 3, and if it is : add its two last strings to a String variable.
Then just println this String variable after your reading loops.
try
{
// A String variable to println after the reading.
String consoleResume = "";
scanIn = new Scanner ( new BufferedReader(new FileReader(filepath)));
while(scanIn.hasNextLine())
{
InputLine = scanIn.nextLine();
String[] InArray = InputLine.split(",");
for(int x = 0; x<InArray.length; x++)
{
myArray[Rowc][x] = InArray[x];
}
// There is a transaction when you have 3 strings in InArray
if (InArray.length()==3)
consoleResume+=InArray[1]+":"+InArray[2]+"\n";
Rowc++;
}
System.out.println(consoleResume);
}catch (Exception e)
{
System.out.println("Error");
}
You can also println the transactions inside your loop :
try
{
scanIn = new Scanner ( new BufferedReader(new FileReader(filepath)));
while(scanIn.hasNextLine())
{
InputLine = scanIn.nextLine();
String[] InArray = InputLine.split(",");
for(int x = 0; x<InArray.length; x++)
{
myArray[Rowc][x] = InArray[x];
}
// There is a transaction when you have 3 strings in inArray
if (InArray.length()==3)
System.out.println(InArray[1]+":"+InArray[2]);
Rowc++;
}
}catch (Exception e)
{
System.out.println("Error");
}

Reading a text file into a char[][] array in Java

I am trying to fill a char[][] array from a text file and I cannot seem to figure out how to do it. I've tried to use .toCharArray() but it doesn't seem to work. If you can give any insight on how to make this work that would be awesome!
String filename = "ArrayHW2.txt";
int numTests = 6;
char[][] testAnswers = new char[50][5];
char[] key = new char[4];
Scanner input = null;
try
{
input = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening File");
System.exit(1);
}
for(int row = 0; row < testAnswers.length; row++)
{
for(int col = 0; col < testAnswers[row].length; col++)
{
testAnswers[row][col] = input.next().toCharArray();
}
}
input.close();
The basic problem is that you are trying to assign a character array to something was meant to hold a character. You might think of char[] type as storing the location in memory where characters are recorded, and a char type as the character itself.
When you call toCharArray() on a String, the return type is char[]. It looks like you expect this array to have a single character, like the A, B, C, or D of a multiple-choice test. You could get the first (and only?) character of that array with something like ...toCharArray()[0], but this is wasteful because a new array is created, and characters are copied into it from the source string. It's simpler to use the getCharAt() method on the String directly.
String filename = "ArrayHW2.txt";
char[][] testAnswers = new char[50][5];
try (Scanner input = new Scanner(Paths.get(filename))) {
for(int row = 0; row < testAnswers.length; row++) {
for(int col = 0; col < testAnswers[row].length; col++) {
String token = r.next();
if (token.length() != 1)
throw new IllegalArgumentException("Answers must be one character");
testAnswers[row][col] = token.charAt(0);
}
}
} catch (IOException ex) {
System.err.println("Error reading file: " + ex.getMessage());
System.exit(1);
}
String filename = "ArrayHW2.txt";
int numTests = 6;
char[][] testAnswers = new char[50][5];
//char[] key = new char[4];
Scanner input = null;
try
{
input = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening File");
System.exit(1);
}
int counter = 0;
while(scanner.hasNext())
{
copyString(testAnswers[counter], scanner.nextLine());
}
input.close();
its been a while i haven't code in java and im not sure about the methods but consider it a pseudo code .
you can use this copy :
void copyString(char[] arr, String x)
{
int size = x.length();
for (int i=0; i<size; i++){
arr[i] = x.CharAt(i);
}

how to refresh the content of the jtable if you're using notepad to putting data in the jtable

public void readCar() {
String choice = String.valueOf(car_combo1.getSelectedItem());
int ctr = 0;
String filename = null;
if (choice.equals("STATE-Description")) {
filename = TEXT_CAR1.getText();
ctr = 12;
} else if (choice.equals("DISCAS-Camera")) {
filename = TEXT_CAR2.getText();
ctr = 3;
} else if (choice.equals("DISCAS-CAR(for removal)")) {
filename = TEXT_CAR3.getText();
ctr = 11;
} else if (choice.equals("DISCAS-PAR(for removal)")) {
filename = TEXT_CAR4.getText();
ctr = 9;
} else if (choice.equals("Closing CAS for chg w/ customer initiated")) {
filename = TEXT_CAR5.getText();
ctr = 11;
}
try {
File file = new File(filename);
FileReader fr = new FileReader(file.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
for (int i = 0; i < ctr; i++) {
dataCar[i] = br.readLine();
String[] temp;
temp = dataCar[i].split("\\*");
car_table.setValueAt(temp[0], i, 0);
car_table.setValueAt(temp[1], i, 1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This is the read function
private void car_combo1ActionPerformed(java.awt.event.ActionEvent evt) {
String choice = String.valueOf(car_combo1.getSelectedItem());
JTableHeader th = car_table.getTableHeader();
if (choice.equals("STATE-Description")) {
car_table.getColumnModel().getColumn(0).setHeaderValue("STATE");
car_table.getColumnModel().getColumn(1).setHeaderValue("Description");
String[] change_choice_to = {"-", "1006", "1009", "1011", "1013", "1015", "1017", "1018", "1019", "1020", "1021", "1022", "1023"};
DefaultComboBoxModel model = new DefaultComboBoxModel(change_choice_to);
car_combo2.setModel(model);
DefaultTableModel model2 = (DefaultTableModel) car_table.getModel();
model1.fireTableDataChanged();
readCar();
}
}
table.repaint(); and tableModel.fireTableDataChanged(); doesn't work. I tried both of those function but the jtable wouldn't refresh. The notepad with more lines in it stays in the jTable when a lesser lined notepad is called.
I'm using BufferedReader and FileReader to read it from the notepad.
Is there anyway to refresh the table into its default then show the data from the notepad again? Thank you.
So, the basic idea is either you want to update the existing TableModel or replace it with a new one.
Because the number rows seems to change between requests, replacing the model seems to be the safer bet, for example;
This is taken from you readCar method as it's the important part...
try (BufferedReader br = new BufferedReader(new FileReader(new File(filename)))) {
DefaultTableModel model = new DefaultTableModel(new String[]{"STATE", "Description"}, 0);
for (int i = 0; i < ctr; i++) {
dataCar[i] = br.readLine();
String[] temp = dataCar[i].split("\\*");
model.addRow(temp);
}
car_table.setModel(model);
} catch (IOException e) {
e.printStackTrace();
}
All this does is create a new DefaultTableModel, for each line of the file, adds a row to the model and then applies the model to the table when it's done.
If this fails, either there is something else in your code which isn't working or the file is been read (or saved) properly
Take a look at How to Use Tables and The try-with-resources Statement for more details
public void eraseTableCar(){
for(int i = 0; i<110 ; i++){
car_table.setValueAt(" ",i,0);
car_table.setValueAt(" ",i,1);
}
}
public void readCar() {
String choice = String.valueOf(car_combo1.getSelectedItem());
int ctr = 0;
String filename = null;
if (choice.equals("STATE-Description")) {
filename = TEXT_CAR1.getText();
ctr = 12;
} else if (choice.equals("DISCAS-Camera")) {
filename = TEXT_CAR2.getText();
ctr = 3;
} else if (choice.equals("DISCAS-CAR(for removal)")) {
filename = TEXT_CAR3.getText();
ctr = 11;
} else if (choice.equals("DISCAS-PAR(for removal)")) {
filename = TEXT_CAR4.getText();
ctr = 9;
} else if (choice.equals("Closing CAS for chg w/ customer initiated")) {
filename = TEXT_CAR5.getText();
ctr = 11;
}
eraseTableCar();
try {
File file = new File(filename);
FileReader fr = new FileReader(file.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
for (int i = 0; i < ctr; i++) {
dataCar[i] = br.readLine();
String[] temp;
temp = dataCar[i].split("\\*");
car_table.setValueAt(temp[0], i, 0);
car_table.setValueAt(temp[1], i, 1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This code works although I don't know if it's a good practice in coding

Categories