【问题标题】:Returning a String converted to Unicode in Java返回在 Java 中转换为 Unicode 的字符串
【发布时间】:2020-09-01 23:03:26
【问题描述】:

我正在学习 Java 课程,但我被这个问题难住了。我要完成大部分工作,直到需要将字符串转换为 ASCII 的部分。我能够将第一个字母输出到 Edit Unicode,但它停在那里。当我在临时文件中隔离代码并使用打印语句时,它会打印出它应该如何:

class Scratch {
public static void main(String[] args) {
    String str = "yams";
    for (int i = 0; i < str.length(); i++) {
        int numUni = (int)str.charAt(i);
        int unicode = (int)numUni;
        System.out.print(unicode + " ");
        //return unicode; //  this line will need to be changed
    }
}

}

输出:

121 97 109 115 
Process finished with exit code 0

这是我到目前为止完成的代码,我的问题是第 4 步:

public class Strings{
// STEP one - concatenateStrings()
public String concatenateStrings(String word1, String word2){
    String concantWord = word1 + " " + word2;
return concantWord;
}

// STEP two - charToASCII()
public int charToASCII(char character){
    int convertedChar = character;
return convertedChar;
}

// STEP three
public char getLastChar(String str){
    //student code here\
    int strLength = str.length();

    char lastChar = str.charAt(str.length() - 1);

    return lastChar; //  this line will need to be changed
}

 // step 4

public static String translateWord(String str){
    //student code here


        for (int i = 0; i < str.length(); i++) {
            int numUni = (int)str.charAt(i);
            String unicode = numUni + " ";


            return unicode; //  this line will need to be changed
        }

    return "";
}

// step 5
public String madLib(String noun1, double number, String pastTenseVerb, String adjective, String noun2) {
    //student code here
    return ""; // this line will need to be changed
}
/**
 * A test block helps you test as you write. Eventually, you will learn
 * test driven development, in which every method you write will have tests you write
 * to make sure it works.
 *
 * Uncomment these lines out as you finish your various methods
 */
public void runTests() {
     System.out.println();
     //Concatenate Strings test
     System.out.println("Testing concatenateStrings method: ");
     System.out.println("Input: 'good','morning' \t Expecting: good morning\t Actual: " + concatenateStrings("good", "morning"));

     System.out.println();
     //Char to ASCII test
     System.out.println("Testing charToASCII method: ");
     System.out.println("Input: 'c' \t Expecting: 99\t Actual:" + charToASCII('c'));

     System.out.println();
     //Get Last Char test
     System.out.println("Testing getLastChar method: ");
     System.out.println("Input: 'Pterodactyl' \t Expecting: L\t Actual: " + getLastChar("Pterodactyl"));

     System.out.println();
     //Translate Word Test
     System.out.println("Testing Translate word method: ");
     System.out.println("Input: 'yams' \t Expecting: 121 97 109 115\t Actual: " + translateWord("yams"));

    // System.out.println();
    // Mad Libs Test
    // System.out.println("Testing Mad Libs method: ");
    // System.out.println("Input: 'pear, 202.356, swam, purple, bear'"
    //      + "\nExpecting: Today I went to the store and bought a pear for $202.36.\nThen I swam and saw a purple bear."
    //      + "\nActual: " + madLib("pear", 202.356, "swam", "purple", "bear"));

}


public static void main(String [] args) {
    // running test method
    Strings f = new Strings();
    f.runTests();  // this is not a static method (should it have been?) so you have to run it with the object
}

}

如有任何指导,我将不胜感激。

【问题讨论】:

  • 它是 Unicode (UTF-16),而不是 ASCII
  • @saka1029 呃,我为混淆道歉。我正在学习 ASCII,我混淆了我将修复它的术语。感谢您的回复。
  • “将字符串转换为 ASCII”是什么意思? 121 97 109 115 的输出对于“yams”是否正确,或者这是您的代码所做的,但您想要别的东西?
  • 教师想要在方法中输入“yams”并将yams作为unicode等效输出。当我运行程序时,我只得到 121,但是当我单独使用该方法并在暂存文件上输出时,它会输出 121 97 109 115,这就是我所追求的。
  • 你贴了很多代码。似乎其中大部分与您的问题没有直接关系 - 请编辑您的问题以删除此类代码,留下显示问题所需的绝对最小值。= - 即可能只有几行。理想情况下,请创建一个MCVE

标签: java string ascii


【解决方案1】:

显然,如果您在循环内返回,则循环只会执行一次。

你想“建立”你的字符串,一次一个 ascii 代码(好吧,unicode 代码点,真的 - 正如其他人所指出的那样,我不知道你在关注什么 80 年代后期过时的垃圾,伙计- ASCII 的日子已经一去不复返了),所以你需要一个 StringBuilder,你想在循环中附加 'numUni + " "' 到这个,然后返回 stringbuilder,建立一个字符串:

StringBuilder out = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
    int uni = (int) str.charAt(i);
    out.append(uni).append(" ");
}
return out.toString();

【讨论】:

  • 感谢您的帮助。这解决了我的问题。我必须阅读 StringBuilder 因为我认为它还没有被教过。在线学习很痛苦,我觉得我在这里和那里遗漏了一些东西。
  • @Drrichardhurts 您不需要使用 StringBuilder。只需使用String out = ""; 然后out = out + uni + " ";
  • 由于@rzwiserloot 非常关心正确的教学(StringBuilder 而不是字符串连接),他应该向您指出@Drrichardhurts 以避免不必要的类型转换int numUni = (int)str.charAt(i); int unicode = (int)numUni; 因为 numUni 是一个整数,所以将它转换为int 是 100% 不必要的。我强烈建议您查找SonarLint 或其他linter 并将其添加到您的IDE。对于经验丰富的程序员和新手程序员来说,Linter 都很方便。
  • 这是UTF-16,而不是unicode codepoint。您的代码将代理对输出为两个数字。
  • @Uroš 完整粘贴中的实际代码没有这种无关的演员表,这似乎表明没有必要解释那部分。如果你要在评论中狙击别人,你应该阅读完整的问题:)
【解决方案2】:

您在第一次迭代后立即返回 ascii 值,编辑您的代码如下所示:

public static String translateWord(String str) {
    //student code here
    String ascii = "";
    for (int i = 0; i < str.length(); i++) {
        int numascii = str.charAt(i);
        ascii += numascii + " ";
    }
    return ascii;
}

编辑:正如下面评论者所提到的,一定要了解字符串池,StringBuilderStringBuffer

【讨论】:

  • 这是一个滥用字符串连接的灌篮案例。在这里,性能方面并不重要,但教给显然是新手的坏习惯可能是个坏主意。
  • 好吧,没有复杂化他现有的代码,我只是指出他哪里出错了,一​​步一步学习总是比一次抓住一切好。感谢您的反馈
猜你喜欢
  • 2016-03-26
  • 2010-12-28
  • 1970-01-01
  • 2012-10-27
  • 2016-11-04
  • 2022-07-21
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多