Using Scanner to read file and store in ArrayList? - java

My Code so far. (Keep in mind this is my first programming class and While loops are still hard and new to me.
import java.util.ArrayList;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class InsultGenerator extends Application
{
ArrayList<String> adjectives1;
ArrayList<String> adjectives2;
ArrayList<String> nouns;
public void start(Stage primaryStage) throws FileNotFoundException
{
File file = new File("insultData.txt");
Scanner inFile = new Scanner(file);
while (inFile.hasNext())
{
}
}
}
So I have a project for my school that requires me to take a text file with 3 columns of text. I have to read the text file and store each column in 3 different ArrayLists. Here is the exact statement that described what is wanted.
Use a Scanner object to read the input file. Remember to add a throws FileNotFoundException clause to the start method header.
At the class level (so they can be used in other methods), declare and create three ArrayList objects called adjectives1, adjectives2, and nouns. All three lists should hold String objects.
When reading the input file, use a while loop to check to see if the input file still has data to read:
while (inFile.hasNext())
{
// read and store data
}
Each iteration of the while loop should read one line of data. Store the first adjective on the line in the adjectives1 list, the second in the adjectives2 list, and the noun in the nouns list. Use the next method of the Scanner to read each word. You may assume that each line will have all three values.
Note that you don't have to know how many lines of input data there will be. An ArrayList doesn't have a fixed capacity and expands and contracts as needed.

In the while loop, first read the next line of text to a String. Then, split the String into an array. Finally, push each element of the array to each array list.
String line = inFilw.nextLine();
String[] words = line.split(" ");
adjectives1.add(words[0]);
adjectives2.add(words[1]);
nouns.add(words[2]);

Related

How to get information from a CSV file in Java

I have a .CSV file with rows for [ID], [NAME], [LASTNAME], [EMAIL], [GENDER]. There are 1000 entries.
Out of those five rows I have to:
Find the total of people on the list. (using a for loop?)
Show the first 10 names (name, lastname).
Show 3 RANDOM names.
Only display emails. (Doable with the current code)
Display the first letters of their last name.
Add a random number behind their last name.
Can someone make an example, please?
As a Java beginner I really can't seem to find an answer to this. I have searched everywhere and i think im going crazy.
I have imported the .csv file to my java eclipse, using the following code, currently it only displays the ID's.
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test111 {
public static void main(String[] args) {
String fileName="test.csv";
File file = new File(fileName);
try {
Scanner inputStream = new Scanner(file);
inputStream.next();
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(",");
System.out.println(values[0]);
}
inputStream.close();
System.out.println("e");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
In order to take every value you have to do something like this:
int id = Integer.parseInt(values[0]);
String name = values[1];
String lastName = values[2];
String email = values[3];
String gender = values[4];
Yours is a lesson in why you shouldn't blindly copy code without reading it, researching it and understanding it.
Look at line 15 from your own code. What do you think is going on here?
String[] values = data.split(",");
You've read a line from your CSV file into a field called data and now you're calling the .split method with a comma as a parameter to break up that line into tokens wherever it finds a comma. Those tokens are being placed into the cells of an array called values.
Why are you only getting your ID attribute? Look at this line:
System.out.println(values[0]);
We just established that all tokens have been placed in an array called values. Let's look at the attribute key you provided:
[ID], [NAME], [LASTNAME], [EMAIL], [GENDER]
Hmm... if printing values[0] gives us the ID, I wonder what we'd get if we... oh, I don't know... maybe tried to print from a different element in the array?
Try:
System.out.println(values[1]);
System.out.println(values[2]);
System.out.println(values[3]);
System.out.println(values[4]);
See what you get.
Coding is about trying things in order to learn them. Knowledge doesn't magically become embedded in your head. To learn something, you have to practice repeatedly, and in doing so, you're going to make mistakes -- this is just how it goes. Don't give up so easily.

How to provide the input data for Scanner class from a text file instead of keyboard in java?

I want to provide the series of inputs of my program from a text file so that I do not have to give input time and again, how can I do this using "javac"?
I used to do this in C/C++ Programs and it looked like as far as I remember gcc <sample.txt> filname.exe and it was called batch processing as told by my professor.
Is there any way to do the same with javac or by using some tweak in VS Code so that I do not have to give input from keyboard every time I run the program?
Thank You!
If you want to be able to run the same code, unchanged, for either getting user input via standard input or via a file, I suggest defining a "system" property as a flag to determine where user input comes from, depending on whether the property is defined or not.
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;
public class Testings {
public static void main(String[] args) throws IOException {
String redirect = System.getProperty("REDIRECT");
Scanner scanner;
if (redirect != null) {
scanner = new Scanner(Paths.get("", args));
}
else {
scanner = new Scanner(System.in);
}
if (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
if (redirect != null) {
scanner.close();
}
}
}
If you want input from a file, rather than from standard input, use the following command to run the code.
java -DREDIRECT Testings path/to/file.txt
If you want input from the user, via the keyboard then remove -DREDIRECT, i.e.
java Testings
Since you are not getting input from the file, no need to provide a path.
Note that if you are using an IDE, then it should provide the ability to define a "system" property as above. Also note that the property name can be anything. I simply (and arbitrarily) chose REDIRECT. Remember though, that it is case sensitive.
Alternatively, you can redirect System.in.
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Testings {
private static void redirect(String[] args) throws IOException {
Path path = Paths.get("", args);
InputStream is = Files.newInputStream(path);
System.setIn(is);
}
public static void main(String[] args) throws IOException {
String redirect = System.getProperty("REDIRECT");
Scanner scanner;
if (redirect != null) {
redirect(args);
}
scanner = new Scanner(System.in);
if (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
}
Regarding the file that you use for input, the path to the file can be either relative or absolute. If it is relative, then it is relative to the current working directory which is the value returned by the following code:
System.getProperty("user.dir");
Alternatively, you could make the file a resource which would mean that the path is relative to the CLASSPATH.
Once you've created a new Scanner using System.in, you can send data to that program in at least three ways.
Example code
Here's an example bit of code. It reads three lines of text from System.in, then prints all three lines.
import java.util.Scanner;
public class SystemInExample {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
String one = scanner.nextLine();
String two = scanner.nextLine();
String three = scanner.nextLine();
System.out.println("one: " + one);
System.out.println("two: " + two);
System.out.println("three: " + three);
}
}
Providing input in three ways
Here's a sample run where I typed in three lines of text, then it parroted the lines back out.
aaaaaaa
bbbbbbb
ccccccc
one: aaaaaaa
two: bbbbbbb
three: ccccccc
Here's a variation using a pipe:
use a text file ("input.txt") which has three lines of text
% cat input.txt
one one one
two two two
three three three
use cat to send the contents of that file to a pipe
the piped output goes to the Java program, which I ran using "java" to compile+run in one step – no "javac"
% cat input.txt | java SystemInExample.java
one: one one one
two: two two two
three: three three three
Here's another variation using a redirect:
use the same text file
run the program (again, JEP 330-style)
use < to direct the file contents to stdin for the program
% java SystemInExample.java < input.txt
one: one one one
two: two two two
three: three three three
The above variations should work fine on mac/unix/linux. If you're using Windows, this probably wouldn't work without modifications.

How can I read a line and split it to save it? And do the same for a second file

I have been trying to read my txt file into java and then splitting the two integer columns to then be saved into a list or array. I need these two numbers seperated because I will be uploading a second txt file in which I will have more numbers that I will need to add or substract from the first files columns.
So here is a sample of my txt files:
file 1:
0033 2000
2390 500
etc.
file 2:
0033 2 400
3829 1 3020
etc.
The first file has two columns and the second file has three columns
To be very honest I'm not good with java at all. So far I have only been able to read the files and print them as they are.
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class test {
public static void readlines(File f) throws IOException {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
int NumberOfLines = 0;
while ((line = br.readLine()) != null) {
System.out.println(line);
NumberOfLines++;
}
System.out.println("Number of lines read: " + NumberOfLines);
br.close();
fr.close();
}
public static void main(String[] args) {
File f = new File("filename1");
File s = new File("filename2");
try {
readlines(f);
readlines(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I know that I should be splitting the data using .split("\t") since it's a tab but how can I save this into a column array so that I can later on in a different class add then together? Do I need to make two classes in which I read file1 and in the second file 2? Afterwards I do all my adding in the main class?
Any ideas will be nice here!! Sorry for asking basic stuff but switching from matlab to java is kind of difficult for me D:
What I'd do is to make the readlines(File f) method return an array. Arrays (in case you don't know) are lists or (commonly) similar elements. For example, in your case, that method would return a String array. split() method returns an array of String, where each element is one of the splitted elements. For example:
String[] splitted = "Hello World!".split(' ');
In this case, splitted would be: ["Hello", "World!"]
If you make readlines(File f) return an array with the splitted read content, all you have to do in your main (if you want to keep this "matrix" appereance) is to push the returned value into another Array.
I hope I explained it clear enough ^^

Storing part of a text file into an ArrayList

I have program that reads this text file:
N
How many parameters does a copy constructor accept?
1
S
What standard Java class do all classes inherit from?
Object
m
What is "computer".substring(3, 5)?
- mpute
+ pu
- put
N
What is the value of pi?
3.141592653
And needs to store only these lines (start with + or -) into the array list:
- mpute
+ pu
- put
So far I have this:
import java.io.*;
import java.util.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class Quiz {
public static void test() {
ArrayList<String> choices = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("What quiz are you taking? ");
String name = input.next();
File file = new File(name);
Scanner s = new Scanner(name);
while (s.hasNext()) {
choices.add(s.next());
}
}
}
How will I store only those lines into the array list instead of all the lines?
I suggest you format your question better, because there are a lot of gibberish unrelated to the question but let me answer the question in the subject.
A simple way to do this is to use this
List<String> lines = Files.readAllLines(Paths.get("C:/YourFile.txt"));
This will put all of lines in your file and you can take it from there.

Error Parsing a Csv File with Java

I have a csv file with values like these:
1/1/1983;1,7;-3;8;-0,7;84;4;2;11;0;1030;0;0
2/1/1983;2,7;-2;8,4;1,9;94;2;2;15;0;1027;0;0
3/1/1983;4,1;-0,4;11,3;3,1;93;3;3;13;0;1030;0;0
4/1/1983;7,6;1,3;15;5,1;84;9;8;28;0;1027;0;0
5/1/1983;5,6;1,4;10;5,1;97;2;2;11;0;1023;0;0
6/1/1983;7;5,5;7,5;7;100;1;3;9;0;1028;0;0
7/1/1983;7,7;5;13,4;7,1;96;1;4;20;0;1029;0;0
8/1/1983;7,9;7;15,5;7,4;97;2;7;24;0;1029;0;1
9/1/1983;6,7;1;10,3;4,1;83;8;15;44;0;1033;0;0,3
10/1/1983;2,2;-1,9;8;0,4;88;8;4;13;0;1036;0;0
11/1/1983;0,7;-3,4;6,4;-1,2;87;3;1;13;0;1038;0;0
12/1/1983;0,2;-4,7;8;-1,7;87;6;4;9;0;1037;0;0
13/1/1983;1,7;-5,2;11,1;-0,1;88;4;3;15;0;1032;0;
So i have found on a website a Csv Parser implementation:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerExample
{
public static void main(String[] args) throws FileNotFoundException
{
//Array
ArrayList<String> weather = new ArrayList<String>();
//Get scanner instance
Scanner scanner = new Scanner(new File("C:/csv/meteo2.csv"));
//Set the delimiter used in file
scanner.useDelimiter(";");
//Get all tokens and store them in some data structure
//I am just printing them
while (scanner.hasNext())
{
weather.add(scanner.next());
}
System.out.println(weather.get(12));
//Do not forget to close the scanner
scanner.close();
}
}
But I Have a problem with the last element of one line and the first element of the successive line :
Infact when in the code i try to print the twelfth element (that must be 0). It prints
0
2/1/1983
But it's considered as only one element.
There is a solution to that?
If you want the semicolon and the linebreak as a delimiter, you should use
scanner.useDelimiter("[;\n]");
as Scanner#useDelimiter(String pattern) expects a regular expression as the parameter.

Categories