2014-11-08 4 views
-2

Я чувствую, что у меня есть большая часть проделанной программы. Я не верю, что я действительно понимаю, как работают петли. Я проверил, пытаясь исправить эту программу, но на данный момент я не знаю, с чего начать.Java - определение пробелов, гласных, цифр

Обновление * Наверное, я не совсем понял, что именно я делаю. Попытка создать методы для них индивидуально. Метод цифр, метод для гласных звуков и т.д. Я довольно новичка в этом, спасибо за помощь вы, ребята, давая до сих пор

{ 
    static Scanner kb = new Scanner(System.in); 

    public static void main (String[] args) 
    { 
String s; 
int x; 

System.out.println("Enter a String(EOF to end)"); 

s=kb.nextLine(); 

System.out.println(("You have entered ") + s.length() + ("characters and it contains the following")); 

System.out.println(whitespace + ("whitespace characters.")); 
System.out.println(digits + ("digits.")); 
System.out.println(letters + ("letters.")); 
System.out.println(vowels + ("vowels.")); 
} 

public static int whitespace(String s){ 
int x; 
int whitespace = 0; 
if (Character.isWhitespace(s.charAt(x))){ 
    for containsWhitespace=true{ 
    whitespace++;}} 

return whitespace;} 

    public static int digits(String s){ 
int digits = 0; 
int x; 
if (Character.isDigit(s.charAt(x))){ 
    return digits ++;}} 

    public static int letters(String s){ 
int letters = 0; 
int x; 
if (Character.isLetter(s.charAt(x))){ 
    letters ++;} 
return letters;} 

public static int vowels(String s){ 
int vowels = 0; 
int x; 
char c = s.charAt(x); 
if((c=='a')||(c=='e')||(c=='i')||(c=='o')||(c=='u')||(c=='A')||(c=='E')||(c=='I')||(c=='O')||(c=='U')){ 
    vowels ++; 
} 
return vowels;} 

public static int length(String s){ 
for (x=0; x<s.length(); x++) 
{ 
    x = s.charAt(x);} 
} 


} 
+1

И, что ваш вопрос? –

+0

В чем проблема, которую нужно решить, количество цифр, букв и гласных? А что конкретно не работает в вашем случае? – Uhla

+0

Это даже не компилируется. – laune

ответ

0

Что вам нужно, вам нужно определить 4 статические переменный уровень класса например:

static int whitespace, digits, letters, vowels; 

И затем во всем своем методе сделайте его недействительным и ожидайте символ вместо строки. Таким образом, ваш цифровой метод будет выглядеть так:

public static void digits(char s) { 
    if (Character.isDigit(s)) { digits ++;} 
} 

Применить эту же логику ко всем вашим методам с приращением соответствующей переменной счетчика.

И, наконец, в главном методе вам нужно перебирать каждый символ в строке, как показано ниже:

for (char ch : s) { 
    digits(ch); 
    //call other methods as well 
} 
System.out.println("You have entered " + s.length() + "characters and it contains the following"); 
System.out.println(whitespace + "whitespace characters."); 
System.out.println(digits + "digits."); 
System.out.println(letters + "letters."); 
System.out.println(vowels + "vowels."); 
1

Это не является допустимым for цикл:

for containsWhitespace=true{ 
    whitespace++;} 
} 

Несколько методов ничего не возвращают, например:

