For homework, we have to read in a txt file which contains a map. With the map we are supposed to read in its contents and place them into a two dimensional array.
I've managed to read the file into a one dimensional String ArrayList, but the problem I am having is with converting that into a two dimensional char array.
This is what I have so far in the constructor:
try{
Scanner file=new Scanner (new File(filename));
while(file.hasNextLine()){
ArrayList<String> lines= new ArrayList<String>();
String line= file.nextLine();
lines.add(line);
map=new char[lines.size()][];
}
}
catch (IOException e){
System.out.println("IOException");
}
When I print out the lines.size() it prints out 1 but when I look at the file it has 10.
Thanks in advance.
You have to create the list outside the loop. With your actual implementation, you create a new list for each new line, so it will always have size 1.
// ...
Scanner file = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>(); // <- declare lines as List
while(file.hasNextLine()) {
// ...
BTW - I wouldn't name the char[][] variable map. A Map is a totally different data structure. This is an array, and if you create in inside the loop, then you may encounter the same problems like you have with the list. But now you should know a quick fix ;)
Change the code as following:
public static void main(String[] args) {
char[][] map = null;
try {
Scanner file = new Scanner(new File("textfile.txt"));
ArrayList<String> lines = new ArrayList<String>();
while (file.hasNextLine()) {
String line = file.nextLine();
lines.add(line);
}
map = new char[lines.size()][];
} catch (IOException e) {
System.out.println("IOException");
}
System.out.println(map.length);
}
Related
Now I am trying to read txt files and make an array in arraylist with that data.
I want to read two txt files and compare them, but I can't understand why the inside while loop is not working.
(I used 'count' variable to test inside while loop, but when I printed count variable, it printed only 0.)
(Also I know that try~ catch~ is not good solution for
NullPointerException error.. but I couldn't find other solution instead of try~ catch~)
import java.io.*;
import java.util.*;
public class Warehouse {
static private String[] eachStockElem = new String[5];
static private String[] eachInputElem = new String[5];
public static void main(String[] args) throws Exception {
Scanner str = new Scanner(new File("a.txt"));
Scanner ip = new Scanner(new File("b.txt"));
PrintStream st_w = new PrintStream("a.txt");
PrintStream tx = new PrintStream("c.txt");
ArrayList<String[]> stockArrayList = new ArrayList<>();
ArrayList<String[]> inputArrayList = new ArrayList<>();
ArrayList<String[]> txArrayList = new ArrayList<>();
String eachTxElem[] = new String[6];
int tx_id=0;
int temp_quantity=0;
int count=0;
try {
while (ip.hasNextLine()) {
eachInputElem = ip.nextLine().split(",");
inputArrayList.add(eachInputElem);
while (str.hasNextLine()) { //this while not working!
eachStockElem = str.nextLine().split(",");
stockArrayList.add(eachStockElem);
count++;
//do comparing operation
break;
}
}
}
catch(NullPointerException e){
System.out.print("");
}
System.out.println(count);
str.close();
ip.close();
tx.close();
}
}
By guessing what "this loop does not work" words mean, i am taking the risk to post of what i think is the problem in your case.
PrintStream in documents:
The name of the file to use as the destination of this print stream.
If the file exists, then it will be truncated to zero size; otherwise,
a new file will be created. The output will be written to the file and
is buffered.
The problem (and the answer, "why it is not working"):
Scanner str = new Scanner(new File("a.txt"));
PrintStream st_w = new PrintStream("a.txt"); //Cleans the text file,
// so scanner has no lines to read.
At this line,
PrintStream st_w = new PrintStream("a.txt");
the program is writing the output in the same input file. Change the name of this output file and execute your test case.
I already read data from a text file (in the file there are all numbers (int and double)) and in my class, I have an array of an object type. I have no idea how to put data which read from the txt file into the array.
I would greatly appreciate it if you can give me some answers.
this.object=new Object[nums1];
File file=new File("/homes/xx.txt");
try {
Scanner scnr=new Scanner(file);
int lineNumber= 1;
while (scnr.hasNextLine()) {
String line = scnr.nextLine();
System.out.println(line);
}
}
catch (FileNotFoundException e) {
System.out.println(e);
}
A couple of sample lines from my input file:
3
1.0 2.5 3.0
I think I need to distinguish between whole numbers and numbers with a decimal point. Should I create another object type so I can store int and double separately?
try this:
File file=new File("/homes/xx.txt");
try {
Scanner scnr=new Scanner(file);
List<String> lines = new ArrayList<String>();
while (scnr.hasNextLine()) {
lines.add(scnr.nextLine());
System.out.println(lines);
}
String[] arr = lines.toArray(new String[0]);
}
catch (FileNotFoundException e) {
System.out.println(e);
If you have a space between your integers and doubles, try this:
Object []objects = file;
Object []numbers = objects.split(“ “);
I am not sure about Object []objects = file; part because I am new java learner too. But if you can insert whole text to an array, you can split and assign values one by one with .split command to another array.
As part of a project I'm working on, I'd like to clean up a file I generate of duplicate line entries. These duplicates often won't occur near each other, however. I came up with a method of doing so in Java (which basically find a duplicates in the file, I stored two strings in two arrayLists and iterating but it was not working because of nested for loops i am getting into the condition manyways.
I need an integrated solution for this, however. Preferably in Java. Any ideas?
List item
public class duplicates {
static BufferedReader reader = null;
static BufferedWriter writer = null;
static String currentLine;
public static void main(String[] args) throws IOException {
int count=0,linecount=0;;
String fe = null,fie = null,pe=null;
File file = new File("E:\\Book.txt");
ArrayList<String> list1=new ArrayList<String>();
ArrayList<String> list2=new ArrayList<String>();
reader = new BufferedReader(new FileReader(file));
while((currentLine = reader.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(currentLine,"/"); //splits data into strings
while (st.hasMoreElements()) {
count++;
fe=(String) st.nextElement();
//System.out.print(fe+"/// ");
//System.out.println("count="+count);
if(count==1){ //stores 1st string
pe=fe;
// System.out.println("first element "+fe);
}
else if(count==5){
fie=fe; //stores 5th string
// System.out.println("fifth element "+fie);
}
}
count=0;
if(linecount>0){
for(String s1:list1)
{
for(String s2:list2){
if(pe.equals(s1)&&fie.equals(s2)){ //checking condition
System.out.println("duplicate found");
//System.out.println(s1+ " "+s2);
}
}
}
}
list1.add(pe);
list2.add(fie);
linecount++;
}
}
}
i/p:
/book1/_cwc/B737/customer/Special_Reports/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/book1/_cwc/B737/customer/Special_Reports/
/jangeer/_cwc/Crj_200/customer/plots/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/
/jangeer/_cwc/Crj_200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/01_Highlights/
/jangeer/_cwc/ERJ170/customer/01_Highlights/
o/p:
/book1/_cwc/B737/customer/Special_Reports/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/plots/
/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/
/jangeer/_cwc/Crj_200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/01_Highlights/
Use a Set<String> instead of Arraylist<String>.
Duplicates aren't allowed in a Set, so if you just add everyline to it, then get them back out, you'll have all distinct strings.
Performance-wise it's also quicker than your nested for-loop.
public static void removeDups() {
String[] input = new String[] { //Lets say you read whole file in this string array
"/book1/_cwc/B737/customer/Special_Reports/",
"/Airbook/_cwc/A330-200/customer/02_Watchlists/",
"/book1/_cwc/B737/customer/Special_Reports/",
"/jangeer/_cwc/Crj_200/customer/plots/",
"/Airbook/_cwc/A330-200/customer/02_Watchlists/",
"/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/",
"/jangeer/_cwc/Crj_200/customer/02_Watchlists/",
"/jangeer/_cwc/Crj_200/customer/01_Highlights/",
"/jangeer/_cwc/ERJ170/customer/01_Highlights/"
};
ArrayList<String> outPut = new ArrayList<>(); //The array list for storing output i.e. distincts.
Arrays.stream(input).distinct().forEach(x -> outPut.add(x)); //using java 8 and stream you get distinct from input
outPut.forEach(System.out::println); //I will write back to the file, just for example I am printing out everything but you can write back the output to file using your own implementation.
}
The output when I ran this method was
/book1/_cwc/B737/customer/Special_Reports/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/plots/
/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/
/jangeer/_cwc/Crj_200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/01_Highlights/
/jangeer/_cwc/ERJ170/customer/01_Highlights/
EDIT
Non Java 8 answer
public static void removeDups() {
String[] input = new String[] {
"/book1/_cwc/B737/customer/Special_Reports/",
"/Airbook/_cwc/A330-200/customer/02_Watchlists/",
"/book1/_cwc/B737/customer/Special_Reports/",
"/jangeer/_cwc/Crj_200/customer/plots/",
"/Airbook/_cwc/A330-200/customer/02_Watchlists/",
"/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/",
"/jangeer/_cwc/Crj_200/customer/02_Watchlists/",
"/jangeer/_cwc/Crj_200/customer/01_Highlights/",
"/jangeer/_cwc/ERJ170/customer/01_Highlights/"
};
LinkedHashSet<String> output = new LinkedHashSet<String>(Arrays.asList(input)); //output is your set of unique strings in preserved order
}
I'm supposed to be coding an app that can read names from a hardcoded text file, save them as a string array, then write those names in a different text file but sorted. I believe I have the first two parts down but I'm confused on how to sort the names then write them into a new file.
These is the actual problem I'm working on:
"Take an input file with 10 names in it (hard coded). Write a program to read the file, save the names in a String array and write into a different file names in sorted order. Use Methods appropriately."
BTW I'm a rookie coder, this is what I have so far.
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
readFile();
saveStringArray();
}
public static void readFile() {
File file = new File("/Users/nicoladaaboul/Desktop/Programming/C++, "
+ "HTML5, Java, PHP/Java/Question2/names.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String i = sc.next();
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void saveStringArray() throws FileNotFoundException {
String token1 = "";
Scanner inFile1 = new Scanner(new File("names.txt")).useDelimiter(",\\s*");
List<String> temps = new ArrayList<String>();
while (inFile1.hasNext()) {
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
Arrays.sort(tempsArray);
for (String s : tempsArray) {
System.out.println(s);
}
}
public static void sortingNames() {
}
public static void writingFile() throws FileNotFoundException {
PrintWriter writer = new PrintWriter("sortedNames.txt");
writer.close();
}
Its important that you break your problem down into instructions.
1. You need to read the file you can use bufferedReader(code below).
2. Create an array(or arraylist) to store your string values.
3. Then as you read each line, store these values in the array.
4. When finished reading the file you then would pass this array to a function that would sort it(Why does my sorting loop seem to append an element where it shouldn't?).
5. Once sorted you simply write this array, to a file.
BufferedReader br = new BufferReader(new FileReader("name.txt"));
int count = 0;
String line;
String[] names = new String[100];
while((line = br.nextLine()) != null){
names[count] = line;
count++;
}
So far, I have 2 arrays: one with stock codes and one with a list of file names. What I want to do is input the .txt files from each of the file names from the second array and then split this input into: 1. Arrays for each file 2. Arrays for each part with each file.
I have this:
ImportFiles f1 = new ImportFiles("File");
for (String file : FileArray.filearray) {
if (debug) {
System.out.println(file);
}
try {
String line;
String fileext = "C:\\ASCIIpdbSKJ\\"+file+".txt";
importstart = new BufferedReader(new FileReader(fileext));
for (line = importstart.readLine(); line != null; line = importstart.readLine()) {
importarray.add (line);
if (debug){
System.out.println(importarray.size());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
importarray.add ("End")
This approach works to create a large array of all the files, will it be easier to change the input method to split it as it is coming in or split the large array I have?
At this point, the stock code array is irrelevant. Once I have split the arrays down I know where I will go from there.
Thanks.
Edit: I am aware that this code is incomplete in terms of { } but it is only printstreams and debugging missed off.
If you want to get a map with a filename and all its lines from all the files, here are relevant code parts:
Map<String, List<String>> fileLines = new HashMap<String, List<String>>();
for (String file : FileArray.filearray)
BufferedReader reader = new BufferedReader(new FileReader(fileext));
List<String> lines = new ArrayList<String>();
while ((line = reader.readLine()) != null){
lines.add(line);
}
fileLines.put(file, lines);
}