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
Related
So, i'm having trouble generating random numbers with uniform distribution in java, given the maximum and the minimun value of some attributes in some data set (Iris from UCI for machine learning). What i have is iris dataset, in some 2-d-array called samples. I put the random values according to the maximun and the minimun value of each attribute in iris data set (without the class attribute) in a 2-d-array called gworms (which has some extra fields for some other values of the algorithm).
So far, the full algorithm is not working properly, and my thoughts are in the fact that maybe the gworms (the points in 4-d space) are not generating correctly or with a good randomness. I think that the points are to close to each other (this i think because of some results obtained later whose code is not shown here). So, i'm asking for your help to validate this code in which i implement "uniform distribution" for gworms (for de first 4 positions):
/*
* 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 glowworms;
import java.lang.Math;
import java.util.ArrayList;
import java.util.Random;
import weka.core.AttributeStats;
import weka.core.Instances;
/**
*
* #author oscareduardo937
*/
public class GSO {
/* ************ Initializing parameters of CGSO algorithm ******************** */
int swarmSize = 1000; // Swarm size m
int maxIte = 200;
double stepSize = 0.03; // Step size for the movements
double luciferin = 5.0; // Initial luciferin level
double rho = 0.4; // Luciferin decay parameter
double gamma = 0.6; // Luciferin reinforcement parameter
double rs = 0.38; // Initial radial sensor range. This parameter depends on the data set and needs to be found by running experiments
double gworms[][] = null; // Glowworms of the swarm.
/* ************ Initializing parameters of clustering problem and data set ******************** */
int numAtt; // Dimension of the position vector
int numClasses; // Number of classes
int total_data; //Number of instances
int threshold = 5;
int runtime = 1;
/*Algorithm can be run many times in order to see its robustness*/
double minValuesAtts[] = new double[this.numAtt]; // Minimum values for all attributes
double maxValuesAtts[] = new double[this.numAtt]; // Maximum values for all attributes
double samples[][] = new double[this.total_data][this.numAtt]; //Samples of the selected dataset.
ArrayList<Integer> candidateList;
double r;
/*a random number in the range [0,1)*/
/* *********** Method to put the instances in a matrix and get max and min values for attributes ******************* */
public void instancesToSamples(Instances data) {
this.numAtt = data.numAttributes();
System.out.println("********* NumAttributes: " + this.numAtt);
AttributeStats attStats = new AttributeStats();
if (data.classIndex() == -1) {
//System.out.println("reset index...");
data.setClassIndex(data.numAttributes() - 1);
}
this.numClasses = data.numClasses();
this.minValuesAtts = new double[this.numAtt];
this.maxValuesAtts = new double[this.numAtt];
System.out.println("********* NumClasses: " + this.numClasses);
this.total_data = data.numInstances();
samples = new double[this.total_data][this.numAtt];
double[] values = new double[this.total_data];
for (int j = 0; j < this.numAtt; j++) {
values = data.attributeToDoubleArray(j);
for (int i = 0; i < this.total_data; i++) {
samples[i][j] = values[i];
}
}
for(int j=0; j<this.numAtt-1; j++){
attStats = data.attributeStats(j);
this.maxValuesAtts[j] = attStats.numericStats.max;
this.minValuesAtts[j] = attStats.numericStats.min;
//System.out.println("** Min Value Attribute " + j + ": " + this.minValuesAtts[j]);
//System.out.println("** Max Value Attribute " + j + ": " + this.maxValuesAtts[j]);
}
//Checking
/*for(int i=0; i<this.total_data; i++){
for(int j=0; j<this.numAtt; j++){
System.out.print(samples[i][j] + "** ");
}
System.out.println();
}*/
} // End of method InstancesToSamples
public void initializeSwarm(Instances data) {
this.gworms = new double[this.swarmSize][this.numAtt + 2]; // D-dimensional vector plus luciferin, fitness and intradistance.
double intraDistance = 0;
Random r = new Random(); //Random r;
for (int i = 0; i < this.swarmSize; i++) {
for (int j = 0; j < this.numAtt - 1; j++) {
//Uniform randomization of d-dimensional position vector
this.gworms[i][j] = this.minValuesAtts[j] + (this.maxValuesAtts[j] - this.minValuesAtts[j]) * r.nextDouble();
}
this.gworms[i][this.numAtt - 1] = this.luciferin; // Initial luciferin level for all swarm
this.gworms[i][this.numAtt] = 0; // Initial fitness for all swarm
this.gworms[i][this.numAtt + 1] = intraDistance; // Intra-distance for gworm i
}
//Checking gworms
/*for(int i=0; i<this.swarmSize; i++){
for(int j=0; j<this.numAtt+2; j++){
System.out.print(gworms[i][j] + "** ");
}
System.out.println();
}*/
} // End of method initializeSwarm
}
The main class is this one:
package uniformrandomization;
/**
*
* #author oscareduardo937
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import weka.core.Instances;
import glowworms.GSO;
public class UniformRandomization {
public UniformRandomization(){
super();
}
//Loading the data from the filename file to the program. It can be .arff or .csv
public static BufferedReader readDataFile(String filename) {
BufferedReader inputReader = null;
try {
inputReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException ex) {
System.err.println("File not found: " + filename);
}
return inputReader;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
BufferedReader datafile1 = readDataFile("src/data/iris.arff");
Instances data = new Instances(datafile1);
GSO gso = new GSO();
gso.instancesToSamples(data);
gso.initializeSwarm(data);
System.out.println("Fin...");
}
}
So i want to know if with this code, the numbers of the position ij of the gworms are generating within the range of max value and min value for attribute j.
Thanks so much in advanced.
My question to be solved is:
/** Maximize 4x+3Y
* Subject to
* 8x+6y <= 25
* 3x+4y <= 15
* x,y >= 0
*/
In theory LP Optimum of this question has unlimited # of solutions.
all required libraries, dependancies available at my google drive:
https://drive.google.com/file/d/0B84k1fZRHSMdak00TjZKNXBKSFU/view?usp=sharing
My code:
package testJOptimizer;
import com.joptimizer.functions.ConvexMultivariateRealFunction;
import com.joptimizer.functions.LinearMultivariateRealFunction;
import com.joptimizer.optimizers.JOptimizer;
import com.joptimizer.optimizers.OptimizationRequest;
/**
*
* #author K.P.L.Kanchana
*/
public class test_4_alternateOptimum {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
// BasicConfigurator.configure();
// Objective function (plane)
LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(new double[] {-4.0, -3.0}, 0); // maximize 4x+3y
//inequalities (polyhedral feasible set G.X<H )
ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[4];
// 8x+6y <= 25
inequalities[0] = new LinearMultivariateRealFunction(new double[]{8.0, 6.0}, -25); // 8x+6y-25<=0
// 3x+4y <= 15
inequalities[1] = new LinearMultivariateRealFunction(new double[]{1.0, 4.0}, -15); // 3x+4y-15<=0
// x >= 0
inequalities[2] = new LinearMultivariateRealFunction(new double[]{-1.0, 0.0}, 0);
// y >= 0
inequalities[3] = new LinearMultivariateRealFunction(new double[]{0.0, -1.0}, 0);
//optimization problem
OptimizationRequest or = new OptimizationRequest();
or.setF0(objectiveFunction);
or.setFi(inequalities);
//or.setInitialPoint(new double[] {0.0, 0.0});//initial feasible point, not mandatory
or.setToleranceFeas(1.E-9);
or.setTolerance(1.E-9);
//optimization
JOptimizer opt = new JOptimizer();
opt.setOptimizationRequest(or);
try {
int returnCode = opt.optimize();
}
catch (Exception ex) {
ex.printStackTrace();
return;
}
// get the solution
double[] sol = opt.getOptimizationResponse().getSolution();
// display the solution
System.out.println("Length: " + sol.length);
for (int i = 0; i < sol.length; i++) {
System.out.println("answer " + (i+1) + ": " + (sol[i]));
}
}
}
I found the issue with my code. To tell the truth I had some help from alberto trivellato. He is the person who develop JOptimizer as I know. I really really appreciate him for wasting his time to find the issue.
As he mentioned The issue was not with multiple solutions but with the high accuracy I'm asking to the solver. it is a best practice to not ask for more precision than you really need. Also remember that inequalities are always in the form of G.x < h, i.e. strictly less than(not less htan or EQUAL), because JOptimizer implements an interior points method solver.
Corrected code:
package testJOptimizer;
import com.joptimizer.functions.ConvexMultivariateRealFunction;
import com.joptimizer.functions.LinearMultivariateRealFunction;
import com.joptimizer.optimizers.JOptimizer;
import com.joptimizer.optimizers.OptimizationRequest;
/**
*
* #author K.P.L.Kanchana
*/
public class test_4_alternateOptimum {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
// BasicConfigurator.configure();
// Objective function (plane)
LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(new double[] {-4.0, -3.0}, 0); // maximize 4x+3y
//inequalities (polyhedral feasible set G.X<H )
ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[4];
// 8x+6y < 25(no equal sign)
inequalities[0] = new LinearMultivariateRealFunction(new double[]{8.0, 6.0}, -25); // 8x+6y-25<0
// 3x+4y < 15
inequalities[1] = new LinearMultivariateRealFunction(new double[]{1.0, 4.0}, -15); // 3x+4y-15<0
// x > 0
inequalities[2] = new LinearMultivariateRealFunction(new double[]{-1.0, 0.0}, 0);
// y > 0
inequalities[3] = new LinearMultivariateRealFunction(new double[]{0.0, -1.0}, 0);
//optimization problem
OptimizationRequest or = new OptimizationRequest();
or.setF0(objectiveFunction);
or.setFi(inequalities);
//or.setInitialPoint(new double[] {0.0, 0.0});//initial feasible point, not mandatory
or.setToleranceFeas(JOptimizer.DEFAULT_FEASIBILITY_TOLERANCE / 10); // There was the issue
or.setTolerance(JOptimizer.DEFAULT_TOLERANCE / 10); // There was the issue
//optimization
JOptimizer opt = new JOptimizer();
opt.setOptimizationRequest(or);
try {
int returnCode = opt.optimize();
}
catch (Exception ex) {
ex.printStackTrace();
return;
}
// get the solution
double[] sol = opt.getOptimizationResponse().getSolution();
// display the solution
System.out.println("Length: " + sol.length);
for (int i = 0; i < sol.length; i++) {
System.out.println("answer " + (i+1) + ": " + (sol[i]));
}
}
}
/*
* 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 sim;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import static jdk.nashorn.internal.objects.NativeMath.max;
/**
*
* #author admin
*/
public class Sim {
public String[][] bigramizedWords = new String[500][100];
public String[] words = new String[500];
public File file1 = new File("file1.txt");
public File file2 = new File("file2.txt");
public int tracker = 0;
public double matches = 0;
public double denominator = 0; //This will hold the sum of the bigrams of the 2 words
public double res;
public double results;
public Scanner a;
public PrintWriter pw1;
public Sim(){
intialize();
// bigramize();
results = max(res);
System.out.println("\n\nThe Bigram Similarity value between " + words[0] + " and " + words[1] + " is " + res + ".");
pw1.close();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Sim si=new Sim();
// TODO code application logic here
}
public void intialize() {
int j[]=new int[35];
try {
File file1=new File("input.txt");
File file2=new File("out.txt");
Scanner a = new Scanner(file1);
PrintWriter pw1= new PrintWriter(file2);
int i=0,count = 0;
while (a.hasNext()) {
java.lang.String gram = a.next();
if(gram.startsWith("question")|| gram.endsWith("?"))
{
count=0;
count-=1;
}
if(gram.startsWith("[")||gram.startsWith("answer")||gram.endsWith(" ") )
{
//pw1.println(count);
j[i++]=count;
count=0;
//pw1.println(gram);
//System.out.println(count);
}
else
{
// System.out.println(count);
count+=1;
//System.out.println(count + " " + gram);
}
int line=gram.length();
int sa_length;
//int[] j = null;
int refans_length=j[1];
//System.out.println(refans_length);
for(int k=2;k<=35;k++)
// System.out.println(j[k]);
//System.out.println(refans_length);
for(int m=2;m<=33;m++)
{
sa_length=j[2];
//System.out.println(sa_length);
for(int s=0;s<=refans_length;s++)
{
for(int l=0;l<=sa_length;l++)
{
for (int x = 0; x <= line - 2; x++) {
int tracker = 0;
bigramizedWords[tracker][x] = gram.substring(x, x + 2);
System.out.println(gram.substring(x, x + 2) + "");
//bigramize();
}
// bigramize();
}
}
}
bigramize();
words[tracker] = gram;
tracker++;
}
//pw1.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(Sim.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void bigramize() {
//for(int p=0;p<=sa_length;p++)
denominator = (words[0].length() - 1) + (words[1].length() - 1);
for (int k = 0; k < bigramizedWords[0].length; k++) {
if (bigramizedWords[0][k] != null) {
for (int i = 0; i < bigramizedWords[1].length; i++) {
if (bigramizedWords[1][i] != null) {
if (bigramizedWords[0][k].equals(bigramizedWords[1][i])) {
matches++;
}
}
}
}
}
matches *= 2;
res = matches / denominator;
}
}
I have tried the above code for bigramizing the words in the file "input.txt" i have got the result of bigram but i didnt get the similarity value.
for e.g:
input file contains as
answer:
high
risk
simulate
behaviour
solution
set
rules
[2]
rules
outline
high
source
knowledge
[1]
set
rules
simulate
behaviour
in the above example I have to compare the words under answer with every word under [2] as {high,rules} {high,outline} {high,high} {high,source} {high,knowledge} and I have to store the maximum value of the above comparison and again the second word from answer is taken and then similar process is taken. At last, mean of maximum value of each iteration is taken.
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");
}
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