2015-07-31 4 views
-1

У меня возникли проблемы с написанием этой программы (я, вероятно, переусердствовал!) Во всяком случае, проблема у меня в том, что я могу делать все, заданное одним методом ... но я должен используйте другие пять методов ... может кто-нибудь мне помочь ?!Строки и текст Ввод/вывод

Вот направление я был дать:

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

  1. Ваш главный метод должен иметь только переменные декларации и вызовы для вызова методов

  2. Ваша программа должна иметь по крайней мере 5 методов, называемых StringLength, convertToUpperCaseString, WordCount, CharCount и OccurenceNPercentage.

  3. Строки неизменяемы в JAVA, вам понадобится новый массив для convertToUpperCaseString.

  4. Значения ASCII для '', 'A', 'Z', 'A' и 'Z' 32, 65, 90, 97 и 122.

То, что я : импорт java.util.Scanner; общественного класса Project_Strings_TextIO {

//initiate main method and call the rest of the methods used 
    public static void main(String[] args){ 

     //call all methods 


    } 

//determine the length of the string 
public static void stringLength(int length){ 

    //initiate scanner and prompt user for a string 
    Scanner input = new Scanner(System.in); 

    System.out.println("Please enter a string! --> "); 
    String phrase = input.nextLine(); 

    //determine length of said string 
    System.out.print("String length is " + phrase.length() + " characters long."); 
} 

//convert the string to uppercase 
public static void convertToUpperCase(int uppercase){ 

    //upper case 
    System.out.print("Look! I can uppercase your string: " + phrase.toUpperCase()); 

} 

//count the words in the string 
public int wordCount(String word){ 
    if(word == null){ 
     return 0; 
    } 
    String input = word.trim(); 
    int count = input.isEmpty() ? 0 : input.split("\\s+").length; 
    return count; 

    //use this? System.out.print("There are " + phrase.charAt(length) + " words in the string."); 

} 

//count the characters in the string 
public static void charCount(int phrase){ 
    System.out.println(phrase.charAt(i));  
} 

//count the occurrences and percentage of the characters in the string 
public static int occurrenceNPercentage(int percent){ 
    int count = 0; 

    //use percent for the loop??? 
    for(int i = 0; i < percent.length(); i++){ 
     if(percent.charAt(i) == char){ 
      count++; 
     } 
     return count; 
    } 
} 

}

+0

Не могли бы вы указать, в чем проблема? Указания указывают, что это нужно сделать, используя 5 методов, которые вызывается из основного метода. –

+0

У меня возникла проблема с использованием методов для выполнения чего-то, что я знаю. Я могу сделать более простой способ (следующие указания - это не мой сильный костюм, когда я знаю ярлык). – Tiffany

+2

Если вы планируете провести какое-либо значительное количество работы с программированием в будущем , или даже если вы планируете принять еще один класс, вам, вероятно, стоит попробовать немного усерднее использовать другие методы. Возможно, это не так, но разделение кода на методы является ключевой частью создания удобного и легко читаемого кода. –

ответ

0

Это полная программа, которая делает то, что вам нужно. Тем не менее, он считает пробелы как символы. Кроме того, stringLength() и charCount() методы делают то же самое - подсчет символов. Метод процентного отчета берется из другого ответа на переполнение стека. С этим ответом вы ничего не узнаете из своей домашней работы. По крайней мере, попробуйте понять алгоритмы. Спасибо и наслаждайтесь!

public class wordReport { 

    //determine the length of the string 
    public static void stringLength(String inputString) { 

     //determine length of said string 
     System.out.println("String length is " + inputString.length() + " characters long."); 
    } 

    //convert the string to uppercase 
    public static void convertToUpperCase(String inputString) { 

     //upper case 
     System.out.println("Look! I can uppercase your string: " + inputString.toUpperCase()); 

    } 

    //count the words in the string 
    public static void wordCount(String inputString) { 
     String[] wordsArray = inputString.split(" "); 
     System.out.println("There are " + wordsArray.length + " words in the string."); 

    } 

    //count the characters in the string 
    public static void charCount(String inputString) { 

     System.out.println("There are " + inputString.length() + " characters in the string."); 

    } 

    //count the occurrences and percentage of the characters in the string 
    public static void occurrenceNPercentage(String inputString) { 
     char[] capital = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 
      'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; 

     char[] small = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
      'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 
     int[] count = new int[26]; 
     char[] chars = inputString.toCharArray(); 
     int myTotal = 0; 
     for (int i = 0; i < chars.length; i++) { 
      for (int j = 0; j < 26; j++) { 
       if (chars[i] == capital[j] || chars[i] == small[j]) { 
        count[j]++; 
        myTotal = myTotal + 1; 
        break; 
       } 
      } 
     } 

     System.out.println("Comlete count"); 
     for (int i = 0; i < 26; i++) { 
      System.out.print(" " + small[i]); 
      System.out.print(" " + count[i]); 
      if (count[i] > 0) { 
       System.out.println(" " + (((float) count[i]/myTotal) * 100) + "%"); 
      } else { 
       System.out.println(" 0%"); 
      } 
      //calculate percentage for the full count 
     } 
    } 

    public static void main(String[] args) { 

     System.out.println("Please enter String"); 

     Scanner input = new Scanner(System.in); 
     String inputString = input.nextLine(); 
     stringLength(inputString); 
     convertToUpperCase(inputString); 
     wordCount(inputString); 
     charCount(inputString); 
     occurrenceNPercentage(inputString); 

    } 

} 
+0

спасибо за помощь! Я понял, что я сильно переусердствовал, и имею почти процентную долю. ваш ответ позволяет мне настроить свой собственный ответ для этой части. Спасибо за помощь! :) (и я узнал ... также понял, что мой учитель действительно плохой: /) – Tiffany

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