java 公共字符串简写(字符串输入)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2760776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:42:11  来源:igfitidea点击:

public String shorthand(String in)

java

提问by luvthug

I am stuck on this code.

我被困在这个代码上。

The code should use the class StringBuilder to build an output string by appending non-vowel characters from its argument in to the result it returns. It needs to identify vowels to be removed using the helper method i created which is public boolean isVowel(char c).

代码应该使用 StringBuilder 类通过将其参数中的非元音字符附加到它返回的结果中来构建输出字符串。它需要使用我创建的辅助方法来识别要删除的元音,该方法是 public boolean isVowel(char c)。

public String shorthand(String in)this is the method I need help with. I have created the stringbuilder but the if condition does not accept isVowel method.

public String shorthand(String in)这是我需要帮助的方法。我已经创建了 stringbuilder 但 if 条件不接受 isVowel 方法。

import java.io.*;
import java.util.*;


public class Shorthand
{    

    public boolean isVowel(char c)
   {

       if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A'|| c == 'E'||c == 'I'|| c == 'O'|| c == 'U')
       {
           return true;
       }
       else
       {
           return false;
       }
   }

    //TODO Complete the shorthand method
    public String shorthand(String in) //this is the code I need help with
    {
      StringBuilder vowel = new StringBuilder();

      if (isVowel() == false)
      { 
        vowel.append(in); 
       } 
          return vowel.toString(); 
    }

    //TODO Complete the run method
    public void run() throws IOException
    {
       String yourLine; 
       Scanner sc = new Scanner(System.in); 
       yourLine = sc.nextLine(); 
       while(!yourLine.equals("*"));
       {
            System.out.println("Enter your line of text");
       }
       yourLine = sc.nextLine(); 
    }
}

回答by ryanprayogo

You didn't pass the char cargument of isVowel()

你没有传递char cisVowel()的参数

Try this:

试试这个:

public String shorthand(String in) { 
        StringBuilder vowel = new StringBuilder();

        for (char c : in.toCharArray()) {
            if (!isVowel(c)) {
                vowel.append(c);
            }
        }

        return vowel.toString();
}

EDIT: Your run()method seems to be a bit weird...

编辑:你的run()方法似乎有点奇怪......

Maybe the following is what you wanted?

也许以下是你想要的?

public void run() throws IOException
{
    String yourLine;
    Scanner sc = new Scanner(System.in);
    while (!sc.nextLine().equals("*")) {
        System.out.println("Enter your line of text");
    }
}

On a side note, it doesn't even call the shorthand()method.

附带说明一下,它甚至不调用该shorthand()方法。

回答by polygenelubricants

There is a lot to be learned from your code.

从您的代码中可以学到很多东西。

On returning a boolean expression

返回布尔表达式

Here's an improved version of isVowel(char ch):

这是 的改进版本isVowel(char ch)

public boolean isVowel(char ch) {
    ch = Character.toLowerCase(ch);
    return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
}

Note two things here:

这里要注意两点:

  • chis simplified to the lower case form, so you have much fewer checks
  • There is no ifstatement.
  • ch简化为小写形式,因此您的检查要少得多
  • 没有if声明。

There is an important lesson here: you should never write something like this:

这里有一个重要的教训:你永远不应该写这样的东西:

if (expression) {
   return true;
} else {
   return false;
}

You should always instead write:

你应该总是写:

return expression;

This is much, much clearer.

这要清楚得多。



On familiarizing yourself with the Java library

熟悉 Java 库

Note the use of Character.toLowerCasein the above code. In fact, it's possible to make the code even simpler by using, e.g. String.indexOf:

注意Character.toLowerCase上面代码中的使用。事实上,可以通过使用例如使代码更简单String.indexOf

public boolean isVowel(char ch) {
    return "aeiouAEIOU".contains("" + ch);
}

This uses String.contains, using string concatenation to effectively convert the charto a String(which implements CharSequence).

这使用String.contains,使用字符串连接有效地将 the 转换char为 a String(which implements CharSequence)。

API link

接口链接

See also

也可以看看



Don't compare against boolean constants

不要与布尔常量进行比较

Beginners tend to write something like this:

初学者倾向于写这样的东西:

if (expression1 == false) {
}
//...
if (expression2 == true) {
}

Especially in Java, you should learn to write like this instead:

尤其是在 Java 中,你应该学会这样写:

if (!expression1) {
}
//...
if (expression2) {
}

This is much clearer, and much less error prone.

这更清晰,并且更不容易出错。

See also

也可以看看



On iterating over every character of a String

迭代一个字符的每个字符 String

Here's a simple loop to show how the indexed way of doing this:

这是一个简单的循环,用于显示索引方式如何执行此操作:

    String s = "Abracadabra";
    for (int i = 0; i < s.length(); i++) {
        System.out.print("[" + s.charAt(i) + "]");
    } // prints "[A][b][r][a][c][a][d][a][b][r][a]"

This uses the length()and charAt(int index)methods of String.

这使用 的length()charAt(int index)方法String

Alternatively, if you don't need the index, you can also use String.toCharArray()to do a foreach on the char[]instead. This is not space efficient (the char[]has to be newly allocated to guarantee immutability), but is very readable and concise:

或者,如果您不需要索引,您也可以使用String.toCharArray()foreachchar[]代替。这不是空间有效的(char[]必须重新分配以保证不变性),但非常可读和简洁:

    String s = "Abracadabra";
    for (char ch : s.toCharArray()) {
        System.out.print("[" + ch + "]");
    } // prints "[A][b][r][a][c][a][d][a][b][r][a]"

