Reading double values from a file - java

I'm trying to read some numbers (double) from a file and store them in an ArrayList and an array (yes, I need both) with the code below:
try {
Scanner scan = new Scanner(file).useDelimiter("\\s*\\n");
while(scan.hasNextDouble())
{
tmp.add(scan.nextDouble());
}
Double[][] tmp2 = new Double[tmp.size()/2][2];
int tmp3 = 0;
for(int i = 0; i < tmp.size()/2; i++)
{
for(int j = 0; j < 2; j++)
{
tmp2[i][j] = tmp.get(tmp3);
tmp3++;
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
The file I'm trying to read is:
0.0 0.0
0.023 0.023
0.05 0.05
0.2 0.2
0.5 0.5
0.8 0.8
0.950 0.950
0.977 0.977
1.0 1.0
But well my code doesn't work, the hasNextDouble() function doesn't find anything, what am I doing wrong?
EDIT: ok so I edited the source a bit (changed from Object[][] to Double[][]) and added inserting values into the array after they were inserted into the ArrayList, but it still doesn't work - the 'while' loop isn't executed a single time.

I tried reducing the code down to only test the Scanner by itself. The following code works with your data file:
public static void main(String[] args) {
Scanner scan;
File file = new File("resources\\scannertester\\data.txt");
try {
scan = new Scanner(file);
while(scan.hasNextDouble())
{
System.out.println( scan.nextDouble() );
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
I got the following (expected) output:
0.0
0.0
0.023
0.023
0.05
0.05
0.2
0.2
0.5
0.5
0.8
0.8
0.95
0.95
0.977
0.977
1.0
1.0
Try this to make sure you're referencing the correct file.

I had the same problem (not working scanner) and the solution seems to be surprisingly easy.
You just need to set a locale for it.
// use US locale to be able to identify doubles in the string
scanner.useLocale(Locale.US);
taken from here: http://www.tutorialspoint.com/java/util/scanner_nextdouble.htm

Below is my rendition of your code, adapted to make it run. It immediately explodes with an array indexing exceptions.
So: Can you give us a little more framework? What's different from what I did?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Zenzen {
private static ArrayList<Double> tmp = new ArrayList<Double>();
private static File file = new File("Zenzen.dat");
public static void main(String[] args) {
Scanner scan;
try {
scan = new Scanner(file);
Object[][] tmp2 = new Object[tmp.size() / 2][2];
int tmp3 = 0;
while (scan.hasNextDouble()) {
tmp.add(scan.nextDouble());
System.out.println(Arrays.deepToString(tmp.toArray())); // debug print
for (int i = 0; i < tmp.size() / 2; i++) {
for (int j = 0; j < 2; j++) {
tmp2[i][j] = tmp.get(tmp3);
tmp3++;
}
}
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
}
[0.0]
[0.0, 0.0]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Zenzen.main(Zenzen.java:26)

Try setting the delimiter first:
scan.useDelimiter("\\s+");
JavaDoc

Related

finding time complexity for the below java code

I have tried to find the time complexity for the below code but I am not sure whether it is right or not. can anyone help me on finding the time complexity for the below code. the code language is JAVA.
code:
// importing the necessary header files for the program
// header files are imported using the keyword import
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
//creating a class called "Partone". class can be created using the keyword class
public class Partone
{
public static void main(String[] args) throws IOException
{
// opening a file named "hikernet1"
File inputFile = new File("hikernet1.txt");
int maxTransmission = 0; //declaring maxTransmission as Integer data type and setting as 0
//reading the content of the file
Scanner reader = new Scanner(inputFile);
// inputCoordinatedAndTransmissionRange
String[] iCATR = reader.useDelimiter("\\A").next().replaceAll("\n", ",").replace("\r", "").split(",");
for (int i = 0; i < Integer.parseInt(iCATR[0]); i++)
{
int transmissions = 0; //declaring transmissions as integer data type and setting is as 0
String[] thisHiker = iCATR[i+1].split(" ");
int transMissionRange = Integer.parseInt(thisHiker[2]);
for (int j = 0; j < Integer.parseInt(iCATR[0]); j++)
{
int distance = (int) Math.sqrt(
Math.pow(Integer.parseInt(thisHiker[0])-Integer.parseInt(iCATR[j+1].split(" ")[0]), 2) + //x2-x1
Math.pow(Integer.parseInt(thisHiker[1])-Integer.parseInt(iCATR[j+1].split(" ")[1]), 2)); //y2-y1
if (distance<=transMissionRange)
{
transmissions++;
}
}
if (transmissions>maxTransmission) //checking the condition
{
maxTransmission = transmissions;
}
}
System.out.println(" The Maximum Transmission: "+maxTransmission);
//the outpit will be displayed in the hikernet1out file
FileWriter fw = new FileWriter("hikernet1out.txt"); //hikernet1out is the name of the output file
fw.write(""+maxTransmission);
fw.close(); //closing the file
reader.close(); //closing all the files
}
} //end of the program
any help would be appreciated much . thanks in advance.
Integer.parseInt(iCATR[0]); retruning any value let consider n.
The inner loop is running n times for every iteration of the outer loop.
The total number of nested loop itration = total number of iteration of outer loop . total number of iteration of inner loop = n * n = n^2
For each iteration nested loop doing O(1) operation.
Total time complexity = O(n^2)*O(1) = O(n^2).

Incorrect output for Project Euler #14 output

I'm trying to implement the algorithm to solve Project Euler Problem #14, which asks to find a number in a given range that outputs the largest Collatz conjecture sequence length. My code is below:
import java.util.ArrayList;
class Collatz {
private static ArrayList<ArrayList<Long>> previousNums = new ArrayList();
public static int seqLen(int x) {
ArrayList<Long> colSeq = new ArrayList();
long val = x;
colSeq.add(val);
while (val > 1) {
if (val%2 == 0) {
val/=2;
if (val < previousNums.size()) /*used to check if index exists*/{
colSeq.addAll(previousNums.get((int)val));
break;
}
else colSeq.add(val);
}
else {
val = 3*val + 1;
if (val < previousNums.size()) {
colSeq.addAll(previousNums.get((int)val));
break;
}
else colSeq.add(val);
}
}
previousNums.add(colSeq);
return colSeq.size();
}
public static void main(String[] args) {
int greatestNum = 0;
long totalVal = 0;
for (int i = 0; i<=1000000; i++) {
int collatz = seqLen(i);
if (collatz > totalVal) {}
greatestNum = i;
totalVal = collatz;
}
System.out.println(greatestNum + " " + totalVal);
}
}
The output I get is
1000000 153
While this is not the correct answer, 153 is the correct sequence length for 1 million. Based off of this, I could assume that my Collatz conjecture algorithm works, but not the comparison part. However, I can't really find anywhere else I could modify the code. Any ideas? Thank you and please pardon the possibility of this being a duplicate (not many other posts had the same problem).
Wow, a mere syntax error was the issue. Looks like I didn't pay attention to:
if (collatz > totalVal) {}
greatestNum = i;
totalVal = collatz;
Yup, didn't enclose the code with the braces.

How to format double to look like an integer in my programme? The chess board rice legend

If I run my programme it gives me double numbers, but in the end those numbers aren't like integers anymore because there is a point in them. Can you tell me how to format it or handle this? Thanks
package writingtofile;
import java.io.*;
import java.math.BigInteger;
public class WritingToFile {
public static void main(String[] args) throws IOException {
int counter = 1;
FileWriter out = null;
try{
out = new FileWriter("out.txt");
for(double number : FibanocciNumbers())
{
out.write("Spot:");
out.write(counter + " ");
out.write(String.valueOf(number) + "\r\n");
counter++;
}
}catch(IOException e)
{
System.out.println("Error!");
}
finally
{
out.close();
}
}
public static double[] FibanocciNumbers()
{
double[] fibNumbers = new double[64];
fibNumbers[0] = 1;
fibNumbers[1] = 2;
double lastNumber;
for(int i = 2; i < 64; i++)
{
lastNumber = fibNumbers[i-1];
fibNumbers[i] = lastNumber * 2;
}
return fibNumbers;
Spot:1 1.0
Spot:2 2.0
Spot:3 4.0
Spot:4 8.0
Spot:5 16.0
Spot:6 32.0
Spot:7 64.0
Spot:8 128.0
Spot:9 256.0
Spot:10 512.0
Spot:11 1024.0
Spot:12 2048.0
Spot:13 4096.0
Spot:14 8192.0
Spot:15 16384.0
Spot:16 32768.0
Spot:17 65536.0
Spot:18 131072.0
Spot:19 262144.0
Spot:20 524288.0
Spot:21 1048576.0
Spot:22 2097152.0
Spot:23 4194304.0
Spot:24 8388608.0
Spot:25 1.6777216E7
Spot:26 3.3554432E7
Spot:27 6.7108864E7
Spot:28 1.34217728E8
Spot:29 2.68435456E8
Spot:30 5.36870912E8
Spot:31 1.073741824E9
Spot:32 2.147483648E9
Spot:33 4.294967296E9
Spot:34 8.589934592E9
Spot:35 1.7179869184E10
Spot:36 3.4359738368E10
Spot:37 6.8719476736E10
Spot:38 1.37438953472E11
Spot:39 2.74877906944E11
Spot:40 5.49755813888E11
Spot:41 1.099511627776E12
Spot:42 2.199023255552E12
Spot:43 4.398046511104E12
Spot:44 8.796093022208E12
Spot:45 1.7592186044416E13
Spot:46 3.5184372088832E13
Spot:47 7.0368744177664E13
Spot:48 1.40737488355328E14
Spot:49 2.81474976710656E14
Spot:50 5.62949953421312E14
Spot:51 1.125899906842624E15
Spot:52 2.251799813685248E15
Spot:53 4.503599627370496E15
Spot:54 9.007199254740992E15
Spot:55 1.8014398509481984E16
Spot:56 3.6028797018963968E16
Spot:57 7.2057594037927936E16
Spot:58 1.44115188075855872E17
Spot:59 2.8823037615171174E17
Spot:60 5.7646075230342349E17
Spot:61 1.15292150460684698E18
Spot:62 2.305843009213694E18
Spot:63 4.6116860184273879E18
Spot:64 9.223372036854776E18
So I don't wnat those numbers with points in it, because I think it changes the way you should understand this. How to get them away or handle them? Tanks
This is your code using BigInteger. Its what you want, no decimal!!
also, double is not an integer, its like float but with capability to to hold large fractional numbers. btw you have named it FibanocciNumbers but those are not fibonnaci numbers
import java.io.*;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) throws IOException
{
int counter = 1;
FileWriter out = null;
try{
out = new FileWriter("out.txt");
for(BigInteger number : FibanocciNumbers())
{
out.write("Spot:");
out.write(counter + " ");
out.write(String.valueOf(number) + "\r\n");
System.out.println(number);
counter++;
}
}catch(IOException e)
{
System.out.println("Error!");
}
finally
{
out.close();
}
}
public static BigInteger[] FibanocciNumbers()
{
BigInteger[] fibNumbers = new BigInteger[64];
fibNumbers[0] = new BigInteger("1");
fibNumbers[1] = new BigInteger("2");
BigInteger lastNumber;
for(int i = 2; i < 64; i++)
{
lastNumber = fibNumbers[i-1];
fibNumbers[i] = lastNumber.multiply( new BigInteger("2") );
}
return fibNumbers;
}
}
last line of Output:
Spot:64 9223372036854775808

Getting 0.0 inbetween lines after parse and sort

Read a file that has a line of random doubles. Read the file, sort the numbers, return the file.
Did this all fine but when I print the sorted numbers I get a 0.0 in between each line. I'm guessing I have an empty string at the end which is why I tried adding trim(), but no luck. Any ideas? Code and output below
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class sortExample {
public static void main (String[] args) throws IOException {
String file = "C:\\Users\\xxxx\\Desktop\\new.txt";
Scanner sc = new Scanner(new FileReader(file));
String line;
while (sc.hasNext()) {
line = sc.nextLine();
line.trim();
String[] lineArray = line.split("\\s");
double[] nums = new double[lineArray.length];
if (lineArray.length > 0) {
for (int i = 0; i < lineArray.length; i++) {
if (!lineArray[i].isEmpty()) {
nums[i] = Double.parseDouble(lineArray[i]);
}}
Arrays.sort(nums);
}
for (int i = 0; i < nums.length-1; i++) {
System.out.print(nums[i] + " ");
}
System.out.print(nums[nums.length-1]);
System.out.print("\n");
}
System.exit(0);
}
}
Here is what I get when the code is run. All the numbers are sorted but I can't figure out why the 0.0 is there after each line. There is no final 0.0 as the System ends. Any ideas?
-91.232 -90.65 -81.425 -80.503 -50.68 -45.588 -23.141 -0.665 18.004 29.005 92.292 93.923
0.0
-100.835 -99.504 -80.183 -72.063 -71.447 -63.888 -47.389 -45.882 -37.815 -37.56 -22.952 -20.448 23.598 48.676 55.724 65.639 67.449 70.038
0.0
-78.977 -78.528 -72.272 -70.805 -64.709 -44.632 -42.855 -23.822 -22.273 -10.833 -1.157 7.712 21.619 21.935 23.442 37.869 42.056 78.46 94.735
0.0
-92.446 -84.111 -47.699 -23.366 -8.725 -1.679 7.685 23.537 32.703 67.569 68.633 72.266
0.0
-85.242 -83.407 -60.563 -47.319 -35.602 -22.979 -20.904 -16.537 25.004 55.298 69.193
0.0
-70.442 -39.916 -25.097 -8.729 -1.194 -0.043 7.086 11.874 19.538 35.647 44.886 52.162
0.0
-98.469 -80.931 -73.274 -55.879 -54.946 -54.695 -52.389 -45.66 -29.34 -12.44 -12.171 16.25 16.536 45.065 97.759
0.0
-65.594 -50.741 -49.607 -36.255 -27.512 -1.492 1.905 10.135 40.764 63.527 66.459 79.457 95.891
0.0
-75.088 -71.983 -64.298 -52.566 -33.779 -26.999 -19.76 -12.022 30.107 32.164 44.109 69.123 71.333
0.0
-100.822 -91.321 -58.742 -51.631 -6.001 -1.338 5.147 13.478 14.336 63.754 66.76 69.227
0.0
-100.729 -87.041 -51.238 -30.391 -19.053 -12.027 -1.812 9.104 38.951 41.738 45.416 57.447 80.157 94.37
0.0
-100.733 -96.084 -66.776 -64.397 -48.363 -38.223 11.665 13.101 22.904 30.637 40.223 61.489 67.105 86.601 98.225
0.0
-96.917 -71.136 -45.42 -45.24 39.232 43.879 51.401 52.31 57.029 76.001 99.577
0.0
-95.874 -91.529 -61.868 -56.623 -56.55 -43.048 -37.933 -33.65 -32.251 -31.507 -14.625 -1.828 34.268 59.821 60.48 73.106 75.763 89.408 89.551
0.0
-90.637 -77.109 -71.369 -64.957 -60.957 -52.252 -45.577 -34.413 -23.08 -22.805 27.066 34.148 39.28 81.409 90.394 91.746
0.0
-100.389 -99.758 -61.022 -26.942 -18.452 -14.1 -6.847 18.504 21.213 47.721 67.033 72.152
0.0
-86.559 -85.971 -80.617 -43.239 -41.397 -30.985 -22.344 -5.222 -3.042 3.629 7.885 24.202 33.706 58.209 67.877 92.776 96.691 98.549
0.0
-90.386 -79.406 -72.129 -56.667 -55.158 -54.217 -37.413 -28.465 8.949 14.774 24.166 24.632 34.977 35.126 59.208 80.778 84.792
0.0
-80.957 -60.479 -55.715 -30.557 -24.367 -10.497 -1.073 30.088 66.313 74.442 86.75 89.186
0.0
-88.962 -65.577 -44.427 -32.155 -32.106 -26.038 -22.205 -21.784 -14.312 -12.412 -5.275 10.442 12.684 33.622 33.838 41.632 50.094 67.565 75.008 89.463
If your input file has empty lines, it will print out "0.0". Try checking if the read line has a length greater than 0. For example:
if (line.length() > 0) {
String[] lineArray = line.split("\\s");
double[] nums = new double[lineArray.length];
if (lineArray.length > 0) {
for (int i = 0; i < lineArray.length; i++) {
if (!lineArray[i].isEmpty()) {
nums[i] = Double.parseDouble(lineArray[i]);
}
}
Arrays.sort(nums);
}
for (int i = 0; i < nums.length - 1; i++) {
System.out.print(nums[i] + " ");
}
System.out.print(nums[nums.length - 1]);
System.out.print("\n");
}

java print to file cuts last digit of number

i try to print values into a file but my results are cutted when longer then 4 digits:
import java.io.FileNotFoundException;
import java.math.BigInteger;
public class create_referencevalues {
/**
* #param args
*/
public static void main(String[] args) {
Long[] list = { 10L, 40L, 90L, 160L, 250L, 350L, 500L, 650L, 800L,
1000L };
try {
java.io.PrintStream p = new java.io.PrintStream(
new java.io.BufferedOutputStream(
new java.io.FileOutputStream(new java.io.File(
"C:/users/djdeejay/listall.csv"), false)));
for (long i = 0; i < 1024; i++) {
//p.print(Long.toBinaryString(i));
Long sum1 = 0L;
for (int j = 0; j < 10; j++) {
if (BigInteger.valueOf(i).testBit(j)) {
sum1 += (list[j]);
}
}
p.println( i + ";"+sum1);
}
p.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Here are the 5 last values as printed:
1018;3750
1019;3760
1020;3800
1021;3810
1022;3840
1023;3850
last should be: 38500
what do I miss here ???
There is nothing wrong with the println. Your code does exactly what I'd expect it to do. Consider the last line, which you claim isn't correct:
1023;3850
The decimal 1023 is 1111111111 in binary. Therefore when i=1023, the inner loop of your program would simply compute the sum of all numbers in list. These numbers add up to 3850, which is what gets printed.
The last one should actually be 3850 and not 38500. When i = 1023 all bits are set and the last line will be the same as if you add all numbers in list[] together.
1000+650+800+500+350+250+160+90+40+10 = 3850

Categories