从myScanner获取多个数据

时间:2011-10-21 04:32:48

标签: java java.util.scanner

我正在尝试同时抓取并存储(coordinate1,x1,y1)。

当有人进入2,3:

时,我正试图发生这种情况

coordinate =(2,3)

X1 = 2

Y1 = 3

    import java.util.Scanner;

    public class LinearSlopeFinder {
      public static void main(String[]args){
         double x1, y1 ;


         Scanner myScanner = new Scanner(System.in);

         System.out.print("    What is the first set of cordinants? ... ");
         String coordinate1 = myScanner.next();//this is the only thing 

                 //it stores

         x1= myScanner.nextInt();//need this from myScanner
         y1= myScanner.nextInt();//need this from myScanner


         System.out.println("your coordinates are " + coordinate1);
         System.out.println("x1 is "+ x1 );

    }
}

现在尝试拆分但仍然收到错误

import java.util.Scanner;

 public class LinearSlopeFinder {
public static void main(String[]args){
    int x1, y1, x2, y2, n1, equation, slope ;

    Scanner myScanner = new Scanner(System.in);

    System.out.print("    What is the first set of cordinants? ... ");
    String coordinate1 = myScanner.nextLine();
    String coordinates[] = coordinate1.split(",");
    x1 = coordinates[0];
    y1 = coordinates[1];

    System.out.println("your cordinants are " + cordinant1);
    System.out.println("x1 is "+ x1 );

     }
}

2 个答案:

答案 0 :(得分:1)

获取行myScanner.nextLine()并将其保存到coordiante1。 使用coordiante1作为分隔符(,)拆分String#split。演员(Integer#parseInt)&将第0个索引分配给x1,将第一个索引分配给y1

答案 1 :(得分:0)

我不确定您希望输入看起来像什么,但有各种方法可以使用Scanner类。查看API文档,以更好地了解此类的工作原理:J2SE6 Scanner API Documentation