【问题标题】:How to access variables in for-loop如何在for循环中访问变量
【发布时间】:2015-03-31 03:12:57
【问题描述】:

我正在使用for-loop 中的扫描仪扫描数字和姓名。如何访问这些变量并在for-loop 之外使用其中的内容?还是没有办法?

       for(int i = 0; i < 5; i++)
       {
           int height = scanner.nextInt();
           int weight = scanner.nextInt();
           String name = scanner.nextLine();
       } 

【问题讨论】:

  • 40 分钟前在您删除的问题中给出了答案!
  • @AndersonGreen 他删除了它并再次询问。我不知道他在和我们玩什么游戏,但如果是忽视或抹杀别人的努力,我不想参与。
  • 上一篇文章我在 for 循环中实例化了一个对象,并尝试在它之外调用该对象的方法。我删除了帖子,因为我不知道我可以编辑我的代码/问题。 @HovercraftFullOfEels
  • 答案是一样的。
  • @HovercraftFullOfEels 我绝不是试图破坏其他人的努力。

标签: java variables object for-loop java.util.scanner


【解决方案1】:

请不要将变量的范围限制在for循环中,如果你想在外部使用它,可能你应该声明外部的引用并在for循环中初始化。

【讨论】:

    【解决方案2】:

    在 for 循环之外创建变量。然后您可以从外部访问它们。只需阅读有关 java 中变量的范围。 This 值得一读。

    int height, weight;
    String name;
    
    for(int i = 0; i < 5; i++){
        height = scanner.nextInt();
        weight = scanner.nextInt();
        name = scanner.nextLine();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-07
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 2021-04-07
      • 1970-01-01
      • 2019-02-09
      相关资源
      最近更新 更多