另一种方法中的Java扫描程序
我正在为我的一个班级的实验室工作,因此我正在寻找更多的解释而不是实际的代码.
对于这项任务的一部分,我需要从用户读取数字,直到按下control-d.我在方法中有一个while循环,我也将扫描器传递给方法,这是我的主要方法: Scanner scan = new Scanner(System.in); System.out.println("Length:"); int length = 0; if(scan.hasNextInt()){ length = scan.nextInt(); } if(length<0 || length>100){ System.out.println("Length is not of the proper size"); scan.close(); return; } Double[] a1 = new Double[length]; Double[] a2 = new Double[length]; fillWithZeros(a1); fillWithZeros(a2); System.out.println("Enter the numbers to be multiplied:"); a1 = fillWithValues(a1,scan); a2 = fillWithValues(a2,scan); double total = calculateTotal(a1,a2); printVector(a1,"a1"); printVector(a2,"a2"); System.out.println("Total: " + total); scan.close(); 那么这是我的fillWithValues方法: public static Double[] fillWithValues(Double[] array,Scanner scan) { int numberOfElements = 0; while(scan.hasNextDouble()){ if(numberOfElements<array.length){ array[numberOfElements] = scan.nextDouble(); numberOfElements++; }else{ return array; } } return array; } 我遇到的问题是,当我按下Control-D时,它并没有像它应该那样结束输入流,但是我在上面有代码,它会结束输入流,所以有人可以解释为什么我遇到这个问题? 我只是将扫描程序声明为全局变量,但我不允许使用全局变量进行此分配. 解决方法
在上面的代码中,您正在使用
a1 = fillWithValues(a1,scan); a2 = fillWithValues(a2,scan); fillWithValues()基本上是这样做的 while(scan.hasNextDouble()){ ... } 这意味着,如果扫描程序观察到EOF字符(在Unix的情况下为CTRL-D),则scan.hasNextDouble()将返回false并且方法将终止 – 但是,程序会立即再次调用该方法,扫描程序将等待下一个双倍(如果再次按CTRL-D,程序最终也会在这种情况下终止). 如果用一次循环调用替换两个方法调用,则程序将在(首先任何唯一的)循环之后恢复并终止. 要解决这个问题,你可以让方法返回一个布尔值而不是数组(你不需要返回并重新分配数组作为返回值,因为你已经修改了作为参数传递的数组的数组元素): public static boolean fillWithValues(Double[] array,Scanner scan) { int numberOfElements = 0; while(scan.hasNextDouble()){ if(numberOfElements<array.length){ array[numberOfElements] = scan.nextDouble(); numberOfElements++; }else{ return true; // all elements read } } return false; // input aborted } 然后,调用代码可以决定是终止还是继续: if (fillWithValues(a1,scan) == true) { fillWithValues(a2,scan); // could also check the return value again if required } 顺便说一下,只有在绝对需要时才使用静态方法 – 这里没有必要.一旦你的整体逻辑工作正常,你应该把它作为一个练习去除静态方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |