【问题标题】:How to put vowels/consonants into separate arrays and output the vowels and consonants?如何将元音/辅音放入单独的数组并输出元音和辅音?
【发布时间】:2020-04-02 06:39:23
【问题描述】:

我在为元音和辅音创建数组以及打印所有元音和辅音时遇到问题。请帮忙。我是 Java 新手 :(

public class VowCon {
 public static void main(String[] args) {
  String x;
  Scanner in = new Scanner(System.in);
  System.out.println("Please enter a STRING: ");
  x = in .nextLine();
  vowel = (a, e, i, o, u);
  char[] vowname = x.toCharArray();
  char[] consname = x.toCharArray();
 }
 for (int i = 0; i < x.length; i++) {
  input = x.CharAt(i);
  if (input == vowel) {
   vowname[] = input;
   else if (input != vowel) {
    consname[] = input;
   }
  }
 }
}
```![enter image description here](https://i.stack.imgur.com/aq3Sm.png)

【问题讨论】:

  • 请了解如何indent your code properly,帮助自己和他人。没有缩进基本上是不可能阅读代码的。您的 IDE 可以为您执行此操作。
  • vowel = a,e,i,o,u; - 你觉得这有什么作用?
  • 哦,对不起,我对数组很陌生,我还在学习这个
  • 抱歉缩进是复制粘贴问题:(
  • @AndyTurner:同意...离开 Java 太久了。也许这样的事情会起作用:用String vowel = "aeiou";替换这一行:vowel = a,e,i,o,u;(无论如何都不应该编译)和这个:if(input==vowel){if (vowel.contains(input))。您的代码中还有其他小错误(不允许编译),例如您需要修复的 vowname[]=inputconsname[]=input;

标签: java arrays string char


【解决方案1】:

请尝试以下代码。

 String input="This string contains your Input";

    String allVowel="a,e,i,o,u,A,E,I,O,U";
    List<String> vowelList=new ArrayList<>();
    List<String> constantList=new ArrayList<>();

    input.chars().mapToObj(c -> String.valueOf((char) c)).forEach(c->{
     if(allVowel.contains(c)){
       vowelList.add(c);
      }
     else if(!c.equals(" ")){
       constantList.add(c);
     }
    });

    String[] constantArray=constantList.toArray(new String[0]);
    String[] vowelArray=vowelList.toArray(new String[0]);
    System.out.println("Constants : "+Arrays.toString(constantArray));
    System.out.println("Vowel : "+Arrays.toString(vowelArray));

【讨论】:

  • 尝试在您的代码中使用扫描仪仍然有问题:(
  • 使用下面的代码来使用扫描仪它将起作用 ** Scanner sc = new Scanner(System.in); System.out.println("请输入字符串:");字符串输入=sc.nextLine(); **
  • @MikMik 你能分享一下你遇到了什么错误吗?
  • 我把错误的图像放在上面第一篇文章的代码中。请看最后一行...
  • @MikMik 你还没有导入类,所以在你的类声明上面写下导入语句,import java.util.*;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 2015-12-17
  • 2018-07-26
相关资源
最近更新 更多