How to split strings into columns - java

I have a list of Strings in single column. I want to make three columns from these string and then print the ouput to another file. How do I do this?
Here is what I've tried so far:
ArrayList<String> list=new ArrayList<String>();
File file = new File("f://file.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
My input data:
City
Gsk
Relocation
sripallu
here
jrajesh
gurgaon
unitech
StatisticsThreads
WizOty
LTDParsvnathK
Quotesby
newest
PMaashuktr
My expected output:
City Gsk Relocation
sripallu here jrajesh
gurgaon unitech StatisticsThreads
WizOty LTDParsvnathK Quotesby
newest PMaashuktr Loans
.
.
.
.
.
.
.

You can structured your requirement in class like Output and make a list of Output.
public class Output{
private String str1;
private String str2;
private String str3;
<geter & setter method>
}
...
ArrayList<Output> list=new ArrayList<Output>();
int i=-1; Output op =null;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();i = ++i%3;
if(i==0){
op = new Output();
op.setStr1(line);
}else if(i==1)
op.setStr2(line);
else
op.setStr3(line);
}

I took your code and modified it a little:
File file = new File("f://file.txt");
try {
Scanner scanner = new Scanner(file);
int itemsOnRow = 0;
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.print (line + " ");
itemsOnRow++;
if (itemsOnRow == 3)
{
itemsOnRow = 0;
System.out.println ();
}
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
You should actually try to implement it next time. If you fail but post the code that you wrote, then it's easier for the people here to help you.

Related

How to add comma seperated string and int into two different arraylists [java]

Say I have strings and integers being read from a file and seperated by a comma and I want to add them into two different arrayLists.
hamburger,15
cheese,10
soda,15
How would I go about doing this? I intially used nextLine() to add them into one arraylist and extract the integer and erase the comma but this wasn't working for arrayLists. I also tried using nextInt() to just grab the int's but was given an exception.
public static void readFile(ArrayList items, ArrayList cost)
{
String intValue = "";
try
{
Scanner read = new Scanner(new File("Menu.txt"));
while (read.hasNext())
{
items.add(read.nextLine());
}
read.close();
for (int i = 0; i < items.size(); i++)
{
intValue = items.indexOf(i).replaceAll("[^0-9]", "");
int value = Integer.parseInt(intValue);
cost.add(value);
}
System.out.println(item);
System.out.println(cost);
}
catch(FileNotFoundException fnf)
{
System.out.println("File was not found.");
}
}
my end result would be:
items = [hamburger, cheese, soda]
cost = [15, 10, 15]
public static void readFile(List<String> items, List<Integer> costs) {
try {
Scanner read = new Scanner(new File("Menu.txt"));
while (read.hasNext()) {
String line = read.nextLine();
String[] itemsAndCosts = line.split(",");
items.add(itemsAndCosts[0]);
costs.add(Integer.parseInt(itemsAndCosts[1]));
}
read.close();
System.out.println(items);
System.out.println(costs);
} catch (FileNotFoundException fnf) {
System.out.println("File was not found.");
}
}
Use List<String> instead of ArrayList.
You can split the line on the , and then you have an array of 2 elements, item and cost. (Note: will only work if there is only one , per line). You can also use .subString(...), but for me, splitting is cleaner.
Use try-with-resources so you don't need to do .close():
try (Scanner read = new Scanner(new File("Menu.txt"))) {
while (read.hasNext()) {
String line = read.nextLine();
String[] itemsAndCosts = line.split(",");
items.add(itemsAndCosts[0]);
costs.add(Integer.parseInt(itemsAndCosts[1]));
}
System.out.println(items);
System.out.println(costs);
} catch (FileNotFoundException fnf) {
System.out.println("File was not found.");
}

Where do I place the return of a function in JAVA?

I'm trying to figure out how to make a function in JAVA that searches through a document line per line:
First I initialize the file and a reader, then convert each line to a string in an ArrayList; after that I try to check the ArrayList against a String to then return the position of the ArrayList as a string.
So for example I have a text containing:
1 - Somewhere over the rainbow
2 - Way up high.
Converted to ArrayList, if then searched for: "Somewhere"; then it should return the sentence "Somewhere over the rainbow";
Here is the code I tried; but it keeps returning 'null';
String FReadUtilString(String line) {
File file = new File(filepath);
ArrayList<String> lineReader = new ArrayList<String>();
System.out.println();
try {
Scanner sc = new Scanner(file);
String outputReader;
while (sc.hasNextLine()) {
lineReader.add(sc.nextLine());
}
sc.close();
for(int count = 0; count < lineReader.size(); count++) {
if(lineReader.get(count).contains(line)){outputReader = lineReader.get(count);}
}
} catch (Exception linereadeline) {
System.out.println(linereadeline);
}
return outputReader;
}
I refactor your code a bit, but I keep your logic, it should work for you:
String FReadUtilString(String line, String fileName){
File file = new File(fileName);
List<String> lineReader = new ArrayList<>();
String outputReader = "";
try (Scanner sc = new Scanner(file))
{
while (sc.hasNextLine()) {
lineReader.add(sc.nextLine());
}
for (int count = 0; count < lineReader.size(); count++){
if (lineReader.get(count).contains(line)){
outputReader = lineReader.get(count);
}
}
}
catch (Exception linereadeline) {
System.out.println(linereadeline);
}
return outputReader;
}
NOTE: I used the try-with-resource statement to ensure the closing of the Scanner.
A more succinct version:
String fReadUtilString(String line, String fileName) {
try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
return lines.filter(l -> l.contains(line)).findFirst();
}
catch (Exception linereadeline) {
System.out.println(linereadeline); // or just let the exception propagate
}
}

Need help parsing a csv file and gathering the information together

The csv file I am trying to parse contains various samples with several lines per sample. For example, there are 10 lines with the same sample name "S1" and I need to get the CT value from each line. I am trying to combine the CT values (differentiated by the Target Name) to create a Sample class for each sample. I am able to parse the file, but I am having a hard time getting it to loop through and gather the right data.
The constructor for my Sample class has 11 parameters, one for the sample name and 10 for the CT values.
After thinking about it for a long time I tried gathering all of the information I need in an ArrayList of String arrays. This didn't help too much because I now don't know how to gather the information together to create and instance of my Sample class. Here's what I tried:
public void parseCSV(){
String line = "";
String csvSplitBy = ",";
try
{
Scanner scanner = new Scanner(new FileReader("/Users/Neema/Desktop/testData.csv"));
String[] data;
while (scanner.hasNextLine())
{
line = scanner.nextLine();
data = line.split(csvSplitBy);
if (data.length > 0 && data[0].equals("Well"))
{
while (scanner.hasNextLine())
{
line = scanner.nextLine();
data = line.split(csvSplitBy);
if (data.length > 4)
{
String sampleName = data[3];
String dataType = data[4];
String ctValue = data[11];
String[] gatheredData = {sampleName, dataType, ctValue};
parsedData.add(gatheredData);
}
}
}
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Here is the csv file, testData2
Thanks for any help!
I think I understand. What you need is a Sample Factory.
class SampleFactory {
String sampleName;
List<TargetAndValue> sampleList;
SampleFactory(String sampleName)
{
this.sampleName = sampleName;
}
class TargetAndValue{
String dataType;
String ctValue;
TargetAndValue(dataType, ctValue)
{
this.dataType = dataType;
this.ctValue = ctValue;
}
}
void addCtValue(dataType, ctValue) { //Instantiate a new TargetAndValue class }
Sample build(){ //Construct your Sample here }
}
Than what you need is a list of SampleFactories. As you parse each line you search for the SampleFactory that has the right sampleName, and add your data point. Once you have parsed everything use your factory to spit out your Sample objects.
Try it with a map. For example
public void parseCSV(){
String line = "";
String csvSplitBy = ",";
Map<String,List<String>> mapofSamples = new TreeMap<>(); // import java.util.Map; import java.util.TreeMap;
try
{
Scanner scanner = new Scanner(new FileReader("/Users/Neema/Desktop/testData.csv"));
String[] data;
while (scanner.hasNextLine())
{
line = scanner.nextLine();
data = line.split(csvSplitBy);
if (data.length > 0 && data[0].equals("Well"))
{
while (scanner.hasNextLine())
{
line = scanner.nextLine();
data = line.split(csvSplitBy);
if (data.length > 4)
{
if(!mapofSamples.containsKey(data[3])){ // if the map does not already contain the sample name add this name and a list with the value
mapofSamples.put(data[3],new ArrayList(){{add(data[11]);}} );
}
else{
mapofSamples.get(data[3]).add(data[11]); // else just add the value to the corresponding sample names value list
}
}
}
}
}
for(String key: mapofSamples.keySet()){ // check if it prints the right keys and values
System.out.println("sample :" + key);
System.out.println("values :" + mapofSamples.get(key));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

How to read a line from a txt file with int and String elements?

I'm trying to create a List by reading a txt file. For example:
12345; Mary Jane ; 20
12365; Annabelle Gibson; NA
Each line contains: number; name; Grade (grade can be a String or a int)
I created the following method;
public static List <Pauta>leFicheiro( String nomeF) throws FileNotFoundException{
List<Pauta> pautaT = new LinkedList<Pauta>();
try {
Scanner s = new Scanner(new File (nomeF));
try{
List<Pauta> pautaS =pautaT;
while ( s.hasNextLine()){
String line = s.nextLine();
String tokens[]= line.split(";");
if(s.hasNextInt()) {
System.out.println ("next int = " + s.nextInt());
}
pautaS.add(new Pauta (s.nextInt(), tokens[1],tokens[2]);
}
pautaT = pautaS;
}
finally {
s.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (ParseException e){
e.printStackTrace();
}
return pautaT;
}
Pauta is a class that receives as arguments ( int, String, String), I thought Grade as a String to make it more simple, but if you have ideas on how to still create a List (main goal) by having it String or int I would be thankful.
Now the problem is: The part s.nextInt() is returning error : InputMismatchException
So I put this following code:
catch (InputMismatchException e) {
System.out.print(e.getMessage());}
which says it returns a null.
How can I solve this?
Instead of using the s.nextInt(), parse the first token to an Integer.
See the example below.
public static void main(String... args) throws FileNotFoundException {
List<Pauta> pautaT = new LinkedList<Pauta>();
try {
Scanner s = new Scanner(new File("test.txt"));
try{
List<Pauta> pautaS =pautaT;
while ( s.hasNextLine()){
String line = s.nextLine();
String tokens[]= line.split(";");
pautaS.add(new Pauta (Integer.parseInt(tokens[0]), tokens[1],tokens[2]));
}
pautaT = pautaS;
}
finally {
s.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
This results in the list to be populated.
Yo may use StringTokenizer and save each token of the same line into a variable and then use them as you want.

Extracing and assigning values from a text file to variable - Java

I am having trouble assigning values from text file to 4 variables. The file has four values in each line which are separated by space. I want to assign each value to a different variable.
the data in the items.txt:
344443 toothbrush WW WQ
243434 ToothPaste WE WQ
349343 DentalFloss WS QA
This is my code which isnt working.
File itemsSold = new File("items.txt");
if (itemsSold.exists()){
Scanner inputFile = new Scanner(itemsSold);
while (inputFile.hasNextLine()) {
Items = inputFile.nextLine();
ItemId = inputFile.nextInt();
ItemName = inputFile.next();
String itemShlve = inputFile.next();
String itemcode= inputFile.next();
System.out.print(ItemId + "\n");
System.out.print(ItemName);
System.out.print(itemitemShlve);
}
inputFile.close();
}
Output needed is this, which what I get:
344443
toothbrush
WW
243434
ToothPaste
WE
349343
DentalFloss
WS
A beginner to Java, Thanks in advance.
You can do this:
Scanner fScn = new Scanner(new File(“items.txt”));
String data;
while( fScn.hasNextLine() ){
data = fScn.nextLine();
String[] token = data.split(" ");
itemId = Integer.parseInt(token[0]);
itemName= token[1];
itemShelve = token[2];
itemCode = token[3];
}
fScn.close();
1) Use file Scanner to capture data line by line
2) Split the line of data into tokens by white spaces
3) Assign the tokens accordingly into respective variables
4) Close file Scanner
Don't mix calls to nextInt and nextLine. Just use nextLine in this case.
Use another Scanner for each line.
if (itemsSold.exists()){
Scanner inputFile = new Scanner(itemsSold);
while (inputFile.hasNextLine()) { // check for next line
Items = inputFile.nextLine(); // read next line
Scanner scanner = new Scanner(Items);//create new Scanner for new line
ItemId = scanner.nextInt(); // read next int
ItemName = scanner.next();
String itemShlve = scanner.next();
String itemcode= scanner.next();
scanner.close(); // don't forget to close the Scanner
...
}
inputFile.close();
}
Note: Follow Java Naming convention.
I hope it will help. If you want fourth value also. Set the value 4 in the SysOut Loop.
File file = new File("C:\\items.Txt");
String[] variable = new String[4];
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
int count;
String temp = new String();
while((line = br.readLine())!=null) {
count = 0;
for(char c : line.toCharArray()) {
if(c ==' ') {
variable[count] = temp;
temp = new String();
count++;
}
else {
temp += c;
}
}
for(int i=0; i<3; i++) {
System.out.println(variable[i]);
}
System.out.println();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
br.close()
fr.close();

Categories

Resources