Java 字符串参数

发布于 2024-07-10 08:40:00 字数 312 浏览 5 评论 0原文

我来自 .net 背景,想知道创建返回布尔值并修改通过参数传入的字符串的方法的可接受方式。 我知道字符串在 Java 中是不可变的,因此下面的代码片段将始终生成一个空字符串。 我只能返回布尔值。 不能抛出异常。 如果我需要将 String 类包装在 StringHolder 中,我可以在哪个包中找到它。

public static void DoStuff()
{
    String msg = "";
    if (GetMessage(msg))
    {
       System.out.println(msg);
    }
}

I'm coming from a .net background and want to know the accepted way of creating a method that returns a boolean and modifies a string that was passed in via parameter. I understand Strings are immutable in Java so the below snippet will always produce an empty string. I am constrained to return boolean only. Exceptions can't be thrown. If I need to wrap the String class in, say, a StringHolder, what package could I find this in.

public static void DoStuff()
{
    String msg = "";
    if (GetMessage(msg))
    {
       System.out.println(msg);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

失而复得 2024-07-17 08:40:00

使用 java.lang.StringBuilder - 基本上是一个可变字符串。 然而,返回修改后的字符串会更安全、更“Java 风格”。

Use a java.lang.StringBuilder - basically a mutable String. However, it would be safer and more "Java style" to return the modified String.

若言繁花未落 2024-07-17 08:40:00

我强烈建议你不要使用 StringBuilder、holder 或类似的。 他们是黑客。 您希望使用字符串,而不是构建器。

最明显的方法是返回一个包含要返回的数据的对象。 David 的 [bombe.livejournal.com's] 解决方案涵盖了这一点,因此我不再重复。 然而,我建议不要试图使其成为通用的数据球,而是使其具体化。 让它像一个物体一样,也许它甚至可以长出真正的行为。 (如果您真的想要去镇上,隐藏构造函数并给它一个静态创建方法。)

第二种方法是反转调用,在 Java 中支持得不太好。 不返回结果,而是告诉回调结果。

(更重要的)使用代码将类似于(它看起来有点奇怪,因为它不特定,也不是通用的):

String userMessage = thing.doStuff(new StuffHandler<String>() {
    public String stuff(boolean success, String message) {
        return message+" was "+(success ? "succesful" : "unsuccesful");
    }
});

实现类似于:

public interface StuffHandler<T> {
    T stuff(boolean success, String message);
}

[...]

    public <T> T doStuff(StuffHandler<T> handler) {
        handler.stuff(isSuccess(), getMessage());
    }

第三种方法是将方法简单地分成两部分。 这可能可行,也可能不可行。

I strongly suggest you do not use StringBuilder, holder or similar. They are hacks. You want to be working with Strings, not builders.

The most obvious approach is to return an object containing the data you want to return. David's [bombe.livejournal.com's] solution covers that, so I won't repeat it. However, I would suggest instead of trying to make it generic ball of data, make it specific. Make it like an object, perhaps it could even grow real behaviour. (And if you really want to go to town, hide the constructor and give it a static creation method instead.)

A second approach, not so well supported in Java, is to invert the calls. Instead of returning a result, tell a callback the result.

The (more important) usage code would be something like (it looks a bit odd because it isn't specific, nor is it generic):

String userMessage = thing.doStuff(new StuffHandler<String>() {
    public String stuff(boolean success, String message) {
        return message+" was "+(success ? "succesful" : "unsuccesful");
    }
});

The implementation goes something like:

public interface StuffHandler<T> {
    T stuff(boolean success, String message);
}

[...]

    public <T> T doStuff(StuffHandler<T> handler) {
        handler.stuff(isSuccess(), getMessage());
    }

A third approach is simply to break the method in two. That may or may not be feasible.

同展鸳鸯锦 2024-07-17 08:40:00

首先我可能不会有这些要求。 我确信它们可以解决。 如果您不想这样做,我建议您为两个结果返回一个容器对象:

public class ResultContainer {
    private final boolean success;
    private final String result;
    public ResultContainer(boolean success, String result) {
        this.success = success;
        this.result = result;
    }
    public boolean isSuccess() { return success; }
    public String getResult() { return result; }
}

在您的主代码中:

ResultContainer resultContainer = GetMessage(message);
if (resultContainer.isSuccess()) {
    System.out.println(resultContainer.getResult());
}

GetMessage() 显然会创建一个 的新实例ResultContainer 并返回它,并填充返回值。

(将泛型用于 ResultContainer 留给读者作为练习。)

First off I probably wouldn’t have these requirements. I’m sure they can be worked around. If you don’t want to do that, I’d recommend returning a container object for your two results:

public class ResultContainer {
    private final boolean success;
    private final String result;
    public ResultContainer(boolean success, String result) {
        this.success = success;
        this.result = result;
    }
    public boolean isSuccess() { return success; }
    public String getResult() { return result; }
}

And in your main code:

ResultContainer resultContainer = GetMessage(message);
if (resultContainer.isSuccess()) {
    System.out.println(resultContainer.getResult());
}

GetMessage() would obviously create a new instance of a ResultContainer and return it, filled with the return values.

(Using Generics for the ResultContaineris left as an exercise for the reader.)

聆听风音 2024-07-17 08:40:00

通过利用泛型,可以将更优雅的持有者类重用于任何类型的对象:

public class Holder<T> {
  T item;
  public Holder( T item) { set( item);}
  public T get( ) { return item;}
  public void set( T item) { this.item = item;}
}

DoStuff( ) 看起来像:

public static void DoStuff( ) {
  String msg = "";
  Holder<String> holder = new Holder<String>( msg);
  if ( getMessage( holder)) { System.out.println( holder.get( ));}
}

并且 GetMessage( ) 必须调用 holder.set(a_string)

A more elegant holder class could be reused for any type of object by utilizing generics:

public class Holder<T> {
  T item;
  public Holder( T item) { set( item);}
  public T get( ) { return item;}
  public void set( T item) { this.item = item;}
}

DoStuff( ) would then look like:

public static void DoStuff( ) {
  String msg = "";
  Holder<String> holder = new Holder<String>( msg);
  if ( getMessage( holder)) { System.out.println( holder.get( ));}
}

and GetMessage( ) would have to call holder.set( a_string).

辞慾 2024-07-17 08:40:00

Java 是一种基于类的面向对象语言,因此它的习惯用法倾向于创建类来封装数据及其周围的行为。

你有一个数据——消息——以某种方式获得,然后如果满足某些条件,就会用它来做其他事情。 使该行为成为外部控制对象中的 get、if 和其他操作序列通常表明程序员不理解 OOP。

我只能返回布尔值。 不能抛出异常。

我可以建议你应该使用 Fortran 或 C 而不是 Java 吗? 过程语言通常具有突变和返回标志的习惯用法,这非常适合该范例(在没有自动内存管理的情况下,调用者创建并传入已填充的缓冲区;这允许在以下情况下安全地释放缓冲区)调用者已经完成了;Java 不需要这样做,所以如果你看看 Map.get() 它会返回一个 String 或 null 如果失败 - 不需要管理调用者中的内存)。 至少,不要费心去寻找惯用的 Java 中可接受的方法 - 有了这些限制,它就不会了,无论谁将它们强加给你,都做出了错误的选择,这意味着你要么有黑客攻击,或者最终得到冗长的代码,试图制定一个非 hacky 的解决方案。

Java's a class-based object oriented language, so its idioms tend to create classes to encapsulate data with the behaviour that surrounds it.

You have a datum - the message - which is obtained in some manner, then if some condition is met, something else is done with it. Making that behaviour a sequence of gets, ifs and other operations in an external controlling object is often a sign that the programmer hasn't understood OOP.

I am constrained to return boolean only. Exceptions can't be thrown.

May I suggest you should be using Fortran or C rather than Java? Procedural languages often have the idiom of mutation and returning a flag, which is well suited to that paradigm (in the absence of automatic memory management, the caller creates and passes in a buffer which is populated; this allows the buffer to be freed safely when the caller is done with it; Java doesn't need to do that, so if you look at say Map.get() it returns a String or null if it fails - no need to manage the memory in the caller). At least, don't bother trying to find the accepted way of doing it in idiomatic Java - with those constraints, it won't be, and whoever is forcing them on you has made a bad choice, which will mean you either have hacks, or end up with verbose code trying to make a non-hacky solution.

南七夏 2024-07-17 08:40:00

您不能使用字符串作为输出参数。 执行此操作的方法是使用 StringBuilder 类,或者在失败时返回 null。

此处讨论

You can't use a string as an output parameter. The way to do it would be to use a StringBuilder class instead or return null for a failure.

Discussion Here

浅唱ヾ落雨殇 2024-07-17 08:40:00

字符串是不可变的,所以是的,您需要将字符串包装在 StringHolder 中。 你可以自己写,就像这样简单

  class StringHolder
  {
     String msg;
  }

  StringHolder sMsg = new StringHolder();
  sMsg.msg = "";
  if (GetMessage(sMsg))
  {
     System.out.println(sMsg.msg);
  }

Strings are immutable, so yes, you will need to wrap the String in a StringHolder. You can write your own as simply as

  class StringHolder
  {
     String msg;
  }

  StringHolder sMsg = new StringHolder();
  sMsg.msg = "";
  if (GetMessage(sMsg))
  {
     System.out.println(sMsg.msg);
  }
不寐倦长更 2024-07-17 08:40:00

一个普通的 StringHolder 就是一个 String[1]。


bool GetMessage(String[] output)
{
     if(output.length < 1)
          throw new Exception("Output must be a String[1]");
     output[0] = "You win!";
}

public static void DoStuff()
{
      String[] msg = new String[1];
      if(GetMessage(msg))
      {
          System.out.println(msg[0]);
      }
}

不过,StringBuilder 可能是执行此操作的规范方法。

A trivial StringHolder would be a String[1].


bool GetMessage(String[] output)
{
     if(output.length < 1)
          throw new Exception("Output must be a String[1]");
     output[0] = "You win!";
}

public static void DoStuff()
{
      String[] msg = new String[1];
      if(GetMessage(msg))
      {
          System.out.println(msg[0]);
      }
}

StringBuilder is probably the canonical way to do it, though.

凤舞天涯 2024-07-17 08:40:00

这是一些奇怪的要求。

为什么不以正确的方式(或者至少是java的方式)来做呢? 就像试图从一个函数中获得两个结果。 就像减法( 2 , 2 ) 返回 0 和“早上好先生”一样。

好吧,无论如何,你可以尝试这两个选项。

第一。 StringBuilder 这不是最好的选择,因为您不是“构建”字符串。

public static void doStuff(){
    String msg = "";
    StringBuilder sb = new StringBuilder();
    if ( getMessage( sb ) ) {
        System.out.println( sb );
    }
}

public static boolean getMessage( StringBuilder sb ) {
    if ( "".equals( sb.toString() )) {
        sb.delete( 0, sb.length() );
        sb.append("It was empty");
        return true;
    } else {
        return false;
    }
}

第二个StringHolder(任何与此相关的支架)也不是太java风格,但可以完成工作。 这将是我认识的大多数 Java 开发人员使用的方法。

public static void doStuff(){
    String msg = "";
    String [] holder = { msg };
    if ( getMessage( holder ) ){
        System.out.println( holder[0]  );
    }
}
public static boolean getMessage( String [] holder ) {
    if ( "".equals(  holder[0] )) {
        holder[0] = "It was empty";
        return true;
    } else {
        return false;
    }
}

第三。 选项。 不是你要求什么,而是我会做什么。 不幸的是违反了“返回布尔值”条件。

public void doStuff() { 
    String msg = "";
    String result = getMessage( msg );
    if ( result != msg ) {
        System.out.println( result );
    }
}
public static String getMessage( String msg ) {
    if ( "".equals(msg){
        return "It was empty";
    }
    return msg
}

选一个。

注意

虽然不是每个人都喜欢这个(Jon Skeet 会说“没有被普遍接受”),但请看一下我正在使用的 java 编码风格(以小写字母和大括号开头的方法)线 )。 有时尊重您正在编码的平台很重要。至少我在使用 C# 编码时就是这么做的(顺便说一句,很少)

That is some strange requirement.

Why don't do it the right way ( or at least the java way ) ? Is like trying to get two results from a function. Like subtract( 2 , 2 ) returns 0 and "Good morning sir".

Well anyway, you can try these two options.

1st. StringBuilder Not the best thing to use, since you're not "building" an String.

public static void doStuff(){
    String msg = "";
    StringBuilder sb = new StringBuilder();
    if ( getMessage( sb ) ) {
        System.out.println( sb );
    }
}

public static boolean getMessage( StringBuilder sb ) {
    if ( "".equals( sb.toString() )) {
        sb.delete( 0, sb.length() );
        sb.append("It was empty");
        return true;
    } else {
        return false;
    }
}

2nd StringHolder ( anything holder for that matter ) Not too java style either but do the work. This would be the one used by most java developer I know.

public static void doStuff(){
    String msg = "";
    String [] holder = { msg };
    if ( getMessage( holder ) ){
        System.out.println( holder[0]  );
    }
}
public static boolean getMessage( String [] holder ) {
    if ( "".equals(  holder[0] )) {
        holder[0] = "It was empty";
        return true;
    } else {
        return false;
    }
}

3rd. Option. not what you asked but what I would do. Unfortunately violates the "return boolean" condition.

public void doStuff() { 
    String msg = "";
    String result = getMessage( msg );
    if ( result != msg ) {
        System.out.println( result );
    }
}
public static String getMessage( String msg ) {
    if ( "".equals(msg){
        return "It was empty";
    }
    return msg
}

Choose one.

Note

Although not everyone likes this ( Jon Skeet would say "Is not universally accepted" ) , please take a look at the java coding style I'm using ( methods starting with lower case and braces in the same line ). Sometimes it is important to respect the platform you're coding in. At least that's what I do when I code in C# ( very seldom btw )

栖竹 2024-07-17 08:40:00

<代码>
公共布尔 doStuff(String msg)
{
布尔布尔测试 = false;
msg += "向 msg 添加一些内容";
int msgLength = msg.length();
如果(消息长度> 80)
{
布尔测试=真;
返回布尔测试;
}
返回布尔测试;
}

这是您正在寻找的吗? 我假设布尔测试类似于测试更改的消息是否对于显示来说太长(大于 80 长度)或类似的东西,并且您不需要调用另一个方法来更改 doStuff 内部的消息字符串()。

不过,这里可能完全偏离基地。 :-)


public boolean doStuff(String msg)
{
boolean boolTest = false;
msg += "Appending something to msg";
int msgLength = msg.length();
if ( msgLength > 80 )
{
boolTest = true;
return boolTest;
}
return boolTest;
}

Is this kind of what you're looking for? I'm assuming the boolean test is something like testing if the changed message is too long for a display (greater than 80 length) or something similar, and that you don't need to call another method to change the message string inside of doStuff().

Could be completely off-base here, though. :-)

旧人哭 2024-07-17 08:40:00

首先,您编写程序并通过如下代码制作它们:

Process p = Runtime.exec("java GetMessage.class " + String);

提示:Runtime.exec 应该在任何地方使用。 然后就可以制作很多程序了。

然后你等待返回这样的状态代码:

if (p.returnCode() = 1) 
  Out.printWord("1 made back"):
else 
  {
  Out.printWord("B Made back");
  }

这样你就可以使用该程序,就像在该程序之外一样。 使代码可重用是件好事。 从我这里拿走吧,我已经从事这个行业很多年了。 这就是专业人士编写代码的方式。

first u write teh programs and make them from the code like this:

Process p = Runtime.exec("java GetMessage.class " + String);

Tip for you : Runtime.exec should be used everywhere. Then you can make many programs.

Then u wait to get back a status code like this:

if (p.returnCode() = 1) 
  Out.printWord("1 made back"):
else 
  {
  Out.printWord("B Made back");
  }

This way u can use the program else like out side of this program. It is good to make the code resusable. Take it from me, I've been in it for years. This is how the pros make code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文