Getting 0.0 inbetween lines after parse and sort - java

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");
}

Related

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

Java Program Unable to read Commands

so, i'm making a round robin program and its all done but when i compile and run my code, it stops reading commands at some point but the compiler shows its running.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testing;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author User1
*/
public class Testing {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
try {
DataInputStream in=new DataInputStream(System.in);
int i,j,k,n, quantum;
Double burst,sum=0.0;
Double awt = 0.0, atat = 0.0;
ArrayList<Double> bt = new ArrayList<Double>();
ArrayList<Double> wt = new ArrayList<Double>();
ArrayList<Double> tat = new ArrayList<Double>();
ArrayList<Double> a = new ArrayList<Double>();
System.out.println("enter num of processes : ");
n=Integer.parseInt(in.readLine());
for(i=0; i<n; i++)
{
burst = Double.parseDouble(in.readLine());
bt.add(burst);
} // for loop
System.out.println("Array List bt : " + bt);
System.out.println("Time Quantum : ");
quantum = Integer.parseInt(in.readLine());
a.addAll(bt);
System.out.println("Array List a : " + a);
for (i=0; i<bt.size(); i++)
{
wt.add(0.0);
} // for loop
System.out.println("Array List wt : " + wt);
do
{ // do starts
for(i=0; i<bt.size()-1; i++)
{
if(bt.get(i) > quantum)
{
bt.set(i, bt.get(i) - quantum);
System.out.println("Array List bt after subtracting quantum: " + bt);
for(j=0; j<bt.size()-1; j++)
{
if(j != i && bt.get(j) != 0)
{
wt.add(wt.get(j) + quantum);
System.out.println("Array List wt after adding quantum and setting it to index of process : " + wt);
} // if statement
} // nested for loop
} // if statement.
else
{
for(j=0; j<bt.size(); j++)
{
if(j != i && bt.get(j) != 0)
{
wt.set(j, wt.get(j)+bt.get(j));
} // if statement
bt.add(0.0);
} // for loop
} // else statement
} // for loop
for(k=0; k<a.size(); k++)
{
sum = sum + a.get(k);
} // for loop
} // do ends
while(sum!=0);
{
for(i=0; i<a.size(); i++)
{
tat.add(wt.get(i) + a.get(i));
} // for loop
for (i=0; i<a.size(); i++)
{
awt = awt + wt.get(i);
} // for loop
for(i=0; i<a.size(); i++)
{
atat = atat + tat.get(i);
} // for loop
} // while loop
System.out.println("awt = " +awt+ "\n atat = "+atat);
} // main
catch (IOException ex) {
Logger.getLogger(Testing.class.getName()).log(Level.SEVERE, null, ex);
}
}
} // class
it should generate awt & atat in output.
i think somehow for loop is turning into infinite loop and thats the reason the program is unable to read other commands.
output :
enter num of processes :
4
enter burst time of 4processes :
15
7
19
18
Array List bt : [15.0, 7.0, 19.0, 18.0]
Time Quantum :
7
Array List a : [15.0, 7.0, 19.0, 18.0]
Array List wt : [0.0, 0.0, 0.0, 0.0]
Array List bt after subtracting quantum: [8.0, 7.0, 19.0, 18.0]
Array List wt after adding quantum and setting it to index of process : [0.0, 0.0, 0.0, 0.0, 7.0]
Array List wt after adding quantum and setting it to index of process : [0.0, 0.0, 0.0, 0.0, 7.0, 7.0]
this is the output i get

Spacing/aligning output of 2D array columns

I have these two methods that generate a 2D array of random values with no problems.
import java.util.concurrent.ThreadLocalRandom;
public class Guitar {
private int strings;
private int chords;
private double[][] song;
public Guitar(int mstrings, int mchords) {
this.strings = mstrings;
this.chords = mchords;
song = new double[mstrings+1][mchords];
}
public void generateSong() {
for (int i = 0; i < chords; i++) {
for (int j = 0; j < song[i].length; j++) {
song[i][j] = ThreadLocalRandom.current().nextDouble(27.5, 4186);
song[strings][j] = ThreadLocalRandom.current().nextDouble(0, 3);
if(song[i][j] == song[strings][j])
System.out.printf(" %.1f", song[i][j]);
else System.out.printf(" %.2f", song[i][j]);
}
System.out.println();
}
}
//prints out the same table just with rows and columns swapped
public void simulateSong() {
System.out.println("\nGuitar.simualateSong() ");
for (int i = 0; i < chords; i++) {
for (int j = 0; j < strings; j++) {
System.out.printf(" %.2f", song[j][i]);
}
System.out.println();
}
}
}
Here's the main which uses command line arguments to determine the size.
public class Songwriter {
public static void main(String[] args) throws InterruptedException {
System.out.println("Guitar(): Generated new guitar with " + args[0] + " strings. Song length is " + args[1] + " chords.");
String args0 = args[0];
int strings = Integer.parseInt(args0);
String args1 = args[1];
int chords = Integer.parseInt(args1);
Guitar guitarObj1 = new Guitar(strings, chords);
guitarObj1.generateSong();
guitarObj1.simulateSong();
}
}
My only problem is spacing/aligning the output. Here's a sample run with 3 and 4 as the arguments for number of rows and columns
Guitar(): Generated new guitar with 3 strings. Song length is 4 chords.
1103.75 1133.24 3559.35 330.26
744.83 3850.74 3493.20 1848.97
3908.79 2548.87 1771.52 2761.32
0.5 0.7 2.0 1.6
Guitar.simualateSong()
1103.75 744.83 3908.79
1133.24 3850.74 2548.87
3559.35 3493.20 1771.52
330.26 1848.97 2761.32
which I would like to format to output like so
Guitar(): Generated new guitar with 3 strings. Song length is 4 chords.
1103.75 1133.24 3559.35 330.26
744.83 3850.74 3493.20 1848.97
3908.79 2548.87 1771.52 2761.32
0.5 0.7 2.0 1.6
Guitar.simualateSong()
1103.75 744.83 3908.79
1133.24 3850.74 2548.87
3559.35 3493.20 1771.52
330.26 1848.97 2761.32
Any help is appreciated. Thanks.

Missing Format Argument Exception

When compiling I get a "java.util.MissingFormatArgumentException: null (in java.util.Formater) I do not know why.
"Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier 's'"
Please Help.
import java.lang.*;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class DartSimV1
{
static double[] SiXX(int Money)
{
double[] VarXX;
VarXX = new double[Money];
int IBS;
IBS = 0;
if (IBS < VarXX.length) {
do {
VarXX[IBS] = Math.random();
IBS++;
} while (IBS < VarXX.length);
}
return VarXX;
}
public static double[] SiYY(int Money)
{
double[] VarYY;
VarYY = new double[Money];
int IBS;
IBS = 0;
while (true) {
if (false) {
break;
}
if (!(IBS < VarYY.length)) {
break;
}
VarYY[IBS]=Math.random();
IBS++;
}
return VarYY;
}
public static double WhatPie(double[] IBS,double[] YYCoord)
{
double [] VarXX;
VarXX = IBS;
double [] VarYY;
VarYY = YYCoord;
double Totals;
Totals = 0;
double Contacts;
Contacts = 0;
int IBO;
IBO = 0;
if (IBO < VarXX.length) {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else Totals++;
IBO++;
if (IBO < VarXX.length) {
do {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else {
Totals++;
}
IBO++;
} while (IBO < VarXX.length);
}
}
double PIE;
PIE = 4 *
(Contacts
/
Totals);
return PIE;
}
public static void Answers(int Done, double New)
{
double PIE;
PIE = New;
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE);
}
public static void PieA(double[] New, int Done)
{
double[] PIE;
PIE = New;
int trials;
trials = Done;
double Totals;
Totals = 0.0;
int i;
i = 0;
if (i < PIE.length) {
double IBS;
IBS = PIE[i];
Totals += IBS;
i++;
if (i < PIE.length) {
do {
IBS = PIE[i];
Totals += IBS;
i++;
} while (i < PIE.length);
}
}
double PieA;
PieA = Totals/trials;
System.out.printf("AVG for π = %11.3f%s",PieA);
}
public static void main(String[] args)
{
Scanner show;
show = new Scanner(System.in);
System.out.print("# per trials?: ");
int dPt;
dPt = show.nextInt();
System.out.print("Trial #'s?: ");
int nTri;
nTri = show.nextInt();
double[] PieA;
PieA = new double[nTri];
int IBS=0;
while (IBS<nTri) {
double [] VarXX;
VarXX = SiXX(dPt);
double [] VarYY;
VarYY = SiYY(dPt);
double PIE;
PIE = WhatPie(VarXX,VarYY);
PieA[IBS]=PIE;
Answers(IBS,PIE);
IBS++;
}
PieA(PieA,nTri);
}
}
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE); has 2 parameters: one float %11.3f and one string %s. You've only given it one value to print PIE. It needs two - a float and a string.
Also: The exception gives you the full details of the problem - including the line number. You should include that in your question to give people the best chance of answering.

Reading double values from a file

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

Categories