java - 如何使用while循环将字符串值放入从用户获得的字符串数组中
问题描述
我正在尝试从用户那里获取值并将这些值存储在字符串数组中。它可以通过for循环轻松实现。但是需要使用while循环来完成它。帮我解决这个问题。
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
String[] arr1 = new String[testCases];
for(int i=0; i<testCases;i++) {
String s = in.nextLine();
arr1[i]=s;
}
for(int i=0; i<testCases;i++) {
try {
Pattern.compile(arr1[i]);
System.out.println("Valid");
} catch(Exception e) {
System.out.println("Invalid");
}
}
解决方案
只需使用while循环:
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
String[] arr1 = new String[testCases];
int i = 0;
int n = testCases;
while(i < n)
{
String s = in.nextLine();
arr1[i] = s;
testCases--;
i++;
}
while(testCases < n)
{
try {
Pattern.compile(arr1[testCases]);
System.out.println("Valid");
} catch(Exception e) {
System.out.println("Invalid");
}
testCases++;
i--;
}
推荐阅读
- android - 在 Android Studio 中重新加载 Activity
- python - 在 Python 标签中使用 BeautifulSoup 进行网页抓取
- reactjs - TypeError:无法读取未定义的属性“联系人”
- arrays - 在这个 Ruby 案例中,“self”关键字引用了什么?
- file-extension - 打开 .grp .mps 和 .rsc .rsr
- html - Html 文件没有与我的 css 文件一起下沉?
- node.js - YAML 多行正则表达式修剪注释和空格
- html - 引导表单下拉验证
- bash - bash 在字符串后读取拆分文件
- ruby-on-rails - 如何使用 Arel 跨多态 has_one 关系进行查询