Constructing an object using a given file - java

I'm trying to use a constructor to create an object from a file, the file should contain (on the first line) an Int in String format which is meant to be the number of rows for the MD Array and then has a space followed by another Int in String format. I'm trying to "grab" these two Strings, parse them into an int and then instantiate the MD Array by using these two ints I've "grabbed." I'm just not quite sure where I'm going wrong, as I've just begun using File I/O in my coding. Here's my code.
public SeatingChart(File file) throws FileNotFoundException, DataFormatException, IOException
{
Scanner scan = new Scanner(file);
int rows = 0;
int columns = 0;
String rowStr = "";
String colStr = "";
if (scan.hasNext())
{
rowStr = scan.next();
colStr = scan.next();
}
rows = Integer.parseInt(rowStr);
columns = Integer.parseInt(colStr);
seats = new Student[rows][columns];
scan.close();
}
Any help would be much appreciated :)

From your question, You want to grab two numbers, in string format, separated by a space.
I would grab the entire line then trim the string which ensures there is no space before or after the numbers I need. Then split them based on space.
Look at this simplified step by step example. This example will create a file called numbers.txt then put in it string "5 2". Then the file will be read and taken apart to get the numbers.
import java.util.*;
import java.io.*;
import java.nio.*;
PrintWriter fileWriter = new PrintWriter("numbers.txt", "UTF-8");
fileWriter.println("5 2");
fileWriter.close();
File file = new File("numbers.txt");
Scanner input = new Scanner(file);
String numbersString;
if (input.hasNextLine()) numbersString = input.nextLine();
// Trim the string to ensure you have what you need.
numbersString = numbersString.trim();
// Split both numbers according to the space within them.
String[] numsArray = numbersString.split("\\s+");
// Get your numbers.
int row = Integer.valueOf(numsArray[0]);
int col = Integer.valueOf(numsArray[1]);

Related

How can I remove specific elements from a linkedlist in java based on user input?

I'm very new (6 weeks into java) trying to remove elements from a csv file that lists a set of students as such (id, name, grades) each on a new line.
Each student id is numbered in ascending value. I want to try and remove a student by entering the id number and I'm not sure how I can do this.
So far I've just tried to reduce the value that user inputs to match the index as students are listed by number and I did this in a while loop. However, each iteration doesn't recognize the reduction from the previous user Input, and I think I need a way that can just search the value of the id, and remove the entire line from the csv file.
Have only tried to include the pertinent code. Reading previous stack questions has shown me a bunch of answers related to nodes, which make no sense to me since I don't have whatever prerequisite knowledge is required to understand it, and I'm not sure the rest of my code is valid for those methods.
Any ideas that are relatively simple?
Student.txt (each on a new line)
1,Frank,West,98,95,87,78,77,80
2,Dianne,Greene,78,94,88,87,95,92
3,Doug,Lei,78,94,88,87,95,92
etc....
Code:
public static boolean readFile(String filename) {
File file = new File("C:\\Users\\me\\eclipse-workspace\\studentdata.txt");
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
String[] words=scanner.nextLine().split(",");
int id = Integer.parseInt(words[0]);
String firstName = words[1];
String lastName = words[2];
int mathMark1 = Integer.parseInt(words[3]);
int mathMark2 = Integer.parseInt(words[4]);
int mathMark3 = Integer.parseInt(words[5]);
int englishMark1 = Integer.parseInt(words[6]);
int englishMark2 = Integer.parseInt(words[7]);
int englishMark3 = Integer.parseInt(words[8]);
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,englishMark1,englishMark2,englishMark3);
}scanner.close();
}catch (FileNotFoundException e) {
System.out.println("Failed to readfile.");
private static void removeStudent() {
String answer = "Yes";
while(answer.equals("Yes") || answer.equals("yes")) {
System.out.println("Do you wish to delete a student?");
answer = scanner.next();
if (answer.equals("Yes") || answer.equals("yes")) {
System.out.println("Please enter the ID of the student to be removed.");
//tried various things here: taking userInput and passing through linkedlist.remove() but has never worked.
This solution may not be optimal or pretty, but it works. It reads in an input file line by line, writing each line out to a temporary output file. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. It then renames the output file. I have omitted error handling, closing of readers/writers, etc. from the example. I also assume there is no leading or trailing whitespace in the line you are looking for. Change the code around trim() as needed so you can find a match.
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);

Reading multiple data types from a CSV file in Java

So I want to create a constructor that reads in a line of a file from a csv and save the first token into a variable and the remaining tokens into an array. This constructor will be used in a gradebook application but being new to txt/file manipulation I'm having a hard time.
A line will look like:
Billy Bob,68,79,95,83
I want to separate the tokens into these:
name = Billy Bob
grades[] = "68,79,95,83"
here is the code I have so far:
import java.io.*;
public class gradeBook {
public static void main(String[] args){
System.out.println("Java Grade Book version 1.0");
int lineCounter = 0;
String array[];
try{
File data = new File("/file/path/that/works");
InputStream f = new FileInputStream(data);
BufferedReader br = new BufferedReader(new InputStreamReader(f));
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line); // just here to check that the code is working thus far
//insert code here
//name should equal first token (which is two names like Billy Bob)
//grades[] should contain the other double type tokens (e.g. 56,87,89,90)
}
br.close();
}
catch(Exception e){
System.err.println("Error: File Couldn't Be Read");
}
}
}
And I want to loop through the file to get as many students as are on the file stored so I can manipulate the grades for averages among other things. This is a personal project to help improve my developing skills so any help, useful tutorial links, and tips will be greatly appreciated. But please don't suggest simplistic examples like the many tutorials I have already read that only use one data type.
Thanks for any help!
Split the line into an array;
String[] input = line.split(",");
String variable = input[0];
int[] grades= new int[input.lenght - 2];
for(int i = 1; i < input.length; i++)
{
grades[i] = input[i];// you might have to do Integer.pareseInt(input[i]);
}
I did not write this in an IDE, but the logic should be correct.
You are going to run into a new problem. You grade book will only contain the last entry. Try using a 2D array for grades and 1D array for names; I personally would not use arrays. I would use arraylist.
So I haven't tested computing my tokens with methods or anything else yet but I have tokenized the line to sum (ha ha oops, meant some) degree with this bit of code:
String[] tokens = line.split(",");
String name = tokens[0];
String grade1 = tokens[1];
String grade2 = tokens[2];
String grade3 = tokens[3];
String grade4 = tokens[4];

String.contains registering as !String.contains

I'm trying to append any lines in a text file which contain a given set of strings. I created a test file, in which I put one of those strings. My code is supposed to print any line in the text file containing one of these strings on the same line as the previous line in the text file. Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class AppendIfFromFileScanner {
public static void main(String args[]) {
File file = new File("C:\\Users\\frencke\\workspace\\Testing Stuff\\Append Tetsing\\file3.txt");
ArrayList<String> lines = new ArrayList<String>();
String delima = "\\s+\\s+\\s+\\s+\\s+&\\s+";
String delimb = "\\s+\\s+\\s+\\s+\\s+\\+\\s+";
String delimc = "\\s+\\s+\\s+\\s+\\s+z\\s+";
String delimd = "\\s+\\s+\\s+\\s+\\s+1\\s+";
String delime = "\\s+\\s+\\s+\\s+\\s+2\\s+";
String delimf = "\\s+\\s+\\s+\\s+\\s+3\\s+";
String delimg = "\\s+\\s+\\s+\\s+\\s+4\\s+";
String delimh = "\\s+\\s+\\s+\\s+\\s+5\\s+";
String delimi = "\\s+\\s+\\s+\\s+\\s+6\\s+";
String delimj = "\\s+\\s+\\s+\\s+\\s+7\\s+";
String delimk = "\\s+\\s+\\s+\\s+\\s+8\\s+";
String deliml = "\\s+\\s+\\s+\\s+\\s+9\\s+";
String delimm = "\\s+\\s+\\s+\\s+\\s+a\\s+";
String delimn = "\\s+\\s+\\s+\\s+\\s+b\\s+";
String delimo = "\\s+\\s+\\s+\\s+\\s+c\\s+";
String delimp = "\\s+\\s+\\s+\\s+\\s+d\\s+";
String delimq = "\\s+\\s+\\s+\\s+\\s+e\\s+";
String delimr = "\\s+\\s+\\s+\\s+\\s+f\\s+";
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());}
for(int i=0; i<lines.size(); i++){
for(String s=null; i<lines.size(); i++){
s = lines.get(i);
if(!s.contains(delima)||
!s.contains(delimb)||
!s.contains(delimc)||
!s.contains(delimd)||
!s.contains(delime)||
!s.contains(delimf)||
!s.contains(delimg)||
!s.contains(delimh)||
!s.contains(delimi)||
!s.contains(delimj)||
!s.contains(delimk)||
!s.contains(deliml)||
!s.contains(delimm)||
!s.contains(delimn)||
!s.contains(delimo)||
!s.contains(delimp)||
!s.contains(delimq)||
!s.contains(delimr))
System.out.print("\r\n" + s);
else if(s.contains(delima)||
s.contains(delimb)||
s.contains(delimc)||
s.contains(delimd)||
s.contains(delime)||
s.contains(delimf)||
s.contains(delimg)||
s.contains(delimh)||
s.contains(delimi)||
s.contains(delimj)||
s.contains(delimk)||
s.contains(deliml)||
s.contains(delimm)||
s.contains(delimn)||
s.contains(delimo)||
s.contains(delimp)||
s.contains(delimq)||
s.contains(delimr))
System.out.print(s);}
}
}catch (FileNotFoundException e) {
System.out.println("Cannot find file.");
}
}
}
The contents of my text file are:
first line
text & append this line
So basically, I know that my text file has one of these strings (in this case, delima) in it. Yet, my output is:
first line
text & append this line
Which is not supposed to happen. The output I want is:
first line text & append this line
Does anyone know why it's interpreting the second line of my text file as though it does not contain delima, even though it clearly does? Any help would be appreciated. I'm fairly sure that the problem is something to do with my if statement, but I'm obviously not the expert here.
The String.contains() method matches an exact string, not a regular expression.
Instead, you may wish to try using String.matches(). You may need to adjust your pattern to obtain similar behaviour to contains() (see this page for some examples).

Reading txt file into array using scanner

I have a text file that looks roughly like this:
type, distance, length, other,
A, 62, 17, abc,
A, 12, 4,,
A, 6, 90,,
A, 46, 53,,
etc.
Everything is separated by commas, but sometimes there is a blank. I need to be able to read this data into an array using a scanner (not bufferedreader) and be able to account for the blanks somehow, as well as split by commas. Later I will need to be able to calculate things with the data in each column. How do I get this data into the array?
This is what I have so far: (java)
import java.util.Scanner;
import java.io.*;
public class RunnerAnalysis {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("File: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.nextLine();
String line = inputFile.nextLine();
while(inputFile.hasNext())
{
String[] array = line.split(",");
}
}
}
If you really want to use a Scanner, which is IMHO not such a good idea, you can set the delimiter to ,.
Scanner inputFile = new Scanner(...);
inputFile.useDelimiter(",");
while (inputFile.hasNext())
{
String type = inputFile.next();
int distance = inputFile.nextInt();
int length = inputFile.nextInt();
String other = inputFile.next();
// Process...
}
I prefer using a BufferedReader in combination with String.split(",").

file input from the user

I was trying to take the input of the filename from the user and then proceed to doing all the calculations. but it keeps returning me an error. the file exists in the same directory.
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
//File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(System.in);
scanner.nextLine(); // removes the first line in the input file
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
String colLine = scanner.nextLine();
String[] arr2 = colLine.split("=");
int cols = Integer.parseInt(arr2[1].trim());
double [][]matrix = new double [rows][cols];
for (int i=0; i<rows;i++){
for (int j=0; j<cols;j++) {
matrix[i][j]= scanner.nextDouble();
}
}
System.out.println(rows);
System.out.println(cols);
for (int i=0; i<rows; i++)
{ for (int j=0;j<cols;j++) {
System.out.println(matrix[i][j]);
}
}
}
}
There is one issue with the code. The scanner will just give you the name of the file as string from command line. So, you need to first get the command line argument and then create one more scanner using the constructor which takes file object. e.g.
Scanner scanner = new Scanner(System.in);
Scanner fileScanner = new Scanner(new File(scanner.nextLine()));
String rowLine = fileScanner.nextLine();
System.out.println(rowLine);
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim())
You realize that you are only using a Scanner of type System.in, right? This means that you aren't even looking at a file, you are looking at user input only. This is regardless of whether you have the first line commented out or not. To use a file, you could use a FileInputStream or a couple other File handling classes.
FileInputStream fs = new FileInputStream(new File("matrix1.txt"));
//do stuff with the stream
Heres the java docs for FileInputStream: http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html
Edit: After seeing your comment on what the actual error was, I realize there are more problems with the code than just the way you are handling input. Your error is almost certainly happening at one of the first 2 array accessors, the arr1.trim() calls. That means the user input has nothing on the right side of the "=" sign, or there is no "=" sign in the user input.

Categories

Resources