簡體   English   中英

將字母從字符串轉換為數字

[英]Converting Letters from String to Numbers

您好,我是 java 的新手,我很難將字母從字符串轉換為數字,例如,用戶將輸入“我很好”,output 將變為 901-13015-11-1-25,因為,我= 9 空間 = 0 A = 1 M = 13 空間 = 0 O = 15 K = 11 A = 1 Y = 25。我嘗試使用 switch,但我很難,因為程序會打印我在字符串,這里是我創建的測試代碼,我希望有人可以幫助我或給我提示和建議。

import java.util.*;
public class New2
{
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Input the First string: ");
    String fs = input.nextLine();
    
    fstoInt(fs);
    System.out.println(fs);

}

public static int fstoInt(String fs) {
    int num = 0;
    switch (fs) {
    case "A":
        num = 1;
        break;
    case "B":
        num = 2;
        break;
    case "C":
        num = 3;
        break;
    case "D":
        num = 4;
        break;
    case "E":
        num = 5;
        break;
    case "F":
        num = 6;
        break;
    case "G":
        num = 7;
        break;
    }
    return num;
}
}

output 將變為 901-13015-11-1-25 因為,I = 9 空格 = 0 A = 1 M = 13 空格 = 0 O = 15 K = 11 A = 1 Y = 25

我認為您沒有正確閱讀作業。

這意味着: AA變為11 並且K ... 也變為11 不確定這是你想要的。

switch (fs) {
    case "A":

假設它都是連續的,“A”變為 1,“Z”變為 26:字符只是數字(它們的 unicode 值),並且這些字母是按順序排列的。 因此,您需要的不是巨大的開關塊,而是:

int num = fs.charAt(0) - 'A' + 1;

這會將“A”變為 1,將“Z”變為 26。

正如評論已經說過的那樣,您的問題是fs不僅僅是"A" "Hello" 您需要遍歷字符。 隨着空間得到特殊處理(變成 0),並且可能任何不是“A”-“Z”的東西都應該崩潰:

for (char c : fs.toCharArray()) {
    int num = charToCode(c);
}

然后寫charToCode:

public int charToCode(char c) throws IllegalArgumentException {
    if (c == ' ') return 0;
    if (c >= 'A' && c <= 'Z') return c - 'A' + 1;
    throw new IllegalArgumentException(
      "Only spaces and capital letters allowed");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM