I have a data file with 1000 data points that is organized like this:
1000
16 11
221 25
234 112
348 102
451 456
I'm trying to read the file into my program and find an arrangement of the points that results in the shortest total point to point distance. Since I have little experience with lists, I'm having a lot of trouble even reading the data points. Is there a better way to go about this? How do you run the list through a nearest neighbor algorithm?
public static void main(String[] args) throws IOException {
File file = new File("output.txt");
Scanner scanner = new Scanner(file);
ArrayList<shortestRoute> arrayList = new ArrayList<shortestRoute>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] fields = line.split(" ");
arrayList.add(new shortestRoute(Integer.parseInt(fields[0]), Integer.parseInt(fields[1])));
}
scanner.close();
System.out.println(arrayList);
}
I know that the formula for finding point to point distance is SquareRoot[(x2-x1)^2-(y2-y1)^2]. What I'm having trouble with is inputting the data points into the greedy algorithm.
You are splitting the input String using four spaces. Looking at the input file I assume that the numbers could also be separated by a tab. Rather using four spaces you should look for any white space. The split function should change like this:
String[] fields = line.split("\\s+");
I think it's because the first line is the number of points in the file.
Since it's all numbers just stick to using Scanner.
public static void main(String[] args) throws IOException {
File file = new File("output.txt");
Scanner scanner = new Scanner(file);
ArrayList<shortestRoute> arrayList = new ArrayList<shortestRoute>();
for(int i =0, n = scanner.nextInt(); i < n; i++) {
arrayList.add(new shortestRoute(scanner.nextInt(), scanner.nextInt()));
}
scanner.close();
System.out.println(arrayList);
}
Related
Hi everyone this is my first question here so I apologize in advance if it is not in the correct format for this forum. I'm a comp sci student and I am really a novice programmer. For an assignment, I need to read in a file of polynomials and then sort them from highest degree to lowest. On each line of the file I have a coefficient and an exponent separated by a space.
This is what my .txt file looks like:
"5.6 3
4 1
8.3 0" which represents the polynomial 5.6x^3 + 4x + 8.3
I have to scan the file from a JFileChooser and then add the tokens to an ArrayList of type Polynomial. My question/problem is how can I run the file contents through a for loop and separate the first token(coefficients) from the second token(exponents) and then add them to the ArrayList? I'm going to need the exponents to be of type int and the coefficients should be double.
This is what I have so far:
ArrayList aList = new ArrayList();
// scanner used to read each line
try {
scan = new Scanner(file);
if (file.isFile()) {
while (scan.hasNext()) {
for (int i = 0; i < something.size(); i++) {
//this is where I'm lost, not sure what I need to do here
}
}
}
....
Thank you guys I appreciate the assistance.
-Linden
EDIT:
Alright I figured it out, it was a lot more complicated than I thought. Here's what I did:
Scanner scan = new Scanner(file);
if (file.isFile()) {
for (int i = 0; i <=2; i ++) {
term(scan);
}
}
static void term(Scanner scan) {
String s = scan.nextLine();
String [] splitter = s.split(" ");
String coefficient = splitter[0];
String exponent = splitter[1];
//populating
try {
arrayList.add(new Polynomial(coefficient, exponent));
} catch (InvalidPolynomialSyntax e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thanks to the two guys that tried to help me out and the 24 viewers who didn't lol
First, you need to look at the scanner class. What methods does it have that you should use to get the data you need?
I don't want to give you the answer to your homework out of respect but broadly what you need is a way to get each line of that file from the scanner so you can compare the contents of each line to each other.
So look at the scanner class documentation and see what it has that you can use.
Start by simply trying to print out each line. Once you do that you can think about how you want to compare them.
you can read file as one sentence. First get all the text such as 5.6 3 4 1 8.3 0 as string. Then you can just use String [] arrayOfNumbers = yourString.split(" ");
This will split the string according to " " character so you get numbers directly.
i have a text file and i want to read the integers and doubles. I dont know how many values i have to read. The first value in the line is always the integer and the second is always the double. I want to save the value of the first line seperately.
200
11010 0.004
500 0.02
637 0.018
How to create 2 arrays and save the values, so i can use them later? I am not allowed to create a new class. I tried to use Point but cant store doubles.
Scanner scanner = new Scanner(new File(args[0]));
int cores= scanner.nextInt();
System.out.print(cores);
while (scanner.hasNext()) {
int x = scanner.nextInt();
double y = scanner.nextDouble();
System.out.printf("x");}
I' ve tried the code above but throws out Exception
You can use simple file handling approach to read the file line by line, For the first line you can use a flag to mark the line and sent the file to remote location you want to save the data. Then for all later lines you can split the string on the basis of " " (space). Post which once you have stripped the elements of the resulting array you can typecast and append the element at first index to integer array. And the second element (typecast before append) to the double array. This shall work absolutely fine with any length of file.
A demo code for the same is as following:
public class ReadLineByLine
{
public static void main(String args[])
{
try
{
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis);
String tempLineData = "";
int flag = 0;
String[] elements;
List<Integer> ints = new ArrayList<Integer>(
List<Float> floats = new ArrayList<Float>(
while(sc.hasNextLine())
{
if(flag == 0){
// Place the operation with the first line here
flag++;
}
tempLineData=sc.nextLine();
elements = tempLineData.split(" ");
ints.add((int)elements[0].trim());
floats.add((float)elements[1].trim());
}
sc.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
This is a project from school, but i'm only asking for help in the logic on one small part of it. I got most of it figured out.
I'm being given a file with lines of string integers, for example:
1234 123
12 153 23
1234
I am to read each line, compute the sum, and then go to the next one to produce this:
1357
188
1234
I'm stuck on the scanner part.
public static void doTheThing(Scanner input) {
int[] result = new int[MAX_DIGITS];
while(input.hasNextLine()) {
String line = input.nextLine();
Scanner linesc = new Scanner(line);
while(linesc.hasNext()) {
String currentLine = linesc.next();
int[] currentArray = convertArray(stringToArray(currentLine));
result = addInt(result, currentArray);
}
result = new int[MAX_DIGITS];
}
}
In a nutshell, I want to grab each big integer, put it an array of numbers, add them, and then i'll do the rest later.
What this is doing it's basically reading all the lines and adding everything and putting it into a single array.
What i'm stuck on is how do I read each line, add, reset the value to 0, and then read the next line? I've been at this for hours and i'm mind stumped.
Edit 01: I realize now that I should be using another scanner to read each line, but now i'm getting an error that looks like an infinite loop?
Edit 02: Ok, so after more hints and advice, I'm past that error, but now it's doing exactly what the original problem is.
Final Edit: Heh....fixed it. I was forgetting to reset the value to "0" before printing each value. So it makes sense that it was adding all of the values.
Yay....coding is fun....
hasNext method of the Scanner class can be used to check if there is any data available in stream or not. Accordingly, next method used to retrieve next continuous sequence of characters without white space characters. Here use of the hasNext method as condition of if doesn't make any sense as what you want is to check if the there are any numerical data left in the current line. You can use next(String pattern).
In addition, you can try this solution even though it is not optimal solution...
// In a loop
String line = input.nextLine(); //return entire line & descard newline character.
String naw[] = line.split(" "); //split line into sub strings.
/*naw contains numbers of the current line in form of string array.
Now you can perfom your logic after converting string to int.*/
I would also like to mention that it can easily & efficiently be done using java-8 streams.
An easier approach would be to abandon the Scanner altogether, let java.nio.io.Files to the reading for you and then just handle each line:
Files.lines(Paths.get("/path/to/my/file.txt"))
.map(s -> Arrays.stream(s.split("\\s+")).mapToInt(Integer::parseInt).sum())
.forEach(System.out::println);
If i were you i would be using the BufferedReader insted of the Scanner like this:
BufferedReader br = new BufferedReader(new FileReader("path"));
String line = "";
while((line = br.readLine()) != null)
{
int sum = 0;
String[] arr = line.split(" ");
for(String num : arr)
{
sum += Integer.parseInt(num);
}
System.out.println(sum);
}
Considering the level you're on, I think you should consider this solution. By using only the scanner, you can split the lines into an array of tokens, then iterate and sum the tokens by parsing them and validating that they're not empty.
import java.util.*;
class SumLines {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
while(S.hasNext()) {
String[] tokens = S.nextLine().split(" ");
int sum = 0;
for(int i = 0; i < tokens.length; i++) {
if(!tokens[i].equals("")) sum += Integer.parseInt(tokens[i]);
}
System.out.println(sum);
}
}
}
I'm trying to wrap my head around a problem I have in a programming set.
We're supposed to write code that reads from a file and prints it out. I get that, I can do it.
What he wants us to do is have it print out in reverse.
the file reads:
abc
123
987
He wants:
987
123
abc
The code, as it is, is as follows:
{
FileReader n=new FileReader("F:\\Java\\Set 8\\output1.txt");
Scanner in=new Scanner(n);
int l;
while (in.hasNext())
{
l=in.nextInt();
System.out.println(l);
}
in.close();
}
}
Yes, I am using java.io.*; and Scanner.
What would be the simplest way to do this?
EDIT EDIT EDIT
Here's the improved code, where I try to put it into an array.
The data in the array isn't printing out.
public static void main(String[] args) throws IOException
{
int[]Num=new int[20];
Scanner in=new Scanner(new FileReader("F:\\Java\\Set 8\\output1.txt"));
int k;
for (k=0;k<20;k++)
{
Num[k]=in.nextInt();
}
//in.close();
for (k=20;k<20;k--)
{
System.out.print(+Num[k]);
}
//in.close();
}
The most simplest way is to construct a List and add each line to the list while reading from the file. Once done, print the list items in reverse.
Here is my version of code for your problem.
public static void main(String[] args) throws FileNotFoundException {
FileReader n = new FileReader("/Users/sharish/Data/abc.xml");
Scanner in = new Scanner(n);
ArrayList<String> lines = new ArrayList<String>();
while (in.hasNext()) {
lines.add(in.nextLine());
}
in.close();
for (int i = lines.size() - 1; i >= 0; i--) {
System.out.println(lines.get(i));
}
}
Use Stack.
public static void displayReverse() throws FileNotFoundException {
FileReader n=new FileReader("C:\\Users\\User\\Documents\\file.txt");
Scanner in=new Scanner(n);
Stack<String> st = new Stack<String>();
while (in.hasNext()) {
st.push(in.nextLine());
}
in.close();
while(!st.isEmpty()) {
System.out.println(st.pop());
}
}
If you are permitted the use of third party APIs, Apache Commons IO contains a class, ReversedLinesFileReader, that reads files similar to a BufferedReader (except last line first). Here is the API documentation: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/ReversedLinesFileReader.html
Another (less efficient) solution is hinted at in the comments. You can read your entire file into an ArrayList, reverse that list (e.g. by pushing its contents onto a stack and then popping it off), and then iterate through your reversed list to print.
EDIT:
Here is a crude example:
ArrayList<String> lines = new ArrayList<String>();
Scanner in = new Scanner(new FileReader("input.txt"));
while (in.hasNextLine())
{
lines.add(in.nextLine());
}
Use an ArrayList instead of a static array. We don't necessarily know the length of the file in advance so a static array doesn't make sense here. http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Your example input 123, abc, etc, contains characters as well as ints, so your calls to hasNextInt and nextInt will eventually throw an Exception. To read lines use hasNextLine and nextLine instead. These methods return String and so our ArrayList also needs to store String. http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine()
Once the file is in a list (not a good solution if the file is large - we've read the entire file into memory) we can either reverse the list (if keeping a reversed form around makes sense), or just iterate through it backwards.
for (int i=lines.size()-1; i>=0; i--) // from n-1 downTo 0
{
String line = lines.get(i);
System.out.println( line );
}
public static void main(String[] args) throws Exception{
String fileName = "F:\\Java\\Set 8\\output1.txt";
RandomAccessFile raf = new RandomAccessFile(fileName,"r");
int len = (int) raf.length();
raf.seek(len);
while(len >= 0){
if(len == 0){
raf.seek(0);
System.out.println(raf.readLine());
break;
}
raf.seek(len--);
char ch = (char)raf.read();
if(ch == '\n'){
String str = raf.readLine();
System.out.println(str);
}
}
}
try using org.apache.commons.io.input.ReversedLinesFileReader, it should do what you want.
You could read the lines like you are already doing, but instead of printing them (because that would print them in order and you need it the other way around), add them to some memory structure like a List or a Stack, and then, in a second loop, iterate this structure to print the lines in the needed order.
Using your code and the answers in the comments, here's an example of how you would store the strings into the arraylist and then print them out in reverse (building off of your own code)
{
FileReader n=new FileReader("F:\\Java\\Set 8\\output1.txt");
Scanner in=new Scanner(n);
int l;
ArrayList<String> reversed = new ArrayList<String>(); // creating a new String arraylist
while (in.hasNext())
{
l=in.nextInt();
System.out.println(l);
reversed.add(l); // storing the strings into the reversed arraylist
}
in.close();
// for loop to print out the arraylist in reversed order
for (int i = reversed.size() - 1; i >= 0; i--) {
System.out.println(reversed.get(i));
}
}
}
Using Java 8:
try(PrintWriter out =
new PrintWriter(Files.newBufferedWriter(Paths.get("out.txt")))) {
Files.lines(Paths.get("in.txt"))
.collect(Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(out::println);
}
I want to organize a text file with multiple data
A 33 9.25
V 92 1.123
H 100 2.4
into a parallel Array
So far I got to declaring the arraylist and i know i need to do something with a while loop and hasnext... not sure where to go from there.
public static void main(String[] args) throws IOException
{
Scanner fileIn = new Scanner ( new File("sortdata.txt"));
ArrayList<Character> array1 = new ArrayList<Character>();
ArrayList<Integer> array2 = new ArrayList<Integer>();
ArrayList<Double> array3 = new ArrayList<Double>();
while (fileIn.hasNext())
String i = fileIn.next();
int k = 0;
for(i.index(k);i.length();i.index(k++))
if (i.index(k) =='.')
{
}
}
I know some of my code is wrong but I've been looking at it for a long time, think i'm just missing something minor here.
After reading each line from the file here String i = fileIn.next();, trim() the String(to eliminate leading and trailing white spaces as suggested by #X86) and then follow the below steps.
Split the String on white space using the String#split() method.
The String[] returned by the split method above contains all the 3 data required.
From the string[0] get the character using string.charAt(0) and put it into the Character ArrayList.
Parse string[1] as a Integer using Integer.parseInt(string[1]) and put it into the Integer ArrayList.
Parse string[2] as a Double using Double.parseDouble(string[2]) and put it into the Double ArrayList.
This should work:
while (fileIn.hasNextLine()) {
String c[]= fileIn.nextLine().split(" ");
array1.add(new Character(c[0].charAt(0)));
array2.add(new Integer(c[1].trim()));
array3.add(new Double(c[2].trim()));
}