写一个简单的循环

时间:2013-10-13 20:18:14

标签: java arrays loops output

嘿所以我正在编写一个程序,用户只输入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");
    }
}

1 个答案:

答案 0 :(得分:3)

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

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]);
    }
  }
}