【问题标题】:Writing a simple loop [closed]编写一个简单的循环[关闭]
【发布时间】:2013-10-13 20:18:13
【问题描述】:

嘿,所以我正在编写一个程序,用户输入正好 10 个单词,计算机输出每个包含 Aa 的单词。我在一些帮助下编写了程序,现在我需要知道如何使用户可以通过 while 循环连续输入 10 个单词。这是我到目前为止所拥有的。

import java.util.Scanner;

public class ReadASH{ 
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);

        String name;
        String S="";
        System.out.println("Please enter any word.");
        S = in.nextLine();
        if(S.contains("a")||S.contains("A"))
          System.out.println(S);
        else System.out.println("The word you entered contains no a's or A's");
    }
}

【问题讨论】:

  • 了解如何使用调试器。
  • 你的循环在哪里?做一个for(int i=0;i<10;i++)
  • 您面临的具体问题是什么?有时提出问题可以帮助您找到答案!
  • @nachokk 我应该在代码中的哪个位置添加循环?另外我认为它应该是一段时间而不是一个。但是,如果一段时间内不可能,那也没关系。
  • @Meesh 我的问题是如何以及在哪里添加循环以便用户可以输入 10 个单词。

标签: java arrays loops output


【解决方案1】:

您实际上需要有一个循环,例如:

import java.util.Scanner;

 public class ReadASH{ 
   public static void main(String[] args){
     Scanner in = new Scanner(System.in);

    String name;
    String S;
    for (int i=0; i<10; i++) {
      System.out.println("Please enter any word.");
      S = in.nextLine();
      if (S.contains("a")||S.contains("A"))
        System.out.println(S);
      else System.out.println("The word you entered contains no a's or A's");
    }
  }
}

根据评论更新代码:

import java.util.Scanner;

 public class ReadASH{ 
   public static void main(String[] args){
     Scanner in = new Scanner(System.in);

    String name;
    int wordsToRead = 10;
    String words[] = new String[wordsToRead];

    for (int i=0; i< wordsToRead; i++) {
      System.out.println("Please enter any word.");
      words[i] = in.nextLine();
    }
    for (int i=0; i< wordsToRead; i++) {
      if (words[i].contains("a")||words[i].contains("A"))
        System.out.println(words[i]);
    }
  }
}

【讨论】:

  • 谢谢!这有很大帮助,但我想知道是否可以在用户首先输入所有十个单词然后计算机输出然后返回的地方编写它。 (例如,用户输入“篮球,球,门,赛车,苹果,蚂蚁,精确,湿,不喜欢”,然后计算机输出“篮球,赛车,球,苹果,蚂蚁”
  • @ShadonHamedani 您想将结果存储在一个数组中,然后遍历该数组。
  • 看起来不错,但现在当我尝试运行它时,我收到一条错误消息“java.lang.ArrayIndexOutOfBoundsException: 10 at HWReadASH.main(HWReadASH.java:13)”
  • @ShadonHamedani Mea Culpa!!索引查找应该使用循环索引!
  • 那么我们究竟该如何修复它呢?
猜你喜欢
  • 2019-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
  • 2012-10-20
  • 1970-01-01
相关资源
最近更新 更多