Reputation: 156
I want to read a single character from the keyboard. If it's a capital letter, convert it to lower case and vice versa.
This is my code:
import java.util.Scanner;
public class Nico4
{
public static void main(String[] args)
{
char letra;
boolean mayuscula;
Scanner in=new Scanner(System.in);
System.out.println("Ingrese una letra: ");
letra=in.next().charAt(0);
mayuscula=Character.isUpperCase(letra);
if (mayuscula==true) letra=Character.toLowerCase(letra);
else letra=Character.toUpperCase(letra);
System.out.println(+letra);
}
}
but I'm not getting the right answer. If I input 'A', it returns 97, but I want 'a'. What am I doing wrong?
Upvotes: 0
Views: 244
Reputation: 304
Sample Code :
public class CaptLetter{
public static void main(String args[]) {
String message = "my message";
message = Character.toUpperCase(message.charAt(0)) + message.substring(1);
System.out.println(message); //result like "My message"
System.out.println(upperCaseWords(sentence)); //result like "Hi Chandru How Are You"
}
static String sentence = "Hi chandru how are you";
public static String upperCaseWords(String sentence) {
String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
String newSentence = "";
for (String word: words) {
for (int i = 0; i < word.length(); i++)
newSentence = newSentence + ((i == 0) ? word.substring(i, i + 1).toUpperCase() : (i != word.length() - 1) ? word.substring(i, i + 1).toLowerCase() : word.substring(i, i + 1).toLowerCase().toLowerCase() + " ");
}
return newSentence;
}}
Result:
My message
Hi Chandru How Are You
Upvotes: 1