【发布时间】:2018-10-18 07:33:56
【问题描述】:
我尝试编写代码,其中代码在读取数字 42 后停止处理输入。输入处的所有数字都是整数。在此代码中,要求用户给出他想要给出的输入数。但我是不知道如何在不询问用户他想输入多少数字的情况下接受输入。
import java.util.Scanner;
public class antarahac {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int pattern[] = new int[1];
pattern[0] = 42;
int max, ls, lp = 1;
System.out.println("enter the no. of values you want to enter");
ls = sc.nextInt();
int input[] = new int[ls];
for (int i = 0; i < ls; i++) {
input[i] = sc.nextInt();
}
max = ls - lp - 1;
boolean flag;
for (int i = 0; i < max; i++) {
flag = true;
for (int j = 0; j < lp && flag == true; j++) {
if (pattern[j] != input[j + i]) {
flag = false;
System.out.println("" + input[i]);
}
}
if (flag == true) {
break;
}
}
}
}
【问题讨论】:
-
while (!input.equals("endInput")) 例如。 if ( flag == true ) 可以重写为 if ( flag ) (不太可能包含类型错误
-
int input; while((input = sc.nextInt()) != 42)但您需要在不知道大小的情况下声明一个数组或学习使用List。 PS:为什么pattern使用 1 个单元格的数组?