public static int digits(String s) { 
public static int whitespace(String s){ 

Отпечатки не найдены поскольку они не объявлены.

И я предлагаю вам скачать Eclipse, NetBeans или какую-либо другую IDE для анализа кода и обеспечения подсветки синтаксиса, поиск ошибок и предупреждений будет намного проще с чем-то, что укажет на них.

0

Аналогичная проблема был задан вопрос, прежде чем, для которого я отправил этот кусок кода:

public static void main(String... args) 
{ 
    int answer = 0; 
    Scanner input = null; 
    do 
    { 
     input = new Scanner(System.in); 
     System.out.print("Type a sentence and this program will tell you\nhow many vowels there are (excluding 'y'):"); 
     String sentence = input.nextLine(); 

     int vowels = 0; 
     String temp = sentence.toUpperCase(); 
     for (int i = 0; i < sentence.length(); i++) 
     { 
      switch((char)temp.charAt(i)) 
      { 
       case 'A': 
       case 'E': 
       case 'I': 
       case 'O': 
       case 'U': 
        vowels++; 
      } 
     } 
     System.out.println("The sentence: \"" + sentence + "\" has " + vowels + " vowels"); 
     System.out.print("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press any other key... "); 
     String tempNum = input.next(); 
     try 
     { 
      answer = Integer.parseInt(tempNum); 
     } catch (NumberFormatException e) 
     { 
      answer = 0; 
     } 
     System.out.println(); 
    } while (answer == 1); 
    input.close(); 
    System.out.println("Have a nice day"); 
} 

Для подсчета белых пространств, цифры, согласные и т.д., все, что вам нужно сделать, это использовать класс символов для выяснить, если это цифра, пробел, или алфавитный, а предыдущий код различать гласные и согласные:

public static void main(String... args) 
{ 
    int answer = 0; 
    Scanner input = null; 
    do 
    { 
     input = new Scanner(System.in); 
     System.out 
       .print("Type a sentence and this program will tell you\nhow many vowels there are (excluding 'y'):"); 
     String sentence = input.nextLine(); 

     int vowels = 0; 
     int consonants = 0; 
     int digits = 0; 
     int whitespaces = 0; 

     String temp = sentence.toUpperCase(); 
     for (int i = 0; i < sentence.length(); i++) 
     { 
      char character = (char) temp.charAt(i); 
      if(Character.isDigit(character)) 
      { 
       digits++; 
      } 
      else if(Character.isWhitespace(character)) 
      { 
       whitespaces++; 
      } 
      else if(Character.isAlphabetic(character)) 
      { 
       switch (character) 
       { 
        case 'A': 
        case 'E': 
        case 'I': 
        case 'O': 
        case 'U': 
         vowels++; 
         break; 
        default: 
         consonants++; 
         break; 
       } 
      } 
      else 
      { 
       System.out 
         .println("ERROR: Not an alphanumeric character or a whitespace: '" 
           + character + "'"); 
      } 
     } 
     System.out.println("The string: \"" + sentence + "\" has " 
       + vowels + ((vowels != 1) ? " vowels, " : " vowel, ") 
       + digits + ((digits != 1) ? " digits, " : " digit, ") 
       + whitespaces 
       + ((whitespaces != 1) ? " whitespaces, " : " whitespace, ") 
       + consonants 
       + ((consonants != 1) ? " consonants. " : " consonant.")); 
     System.out 
       .print("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press any other key... "); 
     String tempNum = input.next(); 
     try 
     { 
      answer = Integer.parseInt(tempNum); 
     } 
     catch (NumberFormatException e) 
     { 
      answer = 0; 
     } 
     System.out.println(); 
    } while (answer == 1); 
    input.close(); 
    System.out.println("Have a nice day"); 
} 

когда вы вводите некоторую строку, как: «dfkl, кг 0sdf903o4k; l5kw34 -0 kdfo0orterl; t34k34l; k5l; 34 ", вы получаете следующий результат:

ERROR: Not an alphanumeric character or a whitespace: ';' 
ERROR: Not an alphanumeric character or a whitespace: '-' 
ERROR: Not an alphanumeric character or a whitespace: ';' 
ERROR: Not an alphanumeric character or a whitespace: '-' 
ERROR: Not an alphanumeric character or a whitespace: ';' 
ERROR: Not an alphanumeric character or a whitespace: ';' 
ERROR: Not an alphanumeric character or a whitespace: ';' 
The string: "dfkl;kg-0sdf903o4k;l5kw34 -0 kdfo0orterl; t34k34l;k5l;34 " has 4 vowels, 17 digits, 4 whitespaces, 25 consonants. 
0
// counting vowels consonants and blank spaces from a string 
import java.util.*; 
class VowConsBlank 
{ 
    public static void main(String s[]) 
    { 
    Scanner sc=new Scanner(System.in); 
    System.out.println("Enter a string"); 
    String str=sc.nextLine(); 
    int c=0,v=0,b=0; 
    for(int i=0;i<str.length();i++) 
    { 
     if("AEIOUaeiou ".indexOf(str.charAt(i))==-1) 
      c++; 
     else if(str.charAt(i)==' ') 
      b++; 
     else 
      v++; 
    } 
    System.out.println(" No of vowels: "+v+"\n No. of consonants: "+c+"\n 
    No. of blank: "+b); 
} 
+0

Добавьте несколько объяснений в свой ответ. – Sunil

Смежные вопросы