Reading in a DAG from a file in Java - java

I am given a text file as follows:
0:1,2,3
1:3
2:
3:2
I'm trying to read in from the file then add it to a singly linked list array. Here is what I have so far. I'm able to print out the first part of the file however struggling to print out the values following the ":".
Here is my code.
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> arrayList = new ArrayList<>();
Scanner sc = new Scanner(new File(args[0]));
while (sc.hasNextLine()) {
arrayList.add(sc.nextLine());
}
SinglyLinkedList singlyLinkedList[] = new SinglyLinkedList[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
String dag = arrayList.get(i);
String[] daglist = dag.split(":");
int listindex = Integer.parseInt(daglist[0]);
System.out.println(listindex + ":");
Thanks in advance
Here is the following code that I've tried.
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> arrayList = new ArrayList<>();
Scanner sc = new Scanner(new File(args[0]));
while (sc.hasNextLine()) {
arrayList.add(sc.nextLine());
}
SinglyLinkedList singlyLinkedList[] = new SinglyLinkedList[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
String dag = arrayList.get(i);
String[] daglist = dag.split(":");
int listindex = Integer.parseInt(daglist[0]);
System.out.println(listindex + ":");
// for (int j = 0; j < arrayList.size(); j++) {
// String[] daglist1 = dag.split(",");
// int listvalues = Integer.parseInt(daglist1[1]);
// System.out.println(listindex + ":" + listvalues + " ");
// }
}
}
This is giving me an infinite loop and not printing out correctly.

Related

Converting lines of text from a file to String Array

I read the information in a .txt file and now I would like to store the lines of information from the text into a String Array or a variable.
The information in the .txt file is as given:
Onesimus, Andrea
BAYV
Twendi, Meghan
RHHS
Threesten, Heidi
MDHS
I want to store BAYV, RHHS, MDHS into a different array from the names.
import java.io.File;
import java.util.Scanner;
class testing2 {
public static void main(String [] args) throws Exception {
File Bayviewcamp = new File ("H:\\Profile\\Desktop\\ICS3U\\Bayviewland Camp\\Studentinfo.txt");
Scanner scanner = new Scanner (Bayviewcamp);
while (scanner.hasNextLine())
System.out.println(scanner.nextLine());
Check whether names matches with the regex "[A-Z]+"
List<String> upperCaseList = new ArrayList<>();
List<String> lowerCaseList = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] names = scanner.nextLine().split(",");
for(String name:names) {
if(name.matches("[A-Z]+")) {
upperCaseList.add(name);
}
else {
lowerCaseList.add(name);
}
}
}
As per your example, some of the names has leading spaces. you may have to trim those spaces before you compare with the regex
for(String name:names) {
if(name.trim().matches("[A-Z]+")) {
upperCaseList.add(name.trim());
}
else {
lowerCaseList.add(name.trim());
}
}
Below code has few restrictions like:
There must be format that you said (name and next line value)
Array size is 100 by default but you can change as you want
By name I mean one line: (Onesimus, Andrea) it's under first index in names array.
private static final int ARRAY_LENGTH = 100;
public static void main(String[] args) throws FileNotFoundException {
boolean isValue = false;
File txt = new File("file.txt");
Scanner scanner = new Scanner(txt);
String[] names = new String[ARRAY_LENGTH];
String[] values = new String[ARRAY_LENGTH];
int lineNumber = 0;
while (scanner.hasNextLine()) {
if (isValue) {
values[lineNumber / 2] = scanner.nextLine();
} else {
names[lineNumber / 2] = scanner.nextLine();
}
isValue = !isValue;
lineNumber++;
}
for (int i = 0; i < ARRAY_LENGTH; i++) {
System.out.println(names[i]);
System.out.println(values[i]);
}
}
Below code return separated names:
private static final int ARRAY_LENGTH = 100;
public static void main(String[] args) throws FileNotFoundException {
boolean isValue = false;
File txt = new File("file.txt");
Scanner scanner = new Scanner(txt);
String[] names = new String[ARRAY_LENGTH];
String[] values = new String[ARRAY_LENGTH];
int namesNumber = 0;
int valuesNumber = 0;
while (scanner.hasNextLine()) {
if (!isValue) {
String tempArrayNames[] = scanner.nextLine().split(",");
values[valuesNumber++] = tempArrayNames[0].trim();
values[valuesNumber++] = tempArrayNames[1].trim();
} else {
names[namesNumber++] = scanner.nextLine();
}
isValue = !isValue;
}
}

Want to read .txt file and load it into a 2D array, and then print it as is

Working on an assignement where I have to read a .txt file and place it into a 2D array as is. Note ts HAS TO BE A 2D ARRAY.
I then have to print it like it is again.
The .txt input looks like this:
WWWSWWWW\n
WWW_WWWW\n
W___WWWW\n
__WWWWWW\n
W______W\n
WWWWWWEW\n
Here's the code I have currently, I have an error that says that it cannot resolve method 'add'. Probably has to do with the array initializer
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
String[][] list = new list[][];
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
System.out.println(list);
}
Then the print output has to be
WWWSWWWW
WWW_WWWW
W___WWWW
__WWWWWW
W______W
WWWWWWEW
Any help? Thanks!
Assuming the reason for using 2D array is that each character is saved in a separate String object.
In case we know absolutely nothing regarding the text file, I would implement like this:
public static void main(String[] args) throws FileNotFoundException {
File textFile = new File("D:/trabalho/maze.txt");
Scanner rowsCounter = new Scanner(textFile));
int rows=0;
while (rowsCounter.hasNextLine()) {
rowsCounter.nextLine();
rows++;
}
String[][] data = new String[rows][];
Scanner reader = new Scanner(textFile);
for (int i = 0; i < rows; i++) {
String line = reader.nextLine();
data[i] = new String[line.length()];
for (int j = 0; j < line.length(); j++) {
data[i][j] = line.substring(j, j+1);
}
}
reader.close();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
}
This implementation can handle unknown number of lines and unknown length of each line.
If you wanna stick with your Array a possible solution would be
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
String[][] list = new String[10][5];
for(int x = x; s.hasNextLine();x++ ){
for(int i = 0; i < 5 ; i++){
list[x][i] = s.nextLine();
}
}
s.close();
System.out.println(list);
}
So you don't even need a 2D array Here because the String Class acts like an char Array in C++.
Another solution would be to use ArrayLists
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
ArrayList<String> list = new ArrayList<String>;
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
System.out.println(list);
}
So now you have a list that grows with your amount of Data and also you can just use add Method.
the line ArrayList<String> means that your arrayList just can store data from class String
Here you go!
public static void main(String[] str){
Scanner s = null;
try {
s = new Scanner(new File("path\\text.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> list = new ArrayList<String>();
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
Iterator<String> itr= list.listIterator();
while(itr.hasNext()){
System.out.println(itr.next().toString());
}
}

Reading a CSV in Java / Jython

Here's a simple problem:
public static double[] stringsToDoubles(String[] inputArr) {
double[] nums = new double[inputArr.length];
for (int i = 0; i < nums.length; i++) {
nums[i] = Double.parseDouble(inputArr[i]);
}
return nums;
}
public static double[][] readPointCloudFile(String filename, int n) {
double[][] points = new double[n][];
String delimiter = ",";
Scanner sc = new Scanner(filename);
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
return points;
}
from jython I import properly, and then call the function as
readPointCloudFile("points.txt", 3)
This gives the error
java.lang.NumberFormatException: java.lang.NumberFormatException: For input string: "points.txt"
You never read from the file. You pass the file name to the Scanner and assume that this string is your csv data, but it is just the filename.
Reading a file can be done as follows when you use Java 8:
import java.nio.file.Files;
import java.nio.file.Paths;
[...]
public static double[][] readPointCloudFile(String filename, int n) {
double[][] points = new double[n][];
String delimiter = ",";
String filecontent = new String(Files.readAllBytes(Paths.get(filename)));
Scanner sc = new Scanner(filecontent);
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
return points;
}
Here's my solution in the spirit of solving your own problems, but I'll give someone else credit because the other solutions are probably better.
public static double[] stringsToDoubles(String[] inputArr){
double[] nums = new double[inputArr.length];
for(int i = 0; i < nums.length; i++){
nums[i] = Double.parseDouble(inputArr[i]);
}
return nums;
}
public static double[][] readPointCloudFile(String filename, int n) throws FileNotFoundException{
double[][] points = new double[n][];
String delimiter = ",";
try{
Scanner sc = new Scanner(new File(filename));
for(int i = 0; i < n; i++){
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
} catch (FileNotFoundException e){
System.err.println(e.getMessage());
} finally {
return points;
}
}

How to store string values in string array?

I wanted to store name values in String a[] = new String[3];
public static void main(String[] args) throws IOException {
BufferedReader bo = new BufferedReader(new InputStreamReader(System.in));
String name = bo.readLine();
String a[] = new String[3];
}
}
I guess this should suffice:
String a[] = new String[3];
for(int i=0; i<a.length;i++) {
String name = bo.readLine();
a[i] = name;
}
If your name represents names separated by space, try this:
String a[] = name.split(" ");
If you're working from the console I think this is the easiest way for a beginner to tackle user input:
import java.util.Scanner;
public class ReadToStringArray {
private static String[] stringArray = new String[3];
// method that reads user input into the String array
private static void readToArray() {
Scanner scanIn = new Scanner(System.in);
// read from the console 3 times
for (int i = 0; i < stringArray.length; i++) {
System.out.print("Enter a string to put at position " + i + " of the array: ");
stringArray[i] = scanIn.nextLine();
}
scanIn.close();
System.out.println();
}
public static void main(String[] args) {
readToArray();
// print out the stringArray contents
for (int i = 0; i < stringArray.length; i++) {
System.out.println("String at position " + i + " of the array: " + stringArray[i]);
}
}
}
This method uses the java's native Scanner class. You can just copy and paste this and it will work.

Reading in information into separate arrays

I've been having some difficulties reading in information from a file into separate arrays. An example of the information in the file is:
14 Barack Obama:United States
17 David Cameron:United Kingdom
27 Vladimir Putin:Russian Federation
19 Angela Merkel:Germany
While I can separate the integers into an array, I am having trouble creating an array for the names and an array for the countries. This is my code thus far:
import java.util.*;
import java.io.*;
public class leadRank {
public static void main(String[] args) throws FileNotFoundException {
int size;
Scanner input = new Scanner(new File("names.txt"));
size = input.nextInt();
int[] rank = new int[size];
for (int i = 0; i < rank.length; i++) {
rank[i] = input.nextInt();
input.nextLine();
}
String[] name = new String[size];
for (int i = 0; i <name.length; i++) {
artist[i] =
I think that I would have to read in the line as a string and use indexOf to find the colon in order to start a new array but I'm unsure as to how to execute that.
I just tried to solve your problem in my ways. It was just for a time pass. Hopes this may helps you.
import java.util.*;
import java.io.*;
public class leadRank {
public static void main(String[] args) throws FileNotFoundException {
int size;
File file = new File("names.txt");
FileReader fr = new FileReader(file);
String s;
LineNumberReader lnr = new LineNumberReader(new FileReader(file));
lnr.skip(Long.MAX_VALUE);
size = lnr.getLineNumber()+1;
lnr.close();
int[] rank = new int[size];
String[] name = new String[size];
String[] country = new String[size];
try {
BufferedReader br = new BufferedReader(fr);
int i=0;
while ((s = br.readLine()) != null) {
String temp = s;
if(temp.contains(":")){
String[] splitres = temp.split(":");
String sub = splitres[0];
rank[i] = Integer.parseInt(sub.substring(0,sub.indexOf(" "))); // Adding rank to array rank[]
name[i] = sub.substring(sub.indexOf(" "), sub.length()-1); // Adding name to array name[]
country[i] = splitres[1]; // Adding the conutries to array country[]
}
i++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This is a bit more efficient because it goes through the file only once.
public static void main(String[] args) throws FileNotFoundException {
// create an array list because the size of the array is still not know
ArrayList<Integer> ranks = new ArrayList<Integer>();
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> countries = new ArrayList<String>();
// read the input file
Scanner input = new Scanner(new File("names.txt"));
// read each line
while (input.hasNext()) {
String wholeLine = input.nextLine();
// get the index of the first space
int spaceIndex = wholeLine.indexOf(" ");
// parse the rank
int rank;
try {
rank = Integer.parseInt(wholeLine.substring(0, spaceIndex));
} catch (NumberFormatException e) {
rank = -1;
}
// parse the name & country
String[] tokens = wholeLine.substring(spaceIndex + 1).split(":");
String name = tokens[0];
String country = tokens[1];
// add to the arrays
ranks.add(rank);
names.add(name);
countries.add(country);
}
// get your name and country arrays if needed
String[] nameArr = names.toArray(new String[]{});
String[] countryArr = countries.toArray(new String[]{});
// the rank array has to be created manually
int[] rankArr = new int[ranks.size()];
for (int i = 0; i < ranks.size(); i++) {
rankArr[i] = ranks.get(i).intValue();
}
}

Categories

Resources