views:

1197

answers:

10

Hi, I'd like to know how to convert to upper case the input from the keyboard either if they are letters or numbers (only).

I'm learning to program and I'd like to do it in the Java language. I have to remove the accents if the input has it and convert the input in the upper case letter.

I have an idea of this but I'd really appreciate the help you may want to give me.

Next, I put in this broad the code I've already done....

using namespace std;

int main () {
    char c;
    cin >> c;
    if(c >= 'a' and c<='z') {
        c -= 'a' - 'A';
        cout << c;
    } else if(c >= 'A' and c<='Z'){
        c -= 'A' - 'a';
       cout << c;
    }
    cout << endl;
    return 0;
}

Yeap, it's homework... I do not want to use the existing functions in Java. The point is to develop the function itself.

+9  A: 

I highly suggest you get to know the Java API like the back of your hand. The language is feature rich with classes and methods that will make you love it. In your particular case, try the toUpperCase method of the String class.

Jason Nichols
What about the accents removal?
OscarRyz
Your suggestion is to know the entire Java API? Even if you mean "understand the lay of the land", is that realistic, for the question?
Michael Easter
no his suggestion is the `toUpperCase` method.
Sneakyness
+5  A: 
// Convert to upper case
String upper = string.toUpperCase();

// Convert to lower case
String lower = string.toLowerCase();
Matthew Vines
This misses the accents replacement part too.
OscarRyz
A: 

c++ has a ::toupper(char) function

jspcal
+1  A: 

Like most things in Java, this is already solved for you in either the standard API or in someone elses open source library. You'll want either:

String.toUpperCase to convert the whole string to upper case

Character.toUpperCase if you are working on a char by char basis

and if you haven't yet, bookmark the standard API reference page and refer to it first to see if your problem might have already been solved in the standard API. Learning the Standard API is just as important as learning the java language itself.

whaley
+1  A: 

You can use the class Normalizer to remove the accents, and the method toUpperCase() of the String class to convert to uppercase.

A sample code.

public String toUpperCaseRemovingAccents(String text)
{
   String returnString = Normalizer.normalize(text, Normalizer.Form.NFD);
   returnString = returnString.replaceAll("[^\\p{ASCII}]", "");
   return returnString.toUpperCase();
}
Diego Dias
+1  A: 

Yeap, it's homework... I do not want to use the existing functions in Java. The point is to develop the function itself

Ibbo
Ask for ideas, not "how do I do it?" Try to think by yourself first, *then* ask away. You'll find better answers that way and you may learn something.
Leonardo Herrera
I appreciate your comment Leonardo. I'll try to do it better the next time....
Ibbo
Also, this would be better as an edit to your original post (passing on what I learned after doing this myself). Answers should be answers, clarifications should be in the question, and other stuff (like this) should be comments.
David Thornley
+1  A: 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ICanHasUpperCase {
    public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
     System.in));

    String line = null;
    System.out.print("Can I has char? ");
    while ((line = reader.readLine()) != null) {
        if (line.length() == 1) {
     char c = line.charAt(0);
     System.out.println("Uppercuttin ur chars: "
      + Character.toUpperCase(c));
     System.out.print("Can I has char?");
        } else {
     System.out.println("I please needs a char? ");
        }
    }
    System.out.println("K, bai.");
    }
}
  1. To run the program, save the text above in a file named ICanHasUpperCase.java.
  2. In the same directory in which you saved the file, type this command to compile it: javac ICanHasUpperCase.java
  3. Then type this command to run it: java ICanHasUpperCase
LES2
For a moment I thought this was written in LOLCODE (http://en.wikipedia.org/wiki/LOLCODE)...
Andrew Swan
Sometimes I feel like Java is LOLCODE
LES2
+2  A: 

You'll need to set an array where the things you want to replace are, and then another with the replacements.

Since your replacement matches many chars, it would be better for you to have a matrix.

Once you know what you want, you build an algorithm.

 to_replace: matrix
 replacements: array

 data: char array
 result: char array 

 for each letter in data 
      char replacement = findReplacementFor( letter ).in(matrix)
      result[i++] = replacement 
 end

Or something like that, the point is to describe what steps you need to perform to accomplish what you want.

And then implement that algorithm.

Here's the running code.

public class Conv {
    static char [][] toReplace = {
        {'a','á','à', 'â', 'ä'},
        {'b'},
        {'c'},
        {'d'},
        {'e', 'é', 'è', 'ê', 'ë'}
        // complete with the remaining as needed.
    };
    static char [] replacement = {
        'A','B','C','D','E'
    };

    public static void main( String [] args ) {
        char [] converted = convert("Convërt mê. à".toCharArray());
        System.out.println( new String( converted ));

    }

    /** 
     *Transform the given char array into it's equivalent according to the conversion table.
     */
    private static char []  convert( char [] data  ) {
        char [] result = new char[data.length];

        for( int i = 0 ; i < data.length ; i++ ){
            result[i] = findReplacement( data[i] );
        }
        return result;
    }

    /**
     * Find a replacement for the given char, if there is no a suitable replacement
     * return the same char
     */
    private static char findReplacement( char c ) {
        int i = indexOfReplacementFor( c );
        if( i >= 0 ) {
            return replacement[i];
        }
        return c;
    }
    /** 
     * Search in the reaplcement table what is the corresponding index to replace
     */
    private static int indexOfReplacementFor( char c ) {
        for( int i = 0 ; i < toReplace.length ; i++ ) {
            for( int j = 0 ; j < toReplace[i].length; j++ ){
                if( c == toReplace[i][j] ){
                    return i;
                }
            }
        }
        return -1;
    }

}

Notice that I have splited the function into smaller ones for clarity. I hope the code is easy enough for you to grasp it.

The missing part it how to write accentuated char literals in java, but I'm pretty sure that could be asked here in SO.

EDIT My compiler ( javac from OSX distribution ) wasn't using the UT8 encoding for me.

I'm posting the right code and it works by following this accepted answer.

OscarRyz
Thanks a lot for this help. I know sometimes the questions that some guys like me asks could be a sort of anoying or silly. Anyway, I really Apreciate the help specially for Oscar Reyes. Greetings!!!
Ibbo
Thanks for this useful help.
Ibbo
A: 

Yeap, it's homework... I do not want to use the existing functions in Java. The point is to develop the function itself.

Then I suggest to loop through all the characters of the String and determine if they're inside a certain range 0x061 - 0x07A (or just a - z) and then subtract 0x020 from it before appending to the result. It should deliver 0x041 - 0x05A (A - Z).

Here is a starting point:

String string = "aBcDeF";

for (char c : string.toCharArray()) {
    if (c >= 'a' && c <= 'z') {
        // Substract 0x020 from c.
    }

    // Append c to result.
}

This however doesn't cover diacricital characters, but as this is homework I can't imagine that this is an requirement and that you rather wanted to "add" this yourself to impress the teacher. If this is really the homework requirement, then you'll need to grow/maintain two arrays yourself, one with the to-be-replaced characters and the other with replacement characters. This is however a tedious and non-safe work without a bit help of the standard API's, such as java.text.Normalizer.

BalusC
A: 

Is there a smart way of doing it if we want to change the lower case chars. to upper case and the upper case chars. to lower case?

varunthacker
There are truly builtin ways: `String#toLowerCase()` and `String#toUpperCase()`. In the future, please ask questions as questions by pressing `Ask Question` button at right top. Do not post questions as answers.
BalusC
i think i should have framed the question properly.Both the upper case and the lower case chars are part of one string.they need to be changed.The lower case ones to the upper case ones the the upper case ones to the lower case.
varunthacker