函数在java中返回一个字符串(function to return a string in java)

编程入门 行业动态 更新时间:2024-10-19 03:34:54
函数在java中返回一个字符串(function to return a string in java)

我编写了下面的函数来将毫秒时间转换为格式为mins的字符串:秒。 作为一名前C程序员,我认为“ans”必须是静态的才能正常工作,但在String之前放置静态似乎是不允许的。

我的问题是 - 这个功能会起作用吗?如果不能,将会发生什么样的变化。

public String time_to_string(long t) // time in milliseconds { String ans; int mins,secs; if (t < 0) { return "-"; } else { secs = (int)(t/1000); mins = secs/60; secs = secs - (mins * 60); ans = ""+mins+":"+String.format("%02d", secs); return ans; } }

I wrote the following function to convert a time in milliseconds to a string of the format mins:seconds. Being a former C programmer I assumed that "ans" would have to be static in order to work properly, but putting static before String appears to not be allowed.

My question is - will this function work - and if not, what change will make it work.

public String time_to_string(long t) // time in milliseconds { String ans; int mins,secs; if (t < 0) { return "-"; } else { secs = (int)(t/1000); mins = secs/60; secs = secs - (mins * 60); ans = ""+mins+":"+String.format("%02d", secs); return ans; } }

最满意答案

你的代码很好。 以这种方式返回Strings没有问题。

在Java中, String是对不可变对象的引用。 这与垃圾回收相结合,可以解决很多潜在的复杂问题:您可以简单地传递一个String ,而不用担心它会让你感到厌倦,或者某个地方会修改它。

如果您不介意制作几个文体建议,我会修改代码,如下所示:

public String time_to_string(long t) // time in milliseconds { if (t < 0) { return "-"; } else { int secs = (int)(t/1000); int mins = secs/60; secs = secs - (mins * 60); return String.format("%d:%02d", mins, secs); } }

正如你所看到的,我尽可能地将变量声明推得尽可能小(这是C ++和Java中的首选风格)。 我也消除了ans ,并用String.format()的单个调用替换了字符串连接和String.format()的混合。

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds { if (t < 0) { return "-"; } else { int secs = (int)(t/1000); int mins = secs/60; secs = secs - (mins * 60); return String.format("%d:%02d", mins, secs); } }

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

更多推荐

本文发布于:2023-08-07 13:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464565.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   函数   java   string   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!