I have this from text file:
134.897 134.4565 135.134
I read them using :
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split(" ");
String x1 = (parts[0]);
String x2 = (parts[1]);
String x3 = (parts[2]);
From the String in the text file :
134.897
134.4565
135.134
I just want to take the different number between these three number :
4.897
4.4565
5.134
Given more example :
Text file :
101.435
101.423
101.322
Number I want to take :
435
423
322
My plan is I want to compare each number with others,
101.435//x1
101.423//x2
101.322//x3
if x1.substring(0)=x2.substring(0)=x3.substring(0)
then remove substring(0).
I want to loop this "if" condition until the substring are not same.
Please give me some idea, thanks
Here's the skeleton of an algorithm that could be used:
List<String> inputs = ...;
int index = 0;
while (allTheStringsHaveTheSameCharacterAtIndex(inputs, index)) {
index++;
}
List<String> outputs = takeSubstringOf(inputs, index);
I'll let you fill the blanks, which are very easy to implement with the methods offered by the String class, and loops.
You didn't answer #Steve about scenario of different length of numbers, I'll assume you want to compare numbers according to characters order. Also, I assume that the file always contains three strings in one line, saperated by one white space.
Given this, I hope this helps:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FindDifference {
static File f = null;
ArrayList<String> inputs = new ArrayList<String>();
static String x1 = null;
static String x2 = null;
static String x3 = null;
private static ArrayList<String> getDifferenceList() {
ArrayList<String> ret = new ArrayList<String>();
if (x1 == null || x1.isEmpty()
|| x2 == null || x2.isEmpty()
|| x3 == null || x3.isEmpty()) {
ret.add(x1);
ret.add(x2);
ret.add(x3);
return ret;
}
int index = 0;
while (index < x1.length()
&& index < x2.length()
&& index < x3.length()) {
if (x1.charAt(index) != x2.charAt(index)
|| x1.charAt(index) != x3.charAt(index)) {
break;
}
index++;
}
ret.add(x1.substring(index, x1.length()));
ret.add(x2.substring(index, x2.length()));
ret.add(x3.substring(index, x3.length()));
return ret;
}
public static void main(String[] args) {
if (args.length > 0) {
f = new File(args[0]);
} else {
System.out.println("Please supply file path.");
return;
}
String line;
BufferedReader buffreader = null;
try {
buffreader = new BufferedReader(new FileReader(f));
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split(" ");
x1 = (parts[0]);
x2 = (parts[1]);
x3 = (parts[2]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> output = getDifferenceList();
try {
System.out.println(output.get(0));
System.out.println(output.get(1));
System.out.println(output.get(2));
} catch (Exception e) {
e.printStackTrace();
}
}
}
I made it SSCCE. You can use only getDifferenceList (supplying x1,x2,x3 as fields) in your code (delete "static" wherever needed).
EDIT
As I said, you can use getDifferenceList in any scope (including Android application). I copy this method separately, simply copy-paste it into any class you want, and call it passing the file path:
ArrayList<String> getDifferenceList(String filePath) {
File f = new File(filePath);
String line, x1 = null, x2= null, x3 = null;
BufferedReader buffreader = null;
try {
buffreader = new BufferedReader(new FileReader(f));
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split(" ");
x1 = (parts[0]);
x2 = (parts[1]);
x3 = (parts[2]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> ret = new ArrayList<String>();
if (x1 == null || x1.isEmpty()
|| x2 == null || x2.isEmpty()
|| x3 == null || x3.isEmpty()) {
ret.add(x1);
ret.add(x2);
ret.add(x3);
return ret;
}
int index = 0;
while (index < x1.length()
&& index < x2.length()
&& index < x3.length()) {
if (x1.charAt(index) != x2.charAt(index)
|| x1.charAt(index) != x3.charAt(index)) {
break;
}
index++;
}
ret.add(x1.substring(index, x1.length()));
ret.add(x2.substring(index, x2.length()));
ret.add(x3.substring(index, x3.length()));
return ret;
}
Related
I need to manipulate this code so that it will read the # of digits from a file.
I am honestly stumped on this one for some reason. Do i need to tokenize it first?
Thanks!
import java.io.*;
import java.util.*;
public class CountLetters {
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Synopsis: Java CountLetters inputFileName");
System.exit(1);
}
String line = null;
int numCount = 0;
try {
FileReader f = new FileReader(args[0]);
BufferedReader in = new BufferedReader(f);
while ((line = in.readLine()) != null) {
for (int k = 0; k < line.length(); ++k)
if (line.charAt(k) >= 0 && line.charAt(k) <= 9)
++numCount;
}
in.close();
f.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(numCount + " numbers in this file.");
} // main
} // CountNumbers
Use '' to indicate a char constant (you are comparing chars to ints), also I would suggest you use try-with-resources Statement to avoid explicit close calls and please avoid using one line loops without braces (unless you are using lambdas). Like
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Synopsis: Java CountLetters inputFileName");
System.exit(1);
}
String line = null;
int numCount = 0;
try (BufferedReader in = new BufferedReader(new FileReader(args[0]))) {
while ((line = in.readLine()) != null) {
for (int k = 0; k < line.length(); ++k) {
if ((line.charAt(k) >= '0' && line.charAt(k) <= '9')) {
++numCount;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(numCount + " numbers in this file.");
} // main
Also, you could use a regular expression to remove all non-digits (\\D) and add the length of the resulting String (which is all-digits). Like,
while ((line = in.readLine()) != null) {
numCount += line.replaceAll("\\D", "").length();
}
Use if(Charachter.isDigit(char)) replace char with each char, this will count each number, and I believe arabic numbers as well.
Hello I have an application that loads in values. The values are x,y,and a string value. I want to know how to load in a string because I only know how to o it with an integer. Take a look at this code:
public static void loadStars() {
try {
BufferedReader bf = new BufferedReader(new FileReader ("files/cards.txt"));
for (int i = 0; i < 10; i++) {
String line;
while ((line = bf.readLine()) != null) {
String[] args = line.split(" ");
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
String name = Integer.parseInt(args[2]);
play.s.add(new Star(x,y,name));
}
}
bf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have
play.s.add(new star(x,y,name));
I know how to load in x and y but I don't know how to load in name.
Please help me.
Edit----
In the file that is loaded in it is formatted like this:
x y name
example:
10 10 jack
100 500 conor
each star is represented by 1 line.
public class Star extends BasicStar {
private Image img;
public Star(int x, int y,String starname) {
this.x = x;
this.y = y;
this.starname = starname;
r = new Rectangle(x, y, 3, 3);
}
public void tick() {
if (r.contains(Comp.mx, Comp.my) && Comp.ml) {
remove = true;
}
}
public void render(Graphics g) {
if (!displaySolar) {
ImageIcon i2 = new ImageIcon("res/planets/star.png");
img = i2.getImage();
g.drawImage(img, x, y, null);
}
}
}
Array args[] is already String so you just need to change
String name = Integer.parseInt(args[2]);
to
String name = args[2];
And that's it.
Try this.
public static void loadStars() {
try {
BufferedReader bf = new BufferedReader(new FileReader ("files/cards.txt"));
for (int i = 0; i < 10; i++) {
String line;
while ((line = bf.readLine()) != null) {
String[] args = line.split(" ");
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
String name = args[2]; // args array contain string, no need of conversion.
play.s.add(new Star(x,y,name));
}
}
bf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
you improve your code by using a StringTokenizer. Try This.
public static void loadStars()
throws IOException {
String line;
BufferedReader bf = new BufferedReader(new FileReader ("files/cards.txt"));
try
{
while((line = bf.readLine()) != null)
{
if (line == null || line.trim().isEmpty())
throw new IllegalArgumentException(
"Line null!");
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (tokenizer.countTokens() < 3)
throw new IllegalArgumentException(
"Token number not valid (<= 3)");
int x, y;
String xx = tokenizer.nextToken(" ").trim();
String yy = tokenizer.nextToken(" ").trim();
String name = tokenizer.nextToken(" ").trim();
try
{
x = Integer.parseInt(xx);
}catch(ParseException e){throw new IllegalArgumentException(
"Number format not valid!");}
try
{
y = Integer.parseInt(yy);
}catch(ParseException e){throw new IllegalArgumentException(
"Number format not valid!");}
play.s.add(new Star(x,y,name));
}
} catch (NoSuchElementException | NumberFormatException | ParseException e) {
throw new IllegalArgumentException(e);
}
}
Array args[] is already String so you just need to change
String name = Integer.parseInt(args[2]);
// If you are using this values anywhere else you'd do this so de GC can collects the arg[] array
String name = new String(args[2]);
Be aware that if you have spaces in string arguments each word will be a new argument. If you have a call like:
java -jar MyProgram 1 2 This is a sentence.
Your arg[] will be:
{"1", "2", "This", "is", "a", "sentence."}
If you need the sentence to be one String you should use apostrophes:
java -jar MyProgram 1 2 "This is a sentence."
Your arg[] will be:
{"1", "2", "This is a sentence."}
I have got two text files with data in the following format
data.txt file as following format
A 10
B 20
C 15
data1.txt file is in format (start node,end node, distance):
A B 5
A C 10
B C 20
I am trying to implement a search strategy, for that I need to load the data from data.txt and ONLY the start node and end node from data1.txt (i.e. I dont need the distance). I need to store this information in a stack as I think it would be a best data structure for implementing greedy search.
Actually I am not sure how to get started with file I/O to read these files and store them in array to implement greedy search. So I would highly appreciate any starting idea on how to proceed.
I am new to this, so please bear with me. Any help is much appreciated. Thanks.
EDIT:
Here is what I have got till now
String heuristic_file = "data.txt";
try
{
FileReader inputHeuristic = new FileReader(heuristic_file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
while ((line = bufferReader.readLine()) != null)
{
System.out.println(line);
}
bufferReader.close();
} catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
My approach, doesn't differ fundamentally from the others. Please regard the try/catch/finally blocks. Always put the closing statements into the finally block, so the opened file is guaranteed to be closed, even if an exception was thrown while reading the file.
The part between the two //[...] could surely be done more efficient. Maybe reading the whole file in one take and then parsing the text backwards and searching for a line-break? Maybe a Stream-API supports to set the reading position. I honestly don't know. I didn't need that, up to now.
I chose to use the verbose initialization of the BufferedReader, because then you can specify the expected encoding of the file. In your case it doesn't matter, since your files do not contain symbols out of the standard ASCII range, but I believe it's a semi-best-practice.
Before you ask: r.close() takes care of closing the underlying InputStreamReader and FileInputStream in the right order, till all readers and streams are closed.
public static void readDataFile(String dir, String file1, String file2)
throws IOException
{
File datafile1 = new File(dir, file1);
File datafile2 = new File(dir, file2);
if (datafile1.exists())
{
BufferedReader r = null;
try
{
r = new BufferedReader(
new InputStreamReader(
new FileInputStream(datafile1),
"UTF-8"
)
);
String row;
Stack<Object[]> s = new Stack<Object[]>();
String[] pair;
Integer datapoint;
while((row = r.readLine()) != null)
{
if (row != null && row.trim().length() > 0)
{
// You could use " " instead of "\\s"
// but the latter regular expression
// shorthand-character-class will
// split the row on tab-symbols, too
pair = row.split("\\s");
if (pair != null && pair.length == 2)
{
datapoint = null;
try
{
datapoint = Integer.parseInt(pair[1], 10);
}
catch(NumberFormatException f) { }
// Later you can validate datapairs
// by using
// if (s.pop()[1] != null)
s.add(new Object[] { pair[0], datapoint});
}
}
}
}
catch (UnsupportedEncodingException e1) { }
catch (FileNotFoundException e2) { }
catch (IOException e3) { }
finally
{
if (r != null) r.close();
}
}
// Do something similar with datafile2
if (datafile2.exists())
{
// [...do the same as in the first try/catch block...]
String firstrow = null, lastrow = null;
String row = null;
int i = 0;
do
{
lastrow = row;
row = r.readLine();
if (i == 0)
firstrow = row;
i++;
} while(row != null);
// [...parse firstrow and lastrow into a datastructure...]
}
}
use split
while ((line = bufferReader.readLine()) != null)
{
String[] tokens = line.split(" ");
System.out.println(line + " -> [" + tokens[0] + "]" + "[" + tokens[1] + "][" + tokens[2] + "]");
}
if you must have this in an array you can use the following:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
public class NodeTest {
public static void main(String[] args) throws ParseException {
try {
File first = new File("data.txt");
File second = new File("data1.txt");
Node[] nodes1 = getNodes(first);
Node[] nodes2 = getNodes(second);
print(nodes1);
print(nodes2);
}
catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
}
public static final void print(Node[] nodes) {
System.out.println("======================");
for(Node node : nodes) {
System.out.println(node);
}
System.out.println("======================");
}
public static final Node[] getNodes(File file) throws IOException {
FileReader inputHeuristic = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
List<Node> list = new ArrayList<Node>();
while ((line = bufferReader.readLine()) != null) {
String[] tokens = line.split(" ");
list.add(new Node(tokens[0], tokens[1]));
}
bufferReader.close();
return list.toArray(new Node[list.size()]);
}
}
class Node {
String start;
String end;
public Node(String start, String end){
this.start = start;
this.end = end;
}
public String toString() {
return "[" + start + "][" + end + "]";
}
}
Something like this?
HashSet<String> nodes = new HashSet<String>();
try(BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line = br.readLine();
while (line != null) {
String[] l = line.split(" ");
nodes.add(l[0]);
line = br.readLine();
}
}
try(BufferedReader br = new BufferedReader(new FileReader("data1.txt"))) {
String line = br.readLine();
while (line != null) {
String[] l = line.split(" ");
if (nodes.contains(l[0]) || nodes.contains(l[1]))
// Do whatever you want ...
line = br.readLine();
}
}
My data file looks like this( 1st column-x; 2nd-y; 3rd-type):
46 80 2
95 75 2
78 85 2
59 54 1
81 52 2
57 78 1
72 46 2
I am trying to save x and y coordinates in two different arraylists of points depending on their type.
import java.util.*;
import java.util.ArrayList;
import java.io.*;
import java.awt.Point;
public class program {
public static void main(String []args) {
ArrayList knots = new ArrayList<Point>();
ArrayList zeros = new ArrayList<Point>();
List<Integer> list = new ArrayList<Integer>();
String line = null;
String file = "hepatitis_data1.txt";
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {
String tmp[] = line.split(" +");
System.out.println(line);
for (String s:tmp) {
s = s.trim();
if(s.length() > 0) {
int i = Integer.parseInt(s.trim());
int r = Integer.parseInt(tmp[1].trim());
int g = Integer.parseInt(tmp[2].trim());
if (tmp[3].equals("1")) {
knots.add(new Point(r,g));
}
else if(tmp[3].equals("2")) {
zeros.add(new Point(r,g));
}
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int total = knots.size() + zeros.size();
System.out.println("knot size" + knots.size());
System.out.println("zero size" + zeros.size());
System.out.println("total size" + total);
}
}
It doesn't show any error, but its not doing the right thing either. Total value should be 83 as I have 83 pairs of x-y coordinates, but total comes 240.
Any help??
you are doing a while statement to read the file, and in it, for each line you do a for loop. for each line the for loop is happening 3 times(!!!!) that's exactly the problem right there. do:
import java.util.*;
import java.util.ArrayList;
import java.io.*;
import java.awt.Point;
public class program {
public static void main(String []args) {
ArrayList knots = new ArrayList<Point>();
ArrayList zeros = new ArrayList<Point>();
List<Integer> list = new ArrayList<Integer>();
String line = null;
String file = "hepatitis_data1.txt";
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {
String tmp[] = line.split(" +");
System.out.println(line);
String s = tmp[0];
s = s.trim();
if(s.length() > 0) {
int i = Integer.parseInt(s.trim());
int r = Integer.parseInt(tmp[1].trim());
int g = Integer.parseInt(tmp[2].trim());
if (tmp[3].equals("1")) {
knots.add(new Point(r,g));
}
else if(tmp[3].equals("2")) {
zeros.add(new Point(r,g));
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int total = knots.size() + zeros.size();
System.out.println("knot size" + knots.size());
System.out.println("zero size" + zeros.size());
System.out.println("total size" + total);
}
}
I think below code repeats three time every lines it add data into either knots and zeros (3 times). So you get 240 is total value;
for (String s:tmp) {
s = s.trim();
if(s.length() > 0) {
int i = Integer.parseInt(s.trim());
int r = Integer.parseInt(tmp[1].trim());
int g = Integer.parseInt(tmp[2].trim());
if (tmp[3].equals("1")) {
knots.add(new Point(r,g));
}
else if(tmp[3].equals("2")) {
zeros.add(new Point(r,g));
}
}
it may help
thanks
I got it to work with the sample data you provided, as stated before it had to do with the enhanced for loop you were using it was running through more times than it needed increasing the size of your ArrayLists. My revision:
import java.util.*;
import java.util.ArrayList;
import java.io.*;
import java.awt.Point;
public class program {
public static void main(String []args) {
ArrayList knots = new ArrayList<Point>();
ArrayList zeros = new ArrayList<Point>();
List<Integer> list = new ArrayList<Integer>();
String line = null;
String file = "hepatitis_data1.txt";
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null) {
String tmp[] = line.split(" +");
System.out.println(line);
int x = Integer.parseInt(tmp[1].trim());
int y = Integer.parseInt(tmp[2].trim());
int type = Integer.parseInt(tmp[3].trim());
if(type == 1)
knots.add(new Point(x,y));
if(type == 2)
zeros.add(new Point(x,y));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int total = knots.size() + zeros.size();
System.out.println("knot size " + knots.size());
System.out.println("zero size " + zeros.size());
System.out.println("total size " + total);
}
}
A suggestion I could make to you is to you Scanner instead of BufferedReader in this particular case. Scanner has the nextInt() method you could use to directly read the ints without having to parse any Strings
longlat files:
101.2425101.2334103.345
The coding have algorithm like this:
ArrayList<String> getDifferenceList(String filePath) {
File f = new File("longlat.txt");
String line, x1 = null, x2= null, x3 = null;
BufferedReader buffreader = null;
try {
buffreader = new BufferedReader(new FileReader(f));
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split("");
x1 = (parts[0]);
x2 = (parts[1]);
x3 = (parts[2]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> ret = new ArrayList<String>();
FileWriter writer;
if (x1 == null || x1.isEmpty()
|| x2 == null || x2.isEmpty()
|| x3 == null || x3.isEmpty()) {
ret.add(x1);
ret.add(x2);
ret.add(x3);
return ret;
}
int index = 0;
while (index < x1.length()
&& index < x2.length()
&& index < x3.length()) {
if (x1.charAt(index) != x2.charAt(index)
|| x1.charAt(index) != x3.charAt(index)) {
break;
}
index++;
}
ret.add(x1.substring(index, x1.length()));
ret.add(x2.substring(index, x2.length()));
ret.add(x3.substring(index, x3.length()));
return ret;
}
The values need to be stored into text file are inside the arraylist of ret.
I've tried :
FileWriter writer = new FileWriter("lalala.txt");
for(String str: ret) {
writer.write(str);
} writer.close();
I put the above coding at the top of :
ret.add(x1.substring(index, x1.length()));
Problem : Nothing shown when I click a button "Show lalala text".
and also tried :
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput ("lalala.txt",MODE_APPEND));
String text =(ret);
out.write(text);
out.write('\n');
out.close();
}
catch (java.io.IOException e) {
Toast.makeText(this,"Sorry Text could't be added",Toast.LENGTH_LONG).show
();}
}
I put the above coding at the top of :
ret.add(x1.substring(index, x1.length()));
Problem : Error at 'ret'. It said "Type mismatch: cannot convert from ArrayList to String"
I don't know how to take the arraylist and stored them into text file.
Please give me some ideas, thanks.
ArrayList<String> cannot be cast to String.
You can write the content of the ArrayList to a file in this way:
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("lalala.txt"));
for (String text : ret) {
out.writeln(text);
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
out.close();
}
}
You are writing file before writing to your array List ret
I put the above coding at the top of :
ret.add(x1.substring(index, x1.length()));
Your ret is empty before this line. Your if-condition evaluates true then it actually returns from there.
if-condition evaluates false. then you have empty array list.
There fore write to file after you have fully filled your arrayList.
i.e. just before return statement.
return ret;