显示一系列至少十个四位数的客户ID和产品 D (存储在数组中)。 int[] cIds = {1111 2222 3333 4444 5555 1234 2345 3456 4567 5678};
int[]pIds={0
0 0 0,0,
0 0,0 0 0};
要求用户为客户输入某个产品ID (int介于1- -9999之间) 创建ProductException类,如果用户没有输入有效的产品ID (小于 或大于9999),则为该类抛出ProductException。 捕获ProductEx ception,显示适当的消息,然后为产品ID存储一个0。 在应用程序结束时,显示所有客户ID和产品ID。
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Demo {
public static void main(String[] args) {
//用户id
int[] cIds = {1111,2222,3333,4444,5555,1234,2345,3456,4567,5678};
//产品id
int[] pIds = new int[cIds.length];
//采集数据
Scanner scan = new Scanner(System.in);
System.out.println("请输入十个产品id");
for(int i=0;i< cIds.length;i++){
int j = scan.nextInt();
if(j<1||j>9999){
try {
//不知道为啥抛个异常,老板说抛就抛一下子吧
throw new ProductException("输入的数据异常");
} catch (ProductException e) {
System.out.println(e.getMessage());
pIds[i] = 0;
}
}else{
pIds[i] = j;
}
}
//输出结果
List<Integer> cIdList = Arrays.stream(cIds).boxed().collect(Collectors.toList());
List<Integer> pIdList = Arrays.stream(pIds).boxed().collect(Collectors.toList());
System.out.println(cIdList);
System.out.println(pIdList);
}
}
class ProductException extends RuntimeException{
public ProductException(String msg) {
super(msg);
}
}
解题代码如下:
public static void main(String[] args) {
int[] cIds = {1111, 2222, 3333, 4444, 5555, 1234, 2345, 3456, 4567, 5678};
int[] pIds = new int[cIds.length];
Scanner scanner = new Scanner(System.in);
// 遍历所有客户ID,为每个客户输入一个产品ID
for(int i=0; i<cIds.length; ++i) {
try {
int pId = scanner.nextInt();
// 如果产品ID不在范围内,则抛出异常
if(pId<1 || pId>9999) {
throw new ProductException();
}
pIds[i] = pId;
} catch (ProductException e) {
System.out.println("你输入的产品ID不在范围[1,9999]内");
pIds[i] = 0;
}
}
System.out.println("所有客户ID:" + Arrays.toString(cIds));
System.out.println("所有产品ID:" + Arrays.toString(pIds));
}
static class ProductException extends Exception {
}
如有帮助,请采纳,十分感谢!
回答很少,应该是 题目读不太懂.....
这是在数组中查找匹配的数据?