How to insert data from files into objects - java

I need some help, I've got a matrix 4x4 that shows a mountain, in the Mountain.txt there are the heights of mountain zones:
1 1 1 1
1 2 3 1
1 2 2 1
1 1 1 1
And the file Rocks.txt that has a type or rock for each zone:
stone stone stone stone
stone sand sand stone
stone sand sand sand
sand sand sand sand
Public class Mountain {
int height;
String typeRock;
public Mountain (int height, String typeRock) {
this.height = height;
this.typeRock = typeRock;
};
}
How do I read that data from 2 different files and to make objects with it, like
Mountain zone00 = new Mountain(1, stone);
Mountain zone01 = new Mountain(1, stone);
Mountain zone11 = new Mountain(2, sand);
And so on...

Loading a file from a directory could be done like so:
public String loadFile(String path) {
StringBuilder builder = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while((line = br.readLine()) != null) {
builder.append(line + "\n");
}
br.close();
} catch(IOException e ) {
e.printStackTrace();
}
return builder.toString();
}
You could know use this method to load both files into strings:
String mountainData = loadFile("Mountain.txt");
String rockData = loadFile("Rpcks.txt");
You could now split these Strings:
String[] mountainsTokens = mountainData.split("\\s+");
String[] rockTokens = rockData.split("\\s+");
After that you just need to create your mountains. Therefore you go through each element of your matrix (the size seems to be 4 here):
Mountain[][] zones = new Mountain[4][4];
for(int y = 0; y < 4; y++) {
for(int x = 0; x < 4; x++) {
mountains[y][x] = new Mountain(Integer.parseInt(mountainData[x + y * 4]), rockData[x + y * 4]);
}
}
For that you have to convert something one-dimensional into something two dimensional (x+y*4) Furthermore, you have to convert the String into an int using Integer.parseInt(). You might have to surround with try-catch too.
Btw, I would definetivly save the mountains in a two dimensional arry like above. This makes everything much easier (instead of zone00 you write zones[0][0]).
I hoped that helped.

You simply open and read two files at a time.
Btw you have a bit of a problem in that the size of your input is hard coded. Instead of assuming that the data is a 4 x 4 array of input, you should add the rows and columns to the input file and read those first. This allows your program to handle any sized data.
This code has not been tested, caveat emptor.
public Mountain[][] read( String mountains, String rocks ) throws IOException {
Reader br1 = Files.newBufferedReader( new File( mountains ).toPath() );
Reader br2 = Files.newBufferedReader( new File( rocks ).toPath() );
Scanner scan1 = new Scanner( br1 );
Scanner scan2 = new Scanner( br2 );
final int rows = 4; // shouldn't hard code these
final int columns = 4;
Mountain[][] mountainArr = new Mountain[rows][columns];
for( int i = 0; i < rows; i++ ) {
for( int j = 0; j < columns; j++ ) {
int mountainHeight = scan1.nextInt();
String rock = scan2.next();
mountainArr[i][j] = new Mountain( mountainHeight, rock );
}
}
scan1.close();
scan2.close();
return mountainArr;
}
public static class Mountain {
public Mountain( int height, String rockType ) {
}
}

Related

Is it possible to write a text file in such a way that when read by the Java compiler, it will add a line break at certain points?

