在Java中将字符串转换为Unicode后返回。

huangapple go评论118阅读模式
英文:

Returning a String converted to Unicode in Java

问题

以下是您所提供的代码部分的翻译:

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 + " ");
        }
    }
}

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

    // 步骤二 - charToASCII()
    public int charToASCII(char character){
        int convertedChar = character;
        return convertedChar;
    }

    // 步骤三
    public char getLastChar(String str){
        int strLength = str.length();
        char lastChar = str.charAt(str.length() - 1);
        return lastChar;
    }

    // 步骤四
    public static String translateWord(String str){
        String unicodeOutput = "";
        for (int i = 0; i < str.length(); i++) {
            int numUni = (int)str.charAt(i);
            String unicode = numUni + " ";
            unicodeOutput += unicode;
        }
        return unicodeOutput;
    }

    // 步骤五
    public String madLib(String noun1, double number, String pastTenseVerb, String adjective, String noun2) {
        // 学生代码在这里
        return ""; // 这一行需要更改
    }

    public void runTests() {
        System.out.println();
        // 测试 concatenateStrings 方法
        System.out.println("测试 concatenateStrings 方法:");
        System.out.println("输入:'good','morning' \t 期望输出:good morning\t 实际输出:" + concatenateStrings("good", "morning"));

        System.out.println();
        // 测试 charToASCII 方法
        System.out.println("测试 charToASCII 方法:");
        System.out.println("输入:'c' \t 期望输出:99\t 实际输出:" + charToASCII('c'));

        System.out.println();
        // 测试 getLastChar 方法
        System.out.println("测试 getLastChar 方法:");
        System.out.println("输入:'Pterodactyl' \t 期望输出:L\t 实际输出:" + getLastChar("Pterodactyl"));

        System.out.println();
        // 测试 Translate word 方法
        System.out.println("测试 Translate word 方法:");
        System.out.println("输入:'yams' \t 期望输出:121 97 109 115\t 实际输出:" + translateWord("yams"));
    }

    public static void main(String [] args) {
        // 运行测试方法
        Strings f = new Strings();
        f.runTests();
    }
}

请注意,我只对代码部分进行了翻译,而没有包括问题和附加信息。如果您有任何进一步的问题或需要解释,请随时提问。

英文:

I am taking a Java course and I am stumped on this question. I was to complete most of it up until the portion where I am required to convert a String to ASCII. I am able to get the first letter to output to Edit Unicode but it stops there. When I isolate the code on a scratch file and use a print statement it prints how it should:

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

}

Output:

121 97 109 115 
Process finished with exit code 0

Here is the code that I have completed so far and my issue is with Step 4:

public class Strings{
// STEP one - concatenateStrings()
public String concatenateStrings(String word1, String word2){
String concantWord = word1 + &quot; &quot; + 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 &lt; str.length(); i++) {
int numUni = (int)str.charAt(i);
String unicode = numUni + &quot; &quot;;
return unicode; //  this line will need to be changed
}
return &quot;&quot;;
}
// step 5
public String madLib(String noun1, double number, String pastTenseVerb, String adjective, String noun2) {
//student code here
return &quot;&quot;; // 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(&quot;Testing concatenateStrings method: &quot;);
System.out.println(&quot;Input: &#39;good&#39;,&#39;morning&#39; \t Expecting: good morning\t Actual: &quot; + concatenateStrings(&quot;good&quot;, &quot;morning&quot;));
System.out.println();
//Char to ASCII test
System.out.println(&quot;Testing charToASCII method: &quot;);
System.out.println(&quot;Input: &#39;c&#39; \t Expecting: 99\t Actual:&quot; + charToASCII(&#39;c&#39;));
System.out.println();
//Get Last Char test
System.out.println(&quot;Testing getLastChar method: &quot;);
System.out.println(&quot;Input: &#39;Pterodactyl&#39; \t Expecting: L\t Actual: &quot; + getLastChar(&quot;Pterodactyl&quot;));
System.out.println();
//Translate Word Test
System.out.println(&quot;Testing Translate word method: &quot;);
System.out.println(&quot;Input: &#39;yams&#39; \t Expecting: 121 97 109 115\t Actual: &quot; + translateWord(&quot;yams&quot;));
// System.out.println();
// Mad Libs Test
// System.out.println(&quot;Testing Mad Libs method: &quot;);
// System.out.println(&quot;Input: &#39;pear, 202.356, swam, purple, bear&#39;&quot;
//      + &quot;\nExpecting: Today I went to the store and bought a pear for $202.36.\nThen I swam and saw a purple bear.&quot;
//      + &quot;\nActual: &quot; + madLib(&quot;pear&quot;, 202.356, &quot;swam&quot;, &quot;purple&quot;, &quot;bear&quot;));
}
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
}

}

I would appreciate any guidance.

答案1

得分: 1

很显然,如果你在循环内部使用return语句,那么循环只会执行一次。

你想要逐个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();
英文:

Obviously, if you return inside a loop, the loop will only ever execute once.

You want to 'build up' your string, one ascii code at a time (well, unicode codepoint, really - as others have pointed out, I don't know what dank late 80s outdated cruft you're following, mate - the days of ASCII are loooong gone), so you need a StringBuilder, you want to append 'numUni + " "' to this in the loop, and then return the stringbuilder, built up to a string:

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

答案2

得分: 0

你在第一次迭代后立即返回了 ASCII 值,编辑你的代码看起来应该像下面这样:

public static String translateWord(String str) {
    // 学生代码在这里
    StringBuilder ascii = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        int numascii = str.charAt(i);
        ascii.append(numascii).append(" ");
    }
    return ascii.toString();
}

编辑:如下方评论者所提到的,请务必阅读有关字符串池、StringBuilder 和StringBuffer的内容:

英文:

You're returning the ascii value immediately after the first iteration, edit your code to look something like below:

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

edit: As mentioned by commenter below, definitely read about String pool, StringBuilder and StringBuffer

huangapple
  • 本文由 发表于 2020年9月2日 07:03:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63696549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定