2016-03-29 19 views
0

私は、小文字で姓を入力するようにプログラムを作成しています。大文字または小文字のままで出力するかどうかを尋ねます。私が持っている問題は、toUpperCaseでcharAtを使用することです。charAtを使用して文字列を大文字に変換する

import java.util.Scanner; 
//This imports the scanner class 
public class ChangeCase { 

    public static void main(String[] args) { 
     Scanner scan = new Scanner (System.in); 
     //This allows me to use the term scan to indicate when to scan 
     String lastName; 
     //sets the variable lastName to a string 
     int Option; 

    System.out.println("Please enter your last name"); 
    //Prints out a line 
    lastName = scan.nextLine(); 
    //scans the next line of input and assigns it to the lastName variable 
    System.out.println("Please select an option:"+'\n'+"1. Make all leters Capitalised"+'\n'+ "2. Make the First letter Capitalised"); 
    Option = scan.nextInt(); 
    if (Option == 1){ 
     System.out.println(lastName.toUpperCase()); 
    } 
    if (Option == 2){ 
     System.out.println(lastName.charAt(0).toUpperCase()); 

    } 
    } 

} 

は、私はあなたのエラーが言っているように

+3

**あなたの質問を編集**し、あなたのコードのテキストをあなたのコードの画像へのリンクではなく貼り付けてください。ペーストしたら、テキストを選択してctrl-kを押して、必要な4つのスペースをインデントします。 –

答えて

2

「プリミティブ型char上のtoUpperCase()を呼び出すことはできません」あなたはcharString.toUpperChaseを適用することはできませんというエラーを取得します。あなたはあなたのような何かを行うことができ、大文字の最初の文字を作りたい場合:

String lastName = "hill"; 
    String newLastName = lastName.substring(0, 1).toUpperCase() + lastName.substring(1); 
    System.out.println(newLastName); 

このサンプルの実行:

実行:
ヒル
BUILD SUCCESSFUL(合計時間:あなたはすべての文字を大文字にしたい場合は、

のような単純な0秒)

をです

newLastName = lastName.toUpperCase(); 
    System.out.println(newLastName); 

このサンプルの実行:

実行:SUCCESSFUL
HILL
BUILD(合計時間:0秒)

+0

ありがとう、これはすごく助けました。 –

+0

@AlexRBurgessそれを聞いてうれしい!受け入れることを忘れないでください。乾杯! – robotlos

0

私は大学でCプログラミングでこれを試すために使用されます。ここでもうまくいくはずです。

(char)(lastName.charAt(i) - 32) 

我々は文字から32を差し引くときに32でASCII値を減少させ、したがって、大文字を取得コードするSystem.out.println

上記を試してみてください。アスキーテーブルを参照して、私がテーブルの32の場所を控除することによって伝えようとしていることを理解してください。

0

エラーが表示されるため、プリミティブcharタイプでString.toUpperCase()を呼び出すことはできません。

System.out.println(lastName.charAt(0).toUpperCase()); 

しかし、あなたは最初の文字を取る、その後String.toUpperCase()を呼び出すと、

System.out.println(Character.toUpperCase(lastName.charAt(0))); 

それともようCharacter.toUpperCase(char)を呼び出すことができます。同様に、

System.out.println(lastName.toUpperCase().charAt(0)); 
関連する問題