For my Java class, I'm working on a project that is essentially a database for MTG cards. I have to read from a file as part of the project, so I am reading the card information from a file, and then splitting the lines to put each different type of information together to form different object classes for the different types of cards. The main nitpicky issue I'm running into right now is that I need the card text to be on one line in the text file so I can read it line by line, but I'd prefer if it weren't all on one line when I print it to the console. Is there any way to add a character combination into the text of the file itself that will tell my compiler, "line break here," when it reads that, or am I out of luck? I know I could just use \n in the code to achieve this, but as I am looping through the file, there is no way to do so properly that I know of, as not every card's text needs line breaks inserted. If it matters, this is the chunk of my code that deals with that:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class MTG {
public static void main(String[] args) {
int creatureLength = 4;
//Prompt User
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Magic: the Gathering card database. This tool currently supports Rare and Mythic Rare cards from the Throne of Eldraine Expansion.");
try {
System.out.println("\nSelect the card type you'd like to view.");
System.out.println(""
+ "(1)Creatures\n"
);
int choice = Integer.parseInt(sc.next());
//Choose type
//Creatures
if(choice == 1){
Creature[] creatures = creatureGen("textfiles/Creatures.txt", creatureLength);
System.out.println("\nViewing creatures. Which card would you like to view?: \n");
for(int k = 0; k < creatureLength; k++) {
System.out.println(
"(" + (k + 1) + ") " + creatures[k].getName());
}
int creatureChoice = Integer.parseInt(sc.next());
try {
System.out.println("\n" + creatures[(creatureChoice - 1)]);}
catch(Exception e) {
System.out.println("Input was not a specified number. Exiting...");
}
}
}
catch(NumberFormatException ex){
System.out.println("Input was not a specified number. Exiting...");
}
sc.close();
}
//Read Creature text file
public static Creature[] creatureGen(String path, int length) {
Creature[] creatures = new Creature[length];
try {
FileReader file = new FileReader(path);
BufferedReader reader = new BufferedReader(file);
String name[] = new String[length];
String cost[] = new String[length];
String color[] = new String[length];
String type[] = new String[length];
String cTypes[] = new String[length];
String tags[] = new String[length];
String text[] = new String[length];
int power[] = new int[length];
int toughness[] = new int[length];
for (int i = 0; i < length; i++) {
String line = reader.readLine();
if(line != null) {
name[i] = line.split("\\|")[0];
cost[i] = line.split("\\|")[1];
color[i] = line.split("\\|")[2];
type[i] = line.split("\\|")[3];
cTypes[i] = line.split("\\|")[4];
tags[i] = line.split("\\|")[5];
text[i] = line.split("\\|")[6];
power[i] = Integer.parseInt(line.split("\\|")[7]);
toughness[i] = Integer.parseInt(line.split("\\|")[8]);
creatures[i] = new Creature(name[i], cost[i], color[i], type[i], cTypes[i], tags[i], text[i], power[i], toughness[i]);
}
}
reader.close();
}
catch (Exception e) {
System.out.println("Error reading file: " + path);
}
return creatures;
}
}
The Creature object class essentially just stores the data that I am putting into it with the creatureGen method. A sample line from the text file I am reading from looks something like this:
Charming Prince|1W|White|Creature|Human Noble||When Charming Prince enters the battlefield, choose one — • Scry 2. • You gain 3 life. • Exile another target creature you own. Return it to the battlefield under your control at the beginning of the next end step.|2|2
It would be ideal to be able to insert line breaks after each of the bullet points in this card, for example, but as I said earlier, I need the text to be in one line for my loop to read it. Is there any way around this when I print this back to the console? I appreciate any help.
Just replace those bullet points with line breaks :
text[i] = line.split("\\|")[6].replaceAll("•","\n");
Also, you should not split each time you need an element, put the result of line.split("\|") in a String[] variable and use it afterwards.
for (int i = 0; i < length; i++) {
String line = reader.readLine();
if(line != null) {
String[] elements = line.split("\\|");
name[i] = elements[0];
cost[i] = elements[1];
color[i] = elements[2];
type[i] = elements3];
cTypes[i] = elements[4];
tags[i] = elements[5];
text[i] = elements[6].replaceAll("•","\n");
power[i] = Integer.parseInt(elements[7]);
toughness[i] = Integer.parseInt(elements[8]);
creatures[i] = new Creature(name[i], cost[i], color[i], type[i], cTypes[i], tags[i], text[i], power[i], toughness[i]);
}
}
Finally, about vocabulary, the compiler is not reading your file. The compiler translates your code into binary instructions for the processor (to summarize).
Your file is read at runtime.

Reading two matrices from the same file in java

Hello guys and thank you in advance for your help!
I am trying to do a matrice calculator in java
that reads two matrices from the same file like this:
2 2
34 78
89 -12
#
2 2
67 76
123 5
first line is the rank
second and third line are the first matrix
the "#" splits the first and the second matrix
and that's the code I came up with and I didn't
find anything similar to this problem... can someone help me please?
String [] line = new String[30];
int counter = 2;
int rank[] = new int[2];
int matrixa[][] = new int [3][3];
try {
BufferedReader MyReader = new BufferedReader(new FileReader("matrix.txt"));
while(line != null) {
line = MyReader.readLine().split(" ");
}
rank[0] = Integer.parseInt(line[0]);
rank[1] = Integer.parseInt(line[1]);
for(int i = 0; i <rank[0];i++) {
for (int j=0;j<rank[1];j++) {
matrixa[i][j] = Integer.parseInt(line[counter]);
counter++;
System.out.print(matrixa[i][j] + " ");
}
System.out.println();
} }catch (Exception e) {}
Leaving a ticker variable at when your lines is equal to "#"
int ticker;
for(int i = 0; i < lines.length; i++){
if(lines[i].equals("#")) ticker = i;
}
This ticker then can be used to break the array. This could also be used earlier to break up the array into 2 separate arrays if that is expected.
String currentLine;
String[] line = new String[15];
String[] line2 = new String[15];
int i = 0;
while(line != null && !currentLine.equals("#")){
line = MyReader.readLine().split("");
currentLine = line[i];
if(currentLine.equals("#")) line[i] = null;
i++;
}
while(line2 != null)){
line2 = MyReader.readLine().split("");
}
They can be parsed into matrices and then math can be done on them from there.
Best of luck with your endeavors.

