I'm trying to read coordinates from a file into an array.
Every coordinate has an id, an x-value and a y-value.
The file is in the following format: id position.x position.y
Example:
292961234 1376.42 618.056
29535583 3525.73 530.522
256351971 836.003 3563.33
20992560 4179.74 3074.27
Note: There are 4 lines containing a total of 4 coordinates.
I created the class Node and its constructor expects (int id, double x, double y).
And this is the class NodeList which is supposed to have an array attribute that saves the Nodes:
package .....;
import java.io.File;
import java.util.Iterator;
import java.util.Locale;
import java.util.Scanner;
public class NodeList implements Iterable<Node> {
private Node[] nodes = getNodes();
#Override
public Iterator<Node> iterator() {
return null;
}
public Node[] getNodes() {
Node[] result;
File f;
Scanner scanner;
try {
f = new File("nodes.txt");
Scanner s = new Scanner(f);
int ctr = 0;
while (s.hasNextLine()) {
ctr++;
s.nextLine();
}
result = new Node[ctr];
}
catch (Exception e) {
return null;
}
try {
scanner = new Scanner(f);
}
catch (Exception e) {
return null;
}
Locale.setDefault(new Locale("C"));
for(int i = 0; i < result.length; i++) {
int id = scanner.nextInt();
double x = scanner.nextDouble();
double y = scanner.nextDouble();
result[i] = new Node(id,x,y);
}
return result;
}
public static void main(String[] args) {
NodeList nl = new NodeList();
}
}
The Node class:
package ...;
public class Node {
private int id;
private double x;
private double y;
public Node(int id, double x, double y){
this.id = id;
this.x = x;
this.y = y;
}
public int getId(){
return id;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
}
When the method containing the shown code is called, I get the following
Exception:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at ......NodeList.getNodes(NodeList.java:40)
at ......NodeList.<init>(NodeList.java:9)
at ......NodeList.main(NodeList.java:47)
Process finished with exit code 1
Link to the file containing the nodes: https://pastebin.com/zhzp3DTi
It might be that it is using wrong locale.
I don't think "C" is a valid locale, it should be a language code.
You can try to use
scanner.useLocale(Locale.ROOT);
This is working on my machine:
public static void main(String[] args) {
// TODO code application logic here
String s = "292961234 1376.42 618.056\n" +
"29535583 3525.73 530.522\n" +
"256351971 836.003 3563.33\n" +
"20992560 4179.74 3074.27";
Scanner scanner = new Scanner(s);
scanner.useLocale(Locale.ROOT);
for(int i = 0; i < 4; i++) {
int id = scanner.nextInt();
double x = scanner.nextDouble();
double y = scanner.nextDouble();
System.out.println(id+" "+x+" "+y);
}
}
Related
What I want is if [1][0] is already in the list then if inputting [0][1] is considered as duplicate thus not adding it to the loop. That's the only thing that I wanted to accomplish and yet it seems impossible; at least for me.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class MatrixGraph{
List<List<Integer>> graph;
Scanner input = new Scanner(System.in);
ArrayList<Connection> Links = new ArrayList<Connection>();
boolean visited[];
int nodes;
int vertices;
int matrix[][];
class Node {
String name;
boolean visited;
ArrayList<Node> neighbors = new ArrayList<Node>();
Node(String name) {
this.name = name;
visited = false;
}
}
class Connection {
double fare;
Node source, destination;
Connection(Node source, Node destination) {
this.source = source;
this.destination = destination;
}
}
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of vertices");
int V = s.nextInt();
MatrixGraph amg = new MatrixGraph(V);
int n1 = V-1; int n2 = V*n1; int maxSize = n2/2;
while (true){
System.out.println("Enter the number of edges");
int E = s.nextInt();
if (E > maxSize){
System.out.println("Too Much Edges!");
continue;
}else{
System.out.print("\n");
for(int i=0;i<E;i++){
System.out.print("Source: ");
int mark = s.nextInt();
System.out.print("Destination: ");
int mac = s.nextInt();
if (mark == mac) {
System.out.println("\nERROR TRAPPED!!\nNo Loops Allowed Here!\nAdd New Edge!");
i--;
continue;
} else if(mark > (V-1)||mac > (V-1)) {
i--;
System.out.println("\nLOL No\n");
}
amg.addEdge(mark,mac);
amg.addEdge1(mark,mac);
}
}
}
}
MatrixGraph(int vertices){
graph = new ArrayList<>();
visited = new boolean[vertices];
this.vertices=vertices;
matrix=new int[vertices][vertices];
for (int i = 0; i < vertices; i++){
graph.add(i, new ArrayList<>());
}
}
public void addEdge(int source,int destination){
matrix[source][destination]= 1;
matrix[destination][source]= 1;
}
public void addEdge1(int a, int b) {
graph.get(a).add(b);
graph.get(b).add(a);
}
}
I want to take input from a file using the scanner class in Java. I want to read two coordinates of different cities from the file and then store them in an ArrayList of type City objects.
The input file format is as follows:
NAME : att48
COMMENT : 48 capitals of the US (Padberg/Rinaldi)
TYPE : TSP
DIMENSION : 5
EDGE_WEIGHT_TYPE : ATT
NODE_COORD_SECTION
1 6734 1453
2 2233 10
3 5530 1424
4 401 841
5 3082 1644
My sample code fragment is as follows: TourManager is a class containing an ArrayList of City objects. I haven't shown it here. City class contains every details (x,y coordinates) of a city.
try
{
Scanner in = new Scanner(new File("att48.tsp"));
String line = "";
int n;
//three comment lines
in.nextLine();
in.nextLine();
in.nextLine();
//get n
line = in.nextLine();
line = line.substring(11).trim();
n = Integer.parseInt(line);
City[] city= new City[n];
for (int i = 0; i < n; i++) {
city[i].x=0;
city[i].y=0;
}
//two comment lines
in.nextLine();
in.nextLine();
for (int i = 0; i < n; i++)
{
in.nextInt();
city[i].x = in.nextInt();
city[i].y = in.nextInt();
TourManager.addCity(city[i]);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
But I am getting a NullPointerException in the line.
city[i].x = in.nextInt();
Although I have initialized it by 0 previously, the code throws the NullPointerException.
For clarity, City class is as follows:
public class City {
int x;
int y;
// Constructs a city at chosen x, y location
public City(int x, int y){
this.x = x;
this.y = y;
}
}
Is there a problem in the code?
You are getting error because after doing :
City[] city= new City[n];
You have not allocated memory to individual city[i] elements.
You have to do something like this, but for this you need to add a default constructor to your city class as you are assigning x and y afterwards:
for (i=0;i <n ;i++){
city[i]= new City();
}
Add the following constructor in your City class:
public City(){
}
or I would suggest you to revise your City class:
public class City {
private int x;
private int y;
// Constructs a city at chosen x, y location
public City(int x, int y) {
this.setX(x);
this.setY(y);
}
public City() {
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
I am a beginner in Java and I get this java.util.InputMismatchException for the code I have written it below. The error is:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Graph.main(Graph.java:103)
Once debugging it gives the error when it is going to execute int size = scan.nextInt(); line in main methor. I would appreciate if anyone can help me with this.
import java.io.*;
enter code here`import java.util.*;
import java.util.Random;
public class Graph {
private int maxSize;
private Vertex[] nodes; // array of nodes
private int[][] mat; // adjacency matrix
private int N;
public Graph(int maxSize) {
this.maxSize = maxSize;
nodes = new Vertex[maxSize];
mat = new int[maxSize][maxSize];
for(int i=0; i<maxSize;i++)
for(int j=0; j<maxSize;j++) mat[i][j]=0;
}
public void addVertex(int x, int y) {
if (N >= maxSize) {
System.out.println("Graph full");
return;}
nodes[N++] = new Vertex(x , y);
}
public void addEdge(int v1, int v2) {
mat[v1][v2] = 1;
mat[v2][v1] = 1;
}
//public static void main(String args[]) throws IOException
public void readFile() throws IOException
{
int xcoord;
int ycoord;
Scanner scan = new Scanner("vertex.txt");
int size = scan.nextInt();
int count = 0;
while (scan.hasNext() && count<size) {
scan.nextLine();
nodes[count].setX(scan.nextInt());
nodes[count].setY(scan.nextInt());
count++;
}
//Reads the edges file
Scanner scanEdge = new Scanner("edges.txt");
size = scanEdge.nextInt();
count = 0;
int weight;
//fill out the adjacency matrix
while (scanEdge.hasNext() && count<size) {
scanEdge.nextLine();
xcoord = scanEdge.nextInt(); // "from" node
ycoord = scanEdge.nextInt(); // "to" node
mat[xcoord][ycoord]=scanEdge.nextInt(); //weigth of the link
mat[ycoord][xcoord] = mat[xcoord][ycoord]; //Symmetric matrix
count++;
scanEdge.nextLine();
}
return;
}
public static void main(String args[]){
EasyIn easy = new EasyIn();
// Prints menu
System.out.println();
System.out.println("Welcome to Maze Genrator App");
System.out.println("=============================");
System.out.println("Menu");
System.out.println("====");
System.out.println("1- Read Graph from File");
System.out.println("2- Generate a Graph using a Grid with Random weigths");
System.out.println("3- Compute the Minimum Spanning Tree");
System.out.println("0- Exit");
int command = -1;
while (command != 0) {
if (command > 0) {String pause = easy.readString();} //Creates a pause
System.out.println();
command = easy.readInt(); //Takes command
switch (command){
case 1:
//Reads the vertices file.
Scanner scan = new Scanner("vertex.txt");
int size = scan.nextInt();
//Reads the vertices file
Graph myGraph = new Graph(size);
//String fileName = easy.readString();
try{
myGraph.readFile();
}
catch(IOException e){
e.printStackTrace();
}
System.out.println("List of edges + weigths");
break;
case 0: //Exit command
break;
default:
System.out.println("Selection Invalid!- Try Again");
}
}
System.out.println("Goodbye!");
}
}
public class Vertex {
// The vertex coordinates
private int x;//label e.g. A,B
private int y;//label e.g. A,B
public boolean visited; //Wether the node is visited or not
public Vertex (int x, int y) {
this.x = x;
this.y = y;
visited = false;
}
//display x,y coordinates of the graph
public void display() {
System.out.println(x + " " + y);
}
//set x coordinate
public void setX(int x){
this.x = x;
}
//set y coordinate
public void setY(int y){
this.y = y;
}
}
Once debugging it gives the error when it is going to execute "int
size = scan.nextInt();" line
It means that the next token isn't an integer.
You may want to call and check the return value of scan.hasNextInt(), to prevent this Exception.
Documentation says :
public class InputMismatchException extends NoSuchElementException
Thrown by a Scanner to indicate that the token retrieved does not
match the pattern for the expected type, or that the token is out of
range for the expected type.
new Scanner("vertex.txt")
This is a Scanner which reads the passed String (and not a file with that name). Since this String contains a filename and not a number it will fail.
What you're looking for is:
new Scanner(new File("vertex.txt"))
This one will first create a 'File' instance with the given filename and then pass that to the Scanner, so it will actually read the content of this file.
The same applies to your Scanner for the "edges.txt".
I implemented two java classes to solve the percolation problem but it throws the following exception
java.lang.NullPointerException
at PercolationStats.<init>(PercolationStats.java:24)
at PercolationStats.main(PercolationStats.java:54)
Program:
public class PercolationStats {
int t=0;
double[] sample_threshold;
Percolation B;
int N1;
public PercolationStats(int N, int T) {
t=T;
N1 = N;
int number_of_open=0;
for(int i=0;i<T;i++) {
B=new Percolation(N1);
while(!B.percolates()) {
double r1 = Math.random();
int open_i = (int)(r1*N1);
double r2 = Math.random();
int open_j = (int)(r2*N1);
B.open(open_i,open_j);
}
for(int k=0;k<N1;k++) {
for(int j=0;j<N1;j++) {
if(B.isOpen(k, j))
number_of_open++;
}
sample_threshold[i] = (number_of_open*1.0)/N1;
}
}
}
public double mean() {
double sum = 0.0;
for(int i=0;i<N1;i++) {
sum += sample_threshold[i];
}
return sum/t;
}
public double stddev() {
double sum = 0.0;
double u = mean();
for(int i=0;i<N1;i++) {
sum += (sample_threshold[i]-u)*(sample_threshold[i]-u);
}
return sum/(t-1);
}
public double confidenceLo() {
return mean()-((1.96*Math.sqrt(stddev()))/(Math.sqrt(t)));
}
public double confidenceHi() {
return mean()+((1.96*Math.sqrt(stddev()))/(Math.sqrt(t)));
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
PercolationStats C=new PercolationStats(N,T);
double mean=C.mean();
double stddev = C.stddev();
double confidenceLo = C.confidenceLo();
double confidenceHi = C.confidenceHi();
System.out.println("mean = "+mean);
System.out.println("stddev = "+stddev);
System.out.println("95% confidence interval = "+confidenceLo+", "+confidenceHi);
}
}
You never initialized double[] sample_threshold;. Hence it is null.
Java will indeed fill a double[] with 0.0 once it is initialized to a known size. You must initialize the array first:
public PercolationStats(int N, int T) {
t=T;
N1 = N;
sample_threshold[i] = new double[T]; // add this line
int number_of_open=0;
for(int i=0;i<T;i++) {
B=new Percolation(N1);
while(!B.percolates()) {
double r1 = Math.random();
int open_i = (int)(r1*N1);
double r2 = Math.random();
int open_j = (int)(r2*N1);
B.open(open_i,open_j);
}
for(int k=0;k<N1;k++) {
for(int j=0;j<N1;j++) {
if(B.isOpen(k, j))
number_of_open++;
}
sample_threshold[i] = (number_of_open*1.0)/N1;
}
}
}
here at 3rd line where you've written double[] sample_threshold;
instead just write double[] sample_threshold= new double[5000];
meaning just initalize the array. Then when you use it in for loop java will only consider the arrays for the times your for loop loops.
I have been developing an implementation of the neighbourhood algorithm in Java for a physics project I am working on. I'm brand new to Java so I apologize for any idiocy that results.
I have been getting the error
''
incompatible types
found : void
required: java.util.List<VoronoiPoint>
'' on line 22 from the Java compiler in attempting to compile the program shown below. I cannot figure out why the variable ''thelist'' somehow turns into a void when I declared it to be of type List<VoronoiPoint>. If anybody can explain to me what is going on it would be much appreciated!
import java.lang.Double;
import java.util.*;
public class VoronoiTiling
{
public static void main(String args[])
{
Integer n = 10; //Number of dimensions of model parameter space
Integer ns = 20; //Number of points per iteration
Integer nr = 4; //Number of cells to populate
Integer iterations = 5; //Number of iterations
List<VoronoiPoint> thelist = VoronoiList.startlist(ns,n);
//System.out.println(thelist);
//System.out.println(thelist.get(1).misfit);
for (Integer i=0 ; i<thelist.size() ; i++)
{
thelist.get(i).setmisfit();
}
List<VoronoiPoint> orderedlist = Collections.sort(thelist);
Double distance = EuclidianDistance((thelist.get(1)).location,(thelist.get(2)).location);
System.out.println(distance);
}
public static Double EuclidianDistance(Double[] point1, Double[] point2)
{
Double distance=0.0;
for (int i = 0; i < point1.length; i++)
{
distance = distance + Math.pow((point1[i]-point2[i]),2);
}
return Math.sqrt(distance);
}
}
The other classes I used are here:
The VoronoiList class:
import java.util.*;
public class VoronoiList
{
public static List<VoronoiPoint> startlist(Integer ns, Integer n)
{
List<VoronoiPoint> thestartlist = new ArrayList<VoronoiPoint>();
for (int i = 0; i < ns; i++)
{
thestartlist.add(new VoronoiPoint(0.,n));
}
return thestartlist;
}
}
The VoronoiPoint class:
import java.util.Random;
public class VoronoiPoint implements Comparable<VoronoiPoint>
{
Double[] location;
private Random generator = new Random();
Double misfit = -1.;
//***************************************************************
public VoronoiPoint(Double misfit, Integer n)
{
location = new Double[n];
ParameterBoundaries boundaries = new ParameterBoundaries(n);
for(int i = 0; i < n; i++)
{
location[i] = boundaries.getboundaries(2*i)+2*generator.nextDouble();
}
}
//***************************************************************
//public Double[] getlocation()
//{
//return location;
//}
public void setlocationi(Integer i, Double j)
{
location[i] = j;
}
//***************************************************************
public void setmisfit()
{
Integer n = location.length;
Double tempmisfit = 0.0;
for(Integer i = 0; i < n; i++)
{
tempmisfit = tempmisfit + Math.pow((location[i]),2);
}
misfit = Math.sqrt(tempmisfit); // Temporarily just distance to centre
}
//public Double getmisfit()
//{
//return misfit;
//}
public int compareTo(VoronoiPoint b)
{
if (this.misfit<b.misfit) return -1;
else if (this.misfit==b.misfit) return 0;
return 1;
}
}
And the parameter boundaries class:
public class ParameterBoundaries
{
private Double[] boundaries; /*Set to 2n where n is dimensions of parameter space,
* it just makes it easier*/
public ParameterBoundaries(Integer n)
{
boundaries = new Double[2*n];
for(Integer i = 0; i<n; i++)
{
boundaries[2*i] = -1.0;
boundaries[2*i+1] = 1.0;
}
}
public Double getboundaries(Integer i)
{
return boundaries[i];
}
}
Collections.sort(..) sorts the original list. It doesn't return a new list. (Its return type is void)
Your code is wrong. Collections.sort() is an in-place sort function; it modifies the given list argument and returns nothing (void).