首页 > 解决方案 > 如何使用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"); 
    }
} 

标签: javawhile-loop

解决方案


只需使用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--;
} 

推荐阅读