Java, как вы преобразуете строчные значения в верхний регистр в строковый массив - PullRequest
1 голос
/ 20 марта 2011

У меня есть эта проблема, и я хочу, чтобы, когда пользователь вводит слово в нижнем регистре. Я хочу, чтобы моя программа принимала строчные буквы в массиве и строчные буквы в массиве.

/**
   The ObjectSelectionSorter class provides a public static
   method for performing a selection sort on an numbers of
   objects that implement the Comparable interface.
*/

public class ObjectSelectionSorter
{

   /**
      The selectionSort method performs a selection sort on an
      numbers of objects that implement the Comparable interface.
      @param numbers The numbers to sort.
   */

   public static void selectionSort(Comparable[] numbers)
   {
      int startScan;       // Starting position of the scan
      int index;           // To hold a subscript value
      int minIndex;        // Element with smallest value in the scan
      Comparable minValue; // The smallest value found in the scan

      // The outer loop iterates once for each element in the
      // numbers. The startScan variable marks the position where
      // the scan should begin.
      for (startScan = 0; startScan < (numbers.length-1); startScan++)
      {
         // Assume the first element in the scannable area
         // is the smallest value.
         minIndex = startScan;
         minValue = numbers[startScan];

         // Scan the numbers, starting at the 2nd element in
         // the scannable area. We are looking for the smallest
         // value in the scannable area. 
         for(index = startScan + 1; index < numbers.length; index++)
         {
            if (numbers[index].compareTo(minValue) < 0)
            {
               minValue = numbers[index];
               minIndex = index;
            }
         }

         // Swap the element with the smallest value 
         // with the first element in the scannable area.
         numbers[minIndex] = numbers[startScan];
         numbers[startScan] = minValue;
      }
   }
}




import java.io.*;

/**
   This program demonstrates the search method in
   the IntBinarySearcher class.
*/

public class BinarySearchTest
{
   public static void main(String [] args) throws IOException
   {
      int result;
      String searchValue;
      String input;

      // An array of numbers to search.
      String[] numbers = {"Jake", "Jerry", "Bill", "Lousie", "Goku", "Ivan", "John", "Sarah", "Kim"};


      // Create the console input objects.
      InputStreamReader reader =
                 new InputStreamReader(System.in);
      BufferedReader keyboard =
                 new BufferedReader(reader);

      // First we must sort the array in ascending order.
      ObjectSelectionSorter.selectionSort(numbers);

      do
      {
         // Get a value to search for.
         System.out.print("Enter a value to search for: ");
         input = keyboard.readLine();
         searchValue = input;


         // Search for the value
          result = ObjectBinarySearcher.search(numbers, searchValue);
                    // Display the results.
        if (result == -1)
           System.out.println(searchValue + " was not found.");
        else
        {
           System.out.println(searchValue + " was found at " +
                              "element " + result);
        }

        // Does the user want to search again?
        System.out.print("Do you want to search again? (Y or N): ");
        input = keyboard.readLine();
      } while (input.charAt(0) == 'y' || input.charAt(0) == 'Y');
   }
}



/**
   The StringBinarySearcher class provides a public static
   method for performing a binary search on an String array.
*/



public class ObjectBinarySearcher{

/**
      The search method performs a binary search on an String
      array. The array is searched for the number passed to
      value. If the number is found, its array subscript is
      returned. Otherwise, -1 is returned indicating the
      value was not found in the array.
      @param numbers The array to search.
      @param value The value to search for.
   */



   public static int search(String[] numbers, String value)
   {
      int first;       // First array element
      int last;        // Last array element
      int middle;      // Mid point of search
      int position;    // Position of search value
      boolean found;   // Flag     

      // Set the initial values.
      first = 0;
      last = numbers.length - 1;
      position = -1;
      found = false;


      // Search for the value.
      while (!found && first <= last)
      {
         // Calculate mid point
         middle = (first + last) / 2;


         // If value is found at midpoint...
         if (numbers[middle].equals(value))
         {
            found = true;
            position = middle;
         }

         // else if value is in lower half...
         // need tell is value is less then the integer?, with out using equality regulators
         else if (value.compareTo(numbers[middle]) < 0)
            {

            last = middle - 1;
            }
         // else if value is in upper half....
         else
            first = middle + 1;
      }

      // Return the position of the item, or -1
      // if it was not found.

      return position;
   }
}

Ответы [ 2 ]

2 голосов
/ 20 марта 2011

Попробуйте это:

String[] numbers = {"Jerry"};
numbers[0] = numbers[0].toUpperCase();
1 голос
/ 20 марта 2011

Там string.toUpperCase() и Character.toUpperCase(char). Первый возвращает строку, которая является версией данной строки в верхнем регистре, а вторая возвращает версию char в верхнем регистре. (Я даю последнее, потому что вы упоминаете массив, и это может быть массив символов, который вы имеете в виду)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...