See also

也可以看看



On the software development process

关于软件开发过程

As others have mentioned, your runmethod is very problematic: it currently results in an infinite loop.

正如其他人所提到的,您的run方法非常有问题:它目前会导致无限循环。

What you could have done instead is write what are called "method stubs" for isVowel(e.g. simply return true;) and shorthand(e.g. simply return "";). They're not correct yet, but the important thing is that they compile for now. This gives you time to focus on run, to make sure that you have a properly working loop, and that you are able to extract the relevant input from the user. You should bring the code to the point where it compiles and runs, so you can test and be confident that your rundoes what it needs to do. At that point, you can start to fill out to previously stubbed methods, implementing the proper functionalities as required.

你可以做的是为(例如简单)和(例如简单)编写所谓的“方法存根” 。它们还不正确,但重要的是它们现在可以编译。这让您有时间专注于,以确保您有一个正常工作的循环,并且您能够从用户那里提取相关输入。您应该将代码带到可以编译和运行的地方,这样您就可以测试并确信您做了它需要做的事情。那时,您可以开始填充先前存根的方法,根据需要实现适当的功能。isVowelreturn true;shorthandreturn "";runrun

If you're having difficulty achieving that, you can ask questions about that particular aspect of the homework (but search for it first on stackoverflow!). This gives you high quality and focused answers on problems as you encounter them (as oppose to posing such a problematic code that people can go all over the place on it), and is therefore more instructive for your own sake.

如果您在实现这一目标时遇到困难,可以询问有关作业特定方面的问题(但请先在 stackoverflow 上搜索它!)。当您遇到问题时,这会为您提供高质量和重点突出的答案(反对编写如此有问题的代码,以至于人们可以在上面到处乱翻),因此对您自己来说更具指导意义。

The question is also likely to be more useful to others since it's more general in context (i.e. it's about how to write a user prompt loop, not about how to do your homework) (in contrast, this question is currently titled public String shorthand(String in)).

这个问题也可能对其他人更有用,因为它在上下文中更通用(即它是关于如何编写用户提示循环,而不是关于如何做作业)(相比之下,这个问题目前的标题是public String shorthand(String in))。

Another thing you can do is perform what are called unit tests. isVowelis a GREATcandidate for this: to test its correctness, you'd have to know how to invoke it (something which you apparently are having problem with).

您可以做的另一件事是执行所谓的单元测试isVowel是一个很好的候选者:为了测试它的正确性,你必须知道如何调用它(你显然有问题)。

All of this seems to be unnecessary work at first. Presumably the unit tests aren't part of the homework (though it probably should be), and writing stubs and then replacing it with something else seems like a waste of time and that you should just get it right the first time instead. Precisely because this is a homework assignment, though, you should adopt and practice the methodologies of good software development process. It's for your own good.

所有这些起初似乎都是不必要的工作。大概单元测试不是作业的一部分(尽管它可能应该是),并且编写存根然后用其他东西替换它似乎是在浪费时间,而您应该在第一次就做对。正因为这是一项家庭作业,您应该采用并实践良好软件开发过程的方法论。这是为了你好。

See also

也可以看看

回答by mdma

You want something like this

你想要这样的东西

public String shorthand(String in)
{
      int length = in.length();
      StringBuilder noVowels = new StringBuilder(length);
      for (int i=0; i<length; i++)
      {
         c = in.charAt(i);
         if (!isVowel(c))
           noVowels.append(c);
      }
      return noVowels.toString(); 
}

PS: Your isVowel method only checks for lowercase. If you want to recognise vowels in both upper and lower case, call Character.toLowerCasein the first line of isVowel.

PS:你的 isVowel 方法只检查小写。如果要识别大小写元音,请调用Character.toLowerCaseisVowel 的第一行。

EDIT: I didn't comment on the run() method because I presumed that was work in progress. As you're having problems with that, here's a corrected version.

编辑:我没有对 run() 方法发表评论,因为我认为该方法正在进行中。由于您遇到了问题,这里有一个更正的版本。

public static void main(Stirng[] args) throws IOException
{
   Scanner sc = new Scanner(System.in);
   for(;;) {
    System.out.println("Enter your line of text");
    String line = sc.nextLine();
    if (line.equals("*")) break;
    String shortHandLine = shorthand(line);
    System.out.println(String.format("Shorthand form of %s is %s", line, shortHandLine));
   }    
}

As this is an application, you can right click and run this in most IDEs.

由于这是一个应用程序,您可以右键单击并在大多数 IDE 中运行它。

回答by Uri

Please tag this as homework

请将此标记为作业

To the point: lots of problems here

重点:这里有很多问题

First, you need to have your main actually call shortHand on each line, and probably print the results.

首先,您需要让您的 main 在每一行上实际调用 shortHand,并可能打印结果。

Second, your shorthand function should iterate over all the characters of the string, right now you are not doing that. You will be passing each character to the isVowel function.

其次,你的速记函数应该遍历字符串的所有字符,现在你没有这样做。您将把每个字符传递给 isVowel 函数。

回答by Chris Knight

You need to pass a char value to the isVowel()method. Try the following:

您需要将一个字符值传递给该isVowel()方法。请尝试以下操作:

public String shorthand(String in) 
{
  StringBuilder vowel = new StringBuilder();

  for (int i=0; i < in.length(); i++)
  {
      if (isVowel(in.charAt(i)) == false)
      { 
        vowel.append(in.charAt(i)); 
      }
  } 
  return vowel.toString(); 
}