2014-09-06 63 views
1

我现在在学习Java,并且遇到问题。该程序决定第三点是否在笛卡尔坐标系中的矩形内。第一点是矩形的左上角,第二点是右下角。你必须像这样输入:a b c d e f,其中左(a,b)和右(c,d)。 E和f是第三点的要点。我希望扫描器在6个整数后停止,因此不需要填写非整数,如'结束'。这是我的代码的一部分:如何在6次读取6个整数后停止扫描器?

import java.util.Scanner; 

public class Rectangle { 
    Scanner scanner = new Scanner(System.in); 

    void insideRectangle() { 

     int coordinate; 
     int a; 
     int b; 
     int c; 
     int d; 
     int e; 
     int f; 

     System.out.println("Please fill in the numbers (6 maximum), with spaces in between"); 

     a = 0; 
     b = 0; 
     c = 0; 
     d = 0; 
     e = 0; 
     f = 0; 

     while (scanner.hasNextInt()) { 
      coordinate = scanner.nextInt(); 
      a = coordinate; 
      coordinate = scanner.nextInt(); 
      b = coordinate; 
      coordinate = scanner.nextInt(); 
      c = coordinate; 
      coordinate = scanner.nextInt(); 
      d = coordinate; 
      coordinate = scanner.nextInt(); 
      e = coordinate; 
      coordinate = scanner.nextInt(); 
      f = coordinate; 
     } 

     if (a > c) { 
      System.out.println("error"); 
     } else if (b < d) { 
      System.out.println("error"); 
     } else if (e >= a && c >= e && f <= b && d <= f) { 
      System.out.println("inside"); 
     } else { 
      System.out.println("outside"); 
     } 
    } 
} 
+0

这'while'循环读6坐标上。只要杀死这个循环并保持身体。 (另外,你可以省去重复的'coordinate'变量,直接赋值给'a..f',甚至这些都应该被重构,但这在将来可能会有点用处。) – chrylis 2014-09-06 14:25:51

+1

只需删除循环。 – 2014-09-06 14:27:08

+0

感谢您的帮助,它工作。我刚刚开始这一周;-) – GastonM008 2014-09-06 14:35:47

回答

4

尝试:

int[] values = new int[6]; 
int i = 0; 
while(i < values.length && scanner.hasNextInt()) { 
    values[i++] = scanner.nextInt(); 
} 

然后数组包含你的6个值。

0

我喜欢@Jean Logeart的做法,但我会用一个for循环,而不是:

int[] values = new int[6]; 
for (int i = 0; i < values.length && scanner.hasNextInt(); ++i) { 
    values[i] = scanner.nextInt(); 
} 

为了完整起见,您可以指定数组值到您的abc变量来代码工作的其余部分:

int a = values[0]; 
int b = values[1]; 
int c = values[2]; 
int d = values[3]; 
int e = values[4]; 
int f = values[5]; 

注意,如果扫描仪发现,不到6个值这甚至会工作,因为数组值初始化为0

最后一个技巧:测试实现,您可以创建一个字符串的Scanner,例如:*每*环通

Scanner scanner = new Scanner("3 4 5 6 7 8 9 10 11"); 
相关问题