Homework: How to sort an Array List of String coming from a file

I need to Write a program that reads in the following information from a file. The columns are: Time in 1/100 second ticks, Note Number, Velocity, Length. And each line is a different note I need to Write a program that reads them in, and then prints them out again. I want to have one public class for Note, and an array of them.
0 60 100 24
25 72 100 24
100 60 100 24
50 60 100 24
75 72 100 24
This is my new Note class
public class Note implements Comparable {
private int time;
private int noteNumber;
private int velocity;
private int length;
public Note (int time, int noteNumber, int velocity, int length){
this.time = time;
this.noteNumber = noteNumber;
this.velocity = velocity;
this.length = length;
}
public String toString (){
return String.format("(%s, %d, %d, %d)", time, noteNumber, velocity, length);
}
#Override
public int compareTo(Note note) {
return this.time - note.time;
}
}
This is the class that I am using to read lines from the file. I am able to store correctly only the first line, but now I am having issues trying to store the other lines.
public class MelodyCatcher{
public static Note[] n = new Note[5];
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader ("/Users/enricomomo/Desktop/Text/file1.txt");
BufferedReader br = new BufferedReader (fr); //Info stored into a buffer
String ln = null;
while ((ln = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(ln);
while(st.hasMoreTokens()) // read each number in this line
{
n[0] = new Note(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
n[1] = new Note(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
n[2] = new Note(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
n[3] = new Note(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
n[4] = new Note(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
}
System.out.println("The notes are " + Arrays.toString(n));
Arrays.sort(n);
System.out.println("The notes stored are " + Arrays.toString(n));
}
br.close();
fr.close();
}
}
So, if your lines look like as in example, you can simple split line to Note object as below:
String[] noteParams = ln.split(" ");
Note n = new Note(noteParams[0], noteParams[1], noteParams[2], noteParams[3]);
I can change your code as below to read every line and fill Note array:
String ln = null;
while ((ln = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(ln);
while(st.hasMoreTokens()) // read each number in this line
{
n[0] = new Note(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
n[1] = new Note(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
n[2] = new Note(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
n[3] = new Note(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
n[4] = new Note(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
}
System.out.println("The notes are " + Arrays.toString(n));
Arrays.sort(n);
System.out.println("The notes stored are " + Arrays.toString(n));
}
br.close();
fr.close();

How to determine how big is the treasure map (rows and columns) from a textfile?

I'd like to know how to figure out the rows and columns of a passed textfile.
Suppose the textfile looks like this:
X...................
....................
....................
....................
....................
....................
....................
....................
....................
..X.................
This textfile has 10 rows and 20 columns and I'm facing troubles with how to get those rows and columns for my constructor (DONT WORRY ABOUT "X" symbols). I just would like to know how to get rows and columns from the textfile/ would like to know how to figure out how big the map is.
I need help with the second constructor in the code:
import java.util.Scanner; // Required to get input
import java.io.File; // Required to get input from files
// A 2D treasure map which stores locations of treasures in an array
// of coordinates
public class TreasureMap{
int rows, cols; // How big is the treasure map
Coord [] treasureLocations; // The locations of treasures
Scanner kbd = new Scanner(System.in);
// Prompt the user for info on the treasure map and then create it
public TreasureMap(){
int numberOfTreasures = 0;
System.out.println("Enter map size (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
System.out.println("Enter number of treasures (1 int): ");
numberOfTreasures = kbd.nextInt();
treasureLocations = new Coord[numberOfTreasures];
for (int i = 0; i < numberOfTreasures; i++)
{
System.out.println("Enter treasure " + i + " location (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
treasureLocations[i] = new Coord(rows, cols);
}
}
// Read the string representation of a map from a file
public TreasureMap(String fileName) throws Exception{
Scanner data = new Scanner(new File(fileName));
int counter = 0;
while(data.hasNextLine())
{
counter++;
}
}
// true if there is treasure at the given (r,c) coordinates, false
// otherwise
// This method does not require modification
public boolean treasureAt(int r, int c){
for(int i=0; i<treasureLocations.length; i++){
Coord coord = treasureLocations[i];
if(coord.row == r && coord.col == c){
return true;
}
}
return false;
}
// Create a string representation of the treasure map
public String toString(){
String [][] map = new String[this.rows][this.cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
map[i][j] = ".";
}
}
for(int i=0; i<treasureLocations.length; i++){
Coord c = treasureLocations[i];
map[c.row][c.col] = "X";
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
sb.append(map[i][j]);
}
sb.append("\n");
}
return sb.toString();
}
}
Here's some code you can use to read lines from a file:
File file = new File(fileName);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
int rows = 0;
int cols = 0;
while ((line = br.readLine()) != null) {
// process the line
rows++;
cols = line.length(); // always the size of the last line in the file
}
}
br.close();
Based on your implementation, this would give you width and height of your input file.
public TreasureMap(String fileName) throws Exception{
Scanner data = new Scanner(new File(fileName));
int width = 0;
int height = 0;
while(data.hasNextLine())
{
String line = data.nextLine();
width = Math.max(width, line.length());
height++;
}
System.out.println(width + " x " + height);
}

How do I read each column of a txt file, and place them in separate arrays?

I'm doing a Programming Assignment and basically I need to read from a txt file and sort everything in there in different arrays allowing me to display everything in the cmd prompt neatly and be able to delete stuff.
h Vito 123
d Michael 234 Heart
s Vincent 345 Brain Y
n Sonny 456 6
a Luca 567 Business
r Tom 678 Talking Y
j Anthony 789 Maintenance N
d Nicos 891 Bone
n Vicky 911 7
First column needs to be the employeeRole (employee, doctor). The second column being the employeeName. Third column being the employeeNumber and some of them have have a fourth column (if it's a number it's number of patients. Y is for like sweeping, or answering calls)
So my thought process was put each column into it's own array and then writing it out that way. I was able to put each row into its own array with
public class ReadingFile {
// String test;
// char[] employeeRole = new char[9];
String[] employeeRole = new String[9];
String[] employeeName = new String[9], specialty;
String[] wholeLine = new String[9];
// String word;
int[] employeeNum = new int[9];
int r, n, l, num;
public void Reader()
{
Scanner inputStream = null;
Scanner inputStream2 = null;
Scanner inputStream4 = null;
try
{
BufferedReader inputStream3 =
new BufferedReader(new FileReader("data.txt"));
inputStream = new Scanner(new FileInputStream("data.txt"));
inputStream =
new Scanner(new FileInputStream("data.txt"));
inputStream2 =
new Scanner(new FileInputStream("data.txt"));
inputStream4 =
new Scanner(new FileInputStream("data.txt"));
System.out.println("Yeah");
}
catch(FileNotFoundException e){
System.out.println("File Not found");
System.exit(1);
}
for (l=0; l<9; l++)
{
wholeLine[l] = inputStream2.nextLine();
System.out.println(wholeLine[l]);
}
But I couldn't figure out what to do from there. Doing a split would then put an array into an array? Which means I would put each line into an array and then each word into an array?
So I tried something else, anything with the length not equal to 1 would be the employeeNum, but then they there were the N's and Y's and the number of pateints.
for(r=0; r<9; r++) //role
{
String next = inputStream4.next();
while( next.length() != 1)
{
next = inputStream4.next();
}
employeeRole[r] = next;
System.out.println(employeeRole[r]);
}
I also tried
for (r=0; r<9; r++)
{
employeeRole[r] = wholeLine[r].substring(wholeLine[r].indexOf(1));
//inputStream.nextLine();
System.out.println(employeeRole[r]);
}
I'm just not sure if I'm going the right way about it? If I'm making it more difficult than it really is? Or if there's an easier way to do this. But after everything is done, the output should be able to basically say
Doctors: 2
Name: Michael Employee Number: 234 Specialty: Heart
Name: Nicos Employee Number: 891 Specialty: Bone
Any help would be greatly appreciated, thanks!
You don't have to open 4 streams in order to read the file (I guess you wanted to open "one per column" but you shouldn't do it).
Second, you can split the string on spaces (" ") which will provide you the columns (for every line separately) exactly like you want.
Code example:
BufferedReader br = null;
String[] characters = new String[1024];//just an example - you have to initialize it to be big enough to hold all the lines!
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("data.txt"));
int i=0;
while ((sCurrentLine = br.readLine()) != null) {
String[] arr = sCurrentLine.split(" ");
//for the first line it'll print
System.out.println("arr[0] = " + arr[0]); // h
System.out.println("arr[1] = " + arr[1]); // Vito
System.out.println("arr[2] = " + arr[2]); // 123
if(arr.length == 4){
System.out.println("arr[3] = " + arr[3]);
}
//Now if you want to enter them into separate arrays
characters[i] = arr[0];
// and you can do the same with
// names[1] = arr[1]
//etc
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

Categories