首页 > 解决方案 > 如何在 for 循环中访问字符串值?

问题描述

name在这里,即使我使用未初始化的其他字符串,我也无法访问字符串外部的值。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("\n\tWelcome to the Store");
    System.out.print("\nPls enter the number of items you want to bill ");
    int n = sc.nextInt();
    String name;
    for(int i = 1;i<=100;i++) {
        System.out.print("Enter the name of the item no "+i+" ");
        name = sc.next();
        if (i == n) {
            break;
        }
    }
    System.out.println();   
    for(int m=1;m<=n;m++) {
        //System.out.println(name);        
    }    
}

标签: java

解决方案


您需要更改name为数组,因为它应该包含多个值。

String[] names = new String[n];

我也认为您应该改用while循环。就像是

Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
    System.out.print("Enter the name of the item no " + i + " ");
    names[i] = sc.next();
    i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
    System.out.println(names[m]);
}

推荐阅读