Background info:
----------------------------------------------------------------
public class Point {
protected int x;
protected int y;
public Point(){
this.x = x;
this.y = y;
}
public String toString(){
return "" + x + " , " + y;
}
}
---------------------------------------------------------------
public class PointName extends Point {
private String name;
public PointName(String name, int x, int y){
super();
this.name = name;
}
public PointName() {
// TODO Auto-generated constructor stub
}
public String toString(){
return name + super.toString();
}
}
------------------------------------------------------------------------
我想创建一个名为最近点的应用程序,在此类中,数据由标准输入(键盘)提供。然后我想提供10个点(名称给定点),它将存储在一个向量中。然后将它们打印出来。此后再多一点,但我陷入了这个阶段,因为我不知道该怎么做。我欢迎所有可能的解决方案!!
我的解决方案,所以
public class ClosestPoint {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Write in the new point starting with name then x, y");
String name = "";
Integer x = 0;
Integer y = 0;
String nameGivenPoints[] = null; // List of points to create
String line = in.nextLine(); // info from the board
while(!line.endsWith("")){
nameGivenPoints = line.split("\r\n\r");
name = nameGivenPoints[0];
x = Integer.parseInt(nameGivenPoints[1]);
y = Integer.parseInt(nameGivenPoints[2]);
// Maybe a forloop here
PointName tenDifferentPunkts = new PointName(name, x, y);
System.out.println(tenDifferentPunkts.toString());
line = in.nextLine();
}
}
答案 0 :(得分:0)
试试这个:
PointName.java:
public class PointName extends java.awt.Point
{
private String name;
public PointName(String name, int x, int y)
{
super(x,y);
this.name = name;
}
public String toString()
{
return this.name + " : " + super.toString();
}
}
ClosestPoint.java:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class ClosestPoint
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
String line;
boolean done=false;
String error=null;
List<PointName> points=new ArrayList<PointName>();
do
{
System.out.println("Enter a new point in this format: name:x,y");
line=in.nextLine();
done=line.equals("");
if(!done) //Empty line terminates the loop
{
String [] parts=line.split(":");
if(parts.length==2)
{
String name=parts[0];
parts=parts[1].split(",");
if(parts.length==2)
{
try
{
PointName pn=new PointName(name,Integer.parseInt(parts[0]),Integer.parseInt(parts[1]));
points.add(pn);
}
catch(NumberFormatException ex)
{
error=ex.getMessage();
}
}else error="Invalid format";
}else error="Invalid format";
}
if(!done) done=error!=null; //If there was an error exit the loop
}while(!done); //Keep going until something sets the done flag
if(error!=null)
{
System.out.println("Error: "+error);
}
else
{
//The points are all stored in the points List object now - this just iterates through and prints them out
System.out.println("Here are the points you entered:");
for(PointName pn : points)
{
System.out.println(pn.toString());
}
}
}
}