I'm trying to make an array of strings using a list of names coming from a txt file.
So for example: If I have string[] names = {all the names from the txtfile(one name perline)}
I want to pass "names" into a method that takes in a array like "names"(the one I made above). The method will then run the names through another for loop and create a linked list. I'm really confusing myself on this and tried number of things but nothing seems to work. Right now It'll print out the first name correctly but every name after that just says null. So I have about 70 nulls being printed out.
public static void main(String[] args) {
//String[] names = {"Billy Joe", "Alan Bowe", "Sally Mae", "Joe Blow", "Tasha Blue", "Malcom Floyd"}; // Trying to print theses names..Possibly in alphabetical order
BigNode x = new BigNode();
Scanner in = new Scanner(System.in);
System.out.println("Enter File Name: ");
String Finame = in.nextLine();
System.out.println("You Entered " + Finame);
try {File file = new File(Finame);
BufferedReader readers = new BufferedReader(new FileReader(file));
// String nameLine = ;
String[] name;
name = new String[73];
String[] nameTO;
String nameLine;
// while ((nameLine = readers.readLine()) != null) {
for (int i = 0; i < name.length; i++){
name[i] = readers.readLine();
x.populateNodes(name);
} //}
} catch(IOException e) {
}
Why is x.populateNodes(name) inside the loop? Wouldn't you be populating it after filling your array?
Since I've no idea what BigNode is, I assume it should be one of the following
x.populateNodes(name[i]) inside the loop or x.populateNodes(name) outside the loop.
Related
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];
I'm a beginner so this is definitely common knowledge, so I came here to ask.
If I want to make a very large array that just contains different words, such as this
adjectives[0] = "one";
adjectives[1] = "two";
adjectives[2] = "three";
adjectives[3] = "four";
adjectives[4] = "five";
This is just a small example, the array I'm actually making is very large. Surely I don't have to hardcode this and do each line one by one. How can I do this more efficiently?
EDIT:
Question has slightly shifted while still on the topic.
I want to turn a txt file like this
A
B
C
D
E
into an array list, which is spit out by the program into the console, for use in another program.
Basically textfile.txt -> program -> arraylist.txt
Use a for() loop:
String[] adjectives = new String[6]; //first letter of a non-final variable should be lowercase in java
for(int i = 0; i < adjectives.length; i++) { //loop index from 0 to the arrays length
adjectives[i] = Integer.toString(i) //you could also use an int[]
}
Done.
Also take a look at this:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
If you're trying to simply assign ascending numbers, then use a for loop:
int[] adjectives = int[5];
//replace 5 with whatever you want
for(int x = 0; x < adjectives.length; x++){
adjectives[x] = x
}
If you want to place strings/objects in there that don't have some incremental order, then you can condense the assignment statement to a single line:
String[] adjectives = {"hey", "there", "world", "hello"}
Given the words are comming from a text variable, you could just split it :
String text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
String[] words = text.split("[ \n]");
System.out.println(Arrays.toString(words));
You can use a for loop and parse the index of the lop to string:
final String[] foo = new String[10];
for (int i = 0; i < foo.length; i++) {
foo[i] = Integer.toString(i);
}
System.out.println(Arrays.toString(foo));
read a text file line by line and store each read line into an ArrayList with a BufferedReader
`
import java.io.*;
import java.util.ArrayList;
class TxtFileToArrayList
{
public static void main(String args[])
{
ArrayList lines = new ArrayList();
try{
// Open the file
FileInputStream fstream = new FileInputStream("text.txt"/*file path*/);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine;
//Read File Line By Line
while ((readLine = br.readLine()) != null) {
lines.add(readLine);// put the line in the arrayList
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
}
}
}
`
or use readAllLines()
You can use arraylist and then if you really want arrays only then convert arraylist to array datatype--
List<String> ls=new ArrayList<String>();
for(int i=0;i<=Integer.MAX_VALUE-1;i++)
ls.add(Integer.toString(i));
String array[]=ls.toArray(new String[ls.size()]);
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 got this assignment for school and all my other methods are working just fine, but reading unique words just doesn't work for me.
My method for reading txtfile:
public void lesBok(String filnavn) throws Exception {
File file = new File(filnavn);
Scanner innlestfil = new Scanner(file);
while (innlestfil.hasNextLine()) {
String s = innlestfil.nextLine();
if((ord.contains(s))){
for(i = 0; i < ord.size(); i++){
if(ord.get(i).toString().equalsIgnoreCase(s)){
ord.get(i).oekAntall();
}
}
}else{
Ord nyttOrd = new Ord(s);
ord.add(nyttOrd);
}
}
}
It reads the txt file, but the problem is that it doesn't difference from unique words.
So if a txt file is for example
hey
My
name
is
hey
It reads 5 words instead of 4.
When the same word pops up, I want it to run this method:
public void oekAntall(){
antall ++;
If you are not specifically required to read it in one word at a time, why not read the entire line and then parse it? I would recommend the StringTokenizer class to accomplish this. I'll write out some pseudo code to show what I mean.
String inputLine = sc.readLine();
StringTokenizer st = new StringTokenizer(inputLine, " "); //parse on spaces
while(st.hasMoreTokens()) {
//Parse tokens
array[x] = st.nextToken();
}
I am writing a method that will take in some command line arguments, validate them and if valid will edit an airport's code. The airport name and it's code are stored in a CSV file. An example is "Belfast,BHD". The command line arguments are entered as follows, java editAirport EA BEL Belfast, "EA" is the 2letter code that makes the project know that I want to Edit the code for an Airport, "BEL" is the new code, and Belfast is the name of the Airport.
When I have checked through the cla's and validated them I read through the file and store them in an ArrayList as, "Belfast,BEL". Then I want to update the text file by removing the lines from the text file and dumping in the arraylist, but I cannot figure out how to do it. Can someone show me a way using simple code (no advanced java stuff) how this is possible.
Here is my program
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class editAirport
{
public static void main(String [] args)throws IOException
{
String pattern = "[A-Z]{3}";
String line, line1, line2;
String[] parts;
String[] parts1;
boolean found1 = false, found2 = false;
File file = new File("Airports.txt"); // I created the file using the examples in the outline
Scanner in = new Scanner(file);
Scanner in1 = new Scanner(file);
Scanner in2 = new Scanner(file);
String x = args[0], y = args[1], z = args[2];
//-------------- Validation -------------------------------
if(args.length != 3) // if user enters more or less than 3 CLA's didplay message
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(file.exists())) // if "Airports.txt" doesn't exist end program
JOptionPane.showMessageDialog(null, "Airports.txt does not exist");
else // if everything is hunky dory
{
if(!(x.equals("EA"))) //if user doesn't enter EA an message will be displayed
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(y.matches(pattern))) // If the code doesn't match the pattern a message will be dislayed
JOptionPane.showMessageDialog(null, "Airport Code is invalid");
while(in.hasNext())
{
line = in.nextLine();
parts = line.split(",");
if(y.equalsIgnoreCase(parts[1]))
found1 = true; //checking if Airport code already is in use
if(z.equalsIgnoreCase(parts[0]))
found2 = true; // checking if Airport name is in the file
}
if(found1)
JOptionPane.showMessageDialog(null, "Airport Code already exists, Enter a different one.");
else if(found2 = false)
JOptionPane.showMessageDialog(null, "Airport Name not found, Enter it again.");
else
/*
Creating the ArrayList to store the name,code.
1st while adds the names and coses to arraylist,
checks if the name of the airport that is being edited is in the line,
then it adds the new code onto the name.
sorting the arraylist.
2nd for/while is printing the arraylist into the file
*/
ArrayList<String> airport = new ArrayList<String>();
while(in1.hasNext()) // 1st while
{
line1 = in1.nextLine();
if(line1.contains(z))
{
parts1 = line1.split(",");
parts1[1] = y;
airport.add(parts1[0] + "," + parts1[1]);
}
else
airport.add(line1);
}
Collections.sort(airport); // sorts arraylist
FileWriter aFileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(aFileWriter);
for(int i = 0; i < airport.size();)
{
while(in2.hasNext()) // 2nd while
{
line2 = in2.nextLine();
line2 = airport.get(i);
output.println(line2);
i++;
}
}
output.close();
aFileWriter.close();
}
}
}
}
The Airports.txt file is this
Aberdeen,ABZ
Belfast City,BHD
Dublin,DUB
New York,JFK
Shannon,SNN
Venice,VCE
I think your problem may lie in the two lines:
line2 = in2.nextLine();
line2 = airport.get(i);
this will overwrite the 'line2' in memory, but not in the file.