计数元音 - 扫描仪,字符串

时间:2014-03-25 23:03:50

标签: java.util.scanner

我完全迷失在这里做什么。如何使要处理的字符串不作为命令行参数输入, 而是作为从标准输入读取的一行文本,并提示带问号?

当前代码

import java.util。*;

公共类CountVowels {

public static void main (String[] args) {
        if (args.length ==1) {
        String str = args [0];
        int ofVowels = 0;
    for(int i=0;i <str.length();i++){
        if((str.charAt(i) == 'a') || 
            (str.charAt(i) == 'e')  ||
            (str.charAt(i) == 'i') || 
            (str.charAt(i) == 'o') ||
            (str.charAt(i) == 'u')) {
            ofVowels ++;


        }

    }
    System.out.println(" In The String  "+str+", there are "+ofVowels+" vowels");
}
}
}

1 个答案:

答案 0 :(得分:1)

首先,您需要import java.util.Scanner;

然后你去:

Scanner s = new Scanner(System.in); // create and attach the scanner
System.out.println("?");
String str = s.nextLine(); // gets what the user typed

修改:添加到您的代码中,这样就可以了:

Scanner s = new Scanner(System.in); // create and attach the scanner
System.out.println("?");
String str = s.nextLine(); // gets what the user typed
int ofVowels = 0;
for(int i=0;i <str.length();i++){
    if((str.charAt(i) == 'a') || 
        (str.charAt(i) == 'e')  ||
        (str.charAt(i) == 'i') || 
        (str.charAt(i) == 'o') ||
        (str.charAt(i) == 'u')) {
        ofVowels ++;
    }
}
System.out.println(" In The String "+str+", there are "+ofVowels+" vowels");