Printing and matching values in java - java

I have a program that will read a text file starting on line number 29. If the line contains the words "n.a" or "Total" the program will skip those lines.
The program will get the elements [2] and [6] from the array.
I need to get element [6] of the array and print it underneath its corresponding value.
Element[2] of the array is where all the analytes are and element[6] contains the amount of each analyte.
The files that the program will read look like this:
12 9-62-1
Sample Name: 9-62-1 Injection Volume: 25.0
Vial Number: 37 Channel: ECD_1
Sample Type: unknown Wavelength: n.a.
Control Program: Anions Run Bandwidth: n.a.
Quantif. Method: Anions Method Dilution Factor: 1.0000
Recording Time: 10/2/2013 19:55 Sample Weight: 1.0000
Run Time (min): 14.00 Sample Amount: 1.0000
No. Ret.Time Peak Name Height Area Rel.Area Amount Type
min µS µS*min % mG/L
1 2.99 Fluoride 7.341 1.989 0.87 10.458 BMB
2 3.88 Chloride 425.633 108.551 47.72 671.120 BMb
3 4.54 Nitrite 397.537 115.237 50.66 403.430 bMB
4 5.39 n.a. 0.470 0.140 0.06 n.a. BMB
5 11.22 Sulfate 4.232 1.564 0.69 13.064 BMB
Total: 835.213 227.482 100.00 1098.073
The program needs to read that type of files and stores the element[6] of the array under a heading in a separate file in a folder. That file will have a heading like this:
Fluoride,Chloride,Nitrite,Sulfate,
The amount of fluoride should go under fluoride, the amount of chloride should go under chloride and so on and if there isn`t Nitrite or any other analyte it should put a zero for each analyte.
I just need to know how to match that and then I know I have to make write to the file which I will do later, but for know I need help matching.
The final output should looe like this.
The first line will be written in the textfile and then the second line will be values that will be match under its corresponding analyte like this:
Sample#,Date,Time,Fluoride,Chloride,Nitrite,Sulfate,9-62-1,10/2/2013,19:55,10.458,671.120,403.430,13.064,
Also again if an analyte isnt present on the file or it is null it should put a 0.
Here is my code:
//Get the sample#, Date and time.
String line2;
while ((line2 = br2.readLine()) != null) {
if (--linesToSkip2 > 0) {
continue;
}
if (line2.isEmpty() || line2.trim().equals("") || line2.trim().equals("\n")) {
continue;
}
if (line2.contains("n.a.")) {
continue;
}
if (line2.contains("Total")) {
continue;
}
String[] values2 = line2.split("\t");
String v = values2[2];//Stored element 2 in a string.
String v2 = values2[6];//Stored element 6 in a string.
String analytes = "Fluoride,Chloride,Nitrite,Sulfate";//Stored the analytes into an array.
if (analytes.contains(v)) {
System.out.println(v2);
}
int index2 = 0;
for (String value2 : values2) {
/*System.out.println("values[" + index + "] = " + value);*/
index2++;
}
System.out.print(values2[6] + "\b,");
/*System.out.println(values[6]+"\b,");*/
br.close();
}
Thanks in advance!

So if i understand your task right and every element is in new line.
Where is a lot of ways how to solve this, but with your code simpliest way to solve it in my opinion would be with StringBuffer.
//In your code i saw you have to arrays one of them with element name
//other with element code or smth
StringBuffer firstLine = new StringBuffer();
StringBuffer secondLine = new StringBuffer();
public static void printResult(String[] Name, String[] Code){
//First we gona make first line
//Here we are adding data before Names
firstLine.append("Stuff before Names");
for(int i =0;i<name.length;i++){
//Here we gona add all names in the list which is good
//Dont forget spaces
firstLine.append(name[i]+ " ");
}
//And same goes for second line just change loop array and data added before loop.
//And in the end this should print out your result
System.out.println(firstLine+"\n" + secondLine);
}
Call this method after all file reading is done.
Hope it helps!

Related

question on transferring codes, what method should I use?

Question explaination: as some of the comments suggested, I will try my best to make this question clearer. The inputs are from a file and the code is just one example. Supposedly the code should work for any inputs in the format. I understand that I need to use Scanner to read the file. The question would be what code do I use to get to the output.
Input Specification:
The first line of input contains the number N, which is the number of lines that follow. The next
N lines will contain at least one and at most 80 characters, none of which are spaces.
Output Specification:
Output will be N lines. Line i of the output will be the encoding of the line i + 1 of the input.
The encoding of a line will be a sequence of pairs, separated by a space, where each pair is an
integer (representing the number of times the character appears consecutively) followed by a space,
followed by the character.
Sample Input
4
+++===!!!!
777777......TTTTTTTTTTTT
(AABBC)
3.1415555
Output for Sample Input
3 + 3 = 4 !
6 7 6 . 12 T
1 ( 2 A 2 B 1 C 1 )
1 3 1 . 1 1 1 4 1 1 4 5
I have only posted two questions so far, and I don't quite understand the standard of a "good" question and a "bad" question? Can someone explain why this is a bad question? Appreciate it!
Complete working code here try it.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CharTask {
public static void main(String[] args) {
List<String> lines = null;
try {
File file = new File("inp.txt");
FileInputStream ins =new FileInputStream(file);
Scanner scanner = new Scanner(ins);
lines = new ArrayList<String>();
while(scanner.hasNext()) {
lines.add(scanner.nextLine());
}
List<String> output = processInput(lines);
for (int i=1;i<output.size(); i++) {
System.out.println(output.get(i));
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static List<String> processInput(List<String> lines){
List<String> output = new ArrayList<String>();
for (String line: lines) {
output.add(getProcessLine(line));
}
return output;
}
private static String getProcessLine(String line) {
if(line.length() == 0) {
return null;
}
String output = "";
char prev = line.charAt(0);
int count = 1;
for(int i=1;i<line.length();i++) {
char c = line.charAt(i);
if (c == prev) {
count = count +1;
}
else {
output = output + " "+count + " "+prev;
prev = c;
count = 1;
}
}
output = output + " "+count+" "+prev;
return output;
}
}
Input
(inp.txt)
4
+++===!!!!
777777......TTTTTTTTTTTT
(AABBC)
3.1415555
Output
3 + 3 = 4 !
6 7 6 . 12 T
1 ( 2 A 2 B 1 C 1 )
1 3 1 . 1 1 1 4 1 1 4 5
There are two different problems you need to address, and I think it is going to help you to address them separately. The first is to read in the input. It's not clear to me whether you are going to prompt for it and whether it is coming from the console or a file or what exactly. For that you will want to initialize a scanner, use nextInt to get the number of lines, call nextLine() to clear the rest of that line and then run a for loop from 0 up to the number of lines, reading the next line (using nextLine()) into a String variable. To make sure that is working well, I would suggest printing out the unaltered string and see if what is coming out is what is going in.
The other task is to convert a given input String into the desired output String. You can work on that independently, then pull things back together later. You will want a method that takes in a string and returns a string. You can test it by passing the sample Strings and seeing if it gives you back the desired output strings. Set the result="". Looping over the characters in the String using charAt, it will want variables for the currentCharacter and currentCount, and when the character changes or the end of the string is encountered, concatenate the number and character onto the string and reset the character count and current character as needed. Outside the loop, return the result.
Once the two tasks are solved, pull them together by printing out what the method returns for the input string as opposed to the input string itself.
I think that gives you direction on the method to use. It's not a full-blown solution, but that's not what you requested or needed.

Counting numbers in a line

I'm reading my game map
FileHandle file = Gdx.files.internal("data/" + level + ".txt");
StringTokenizer tokens = new StringTokenizer(file.readString());
while(tokens.hasMoreTokens()){
String type = tokens.nextToken();
if(type.equals("Car")){
carLiist.add(new Car(Integer.parseInt(tokens.nextToken()), Integer.parseInt(tokens.nextToken()), Float.parseFloat(tokens.nextToken()), Float.parseFloat(tokens.nextToken())));
}
And here is my text file
Block 0 0
Block 64 0
Car 1 5 9 5
Car 1 5 2
Block 1
Car 7
Is it possible in java to count number in each line?
EDIT:
How I need to get whole line using stringtokenizer? Here what I'm trying to do, but I get only first word in each line
while(tokens.hasMoreTokens()){
String type = tokens.nextToken();
System.out.println(type);
if(type.equals("Block")){
//System.out.println(type);
list.add(new Brick(Integer.parseInt(tokens.nextToken()), Integer.parseInt(tokens.nextToken())));
Yes there is. Java provides a method to check whether a character is digit or not. Check the character and and increase count if its digit like this:
int digitCount = 0;
if(isDigit(characterToCheck)) {
digitCount++;
}
Method: boolean isDigit(char ch). See here for example

Splitting an input file in Java

I've spent a good couple hours trying to solve this myself, but I just can't figure it out and decided to ask.
I am loading a file into my program for me to split into three fields.Each line in the text file contains 3 comma separated values
double, double, char. I plan on creating an array for each and then type wrapping each string in each array index into its respective array of its type. So first I need to split each line of the input.
So I opened the file and split the input as such:
Scanner fileIn = null;
String temp = "";
String[] data;
String fileName = "test.txt";
File textFile = new File(fileName);
fileIn = new Scanner(textFile);
while(fileIn.hasNext()){
temp += in.next;
}
data = temp.split(",");
for(String string: data) {
System.out.println(string);
}
*NOTE: I know this isn't the prettiest way, but this is just one of the many ways I tried to produce my output.
After using various variations of .split() such as temp.split(",") temp.split(",|\n") temp.split(",|\r") temp.split(",|\r\n") and others I get the same output of
0
0
.1
0
.2
0
.3
0
.4
0
.5
0
So basically after the last character of a line gets paired with the first character of the next line. And I have no Idea how to get it to output to one character per line. Here's a copy of the text file. Thanks for all the help in advance!
EDIT: Text copy of output.
It's your while loop. Just after the loop, temp looks like...
0,0,.1,0,.2,0,.3,0,.4,0,.5,0,.6,0,.7,0,.8,0,.9,0,.10,0,.
You can manually insert a comma like...
while(fileIn.hasNext()){
temp += fileIn.next() + ",";
}
Then temp looks like...
0,0,.,1,0,.,2,0,.,3,0,.,4,0,.,5,0,.,6,0,.,7,0,.,8,0,.,9,0,.,10,0,.,
which can be split with ","

Save multiple strings into one string

I want to save multiple strings in one. Thing is, I don't know how many strings it may be.
I'm creating a program that reads calories from a text file and stores them in corresponding arrays.
Here are parts of the text:
Description of food Fat Food Energy Carbohydrate Protein Cholesterol Weight Saturated Fat
(Grams) (calories) (Grams) (Grams) (Milligrams) (Grams) (Grams)
APPLES, RAW, PEELED, SLICED 1 CUP 0 65 16 0 0 110 0.1
APPLES, RAW, UNPEELED,2 PER LB1 APPLE 1 125 32 0 0 212 0.1
APPLES, RAW, UNPEELED,3 PER LB1 APPLE 0 80 21 0 0 138 0.1
APRICOT NECTAR, NO ADDED VIT C1 CUP 0 140 36 1 0 251 0
Now for the food name, I have an array foodName. I will read the whole string until I reach an int which is the amount.
Here is what I've done so far:
Scanner input = new Scanner("Calories.txt");
while (input.hasNext()) {
String[] words = input.next().split(" ");
int lastI;
for (int i=0; i < words.length; i++) {
if (isNumeric(words[i])) {
lastI = i;
for(int j=lastI; j>=0; j++){
//What should I put here?
}
}
}
}
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
for the inner most for loop, I kept track of the last index so I could start from it and go backwards.
Problem 1: If I go backwards in the second line, I will copy both lines.
Problem 2: How to save all the strings of the name in one index of foodName?
All help is appreciated :)
What you are looking for in Java is called a StringBuilder. You can use this essentially like a string and keep appending onto it.
File file = new File("output.txt");
Scanner input = new Scanner(file);
StringBuilder sb = new StringBuilder();
while (input.hasNextLine()) {
String[] words = input.nextLine().split(" ");
for (int i = 0; i < words.length; i++) {
if (isNumeric(words[i])) {
break;
}
sb.append(words[i] + " ");
}
System.out.println(sb);
sb = new StringBuilder();
}
input.close();
What this does is read the file line by line, creating an array of strings splitting the line on " ". Then, it iterates over each of the strings in the array and checks if it is a number, if it is, it will break the current loop and move onto the next line.
I had the StringBuilder print after each line, and then reset, you should replace this with whatever functionality that you want.
A couples suggestions also for you:
Use a CSV file. Separate everything with commas instead of spaces, it makes parsing extremely easy.
Use regex to check if the string is a number instead of catching exceptions, it is more elegant.
The output of this comes out a little funny because of how you formatted your file. You are parsing on " ", but you added a bunch of extra " " characters in the file to make the format look nice. This messes up your parsing very badly. BUT, this method will parse for you correctly when you fix the format of your flat file.
Output from this was: (note that each line is a separate string. You can see how the file formatting messed up the output)
Description of food Fat Food Energy Carbohydrate Protein Cholesterol Weight Saturated Fat
(Grams) (calories) (Grams) (Grams) (Milligrams) (Grams) (Grams)
APPLES, RAW, PEELED, SLICED
APPLES, RAW, UNPEELED,2 PER LB1 APPLE
APPLES, RAW, UNPEELED,3 PER LB1 APPLE
APRICOT NECTAR, NO ADDED VIT C1 CUP

Store an array into another array for use outside of scope

Question: I need to store the values of lengthCount[j] into an array outside of the scope. \
What I have tried: To add a return statement into the for-loop and making the code into a method.
What are the variables:
lengthCount = [I#78db81f3
j = assigned in for-loop
The code below returns the correct result to the console, but I can't store the correct data into an array for use on the outside of the scope.
What I am trying to do: To take a string, count the letters of each word and then find out how many of each length word there are. E.g. 3 words with 3 letters, 1 word with 1 letter.
My current output:
String length: 0 count: 0
String length: 1 count: 2
String length: 2 count: 2
String length: 3 count: 4
String length: 4 count: 4
String length: 5 count: 1
String length: 6 count: 1
So you can see the code is outputting the correct data, how can I store this into an int array?
for(int j=0; j<lengthCount.length;j++){
System.out.println("String length: "+j+" count: "+lengthCount[j]);
}
If you require any more information, please just leave a comment and I will add it rapido!
Thanks in advance!
Full Code
public class lengthCountReturn {
public static void main(String[] args) {
String userInput = "I do not like green eggs and ham I do not like them Sam-I-Am";
userInput = userInput.replaceAll("\\p{P}", "");
String str[] = userInput.split(" "); // split the strings: "I", "am", "going", etc
int maxLength = 0;
for(String s: str) // finding the word with maximum size and take its length
if(maxLength < s.length())
maxLength = s.length();
int lengthCount[] = new int[maxLength+1];
for(String s1: str)
{
lengthCount[s1.length()]++; // count each length's occurance
}
System.out.println(lengthCount);
for(int j=0; j<lengthCount.length;j++)
{
System.out.println("String length: "+j+" count: "+lengthCount[j]);
}
}
}
Using apache commons you have a one line solution but works only with primitive types and their equivalent objects ( int and Integer, byte and Byte, etc):
Lets say that you have;
import org.apache.commons.lang;
String[] source = {"hello", "world", "foo", "bar"};
Just do:
String[] clone = ArrayUtils.subarray(source, 0, source.length);
In which structure do you wish to store the result ?
I would suggest a Map, for each length lengthCount[j], test if the key exist, add one to the value if yes, otherwise add the key with value 1.
Just define a variable in the scope you need it, and use it in the inner scope.
int[] newArray = new int[lengthCount.length]
for(int j=0; j<lengthCount.length;j++)
{
newArray[j] = lengthCount[j];
}
However all this code is doing is copying the values from lengthCount[] into newArray[], which could be achieved with one call to System.arraycopy(). (All your original code did was print the contents of lengthCount[]).
So your question "how can I store this in an array" makes little sense: it's already in an array.
For "real" code you should investigate the Java Collections API, which gives you more expressive ways to work with data like this. If you are just learning Java, you'll get to Collections soon.

Categories

Resources