java - 如何在 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);
}
}
解决方案
您需要更改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]);
}
推荐阅读
- r - 编织 RMarkdown 文档时出现 YAML 错误 - 扫描仪错误
- linq - 如何在 linq 中与运营商一起使用英国格式的日期
- zend-framework - 如何为 SocialEngine 模块设置默认操作
- c# - 将 2 层架构转换为 3 层架构
- java - org.javalite.activejdbc.DBException:在环境属性文件中找不到配置:开发
- julia - Julia 中缺失值的类型,例如 NA_real_
- r - 应用于少数数据点时 gsub 出错
- android - 附加 PDF - Java.Lang.SecurityException:权限被拒绝
- php - Apache/Laravel 错误:分段错误 (11),/etc/apache2 中可能的核心转储
- php - 在 symfony 控制器中找不到文件