java 如何将 int 分配给 String 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13571957/
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-31 13:15:46  来源:igfitidea点击:

How can I assign an int to a String variable?

javastringvariablesint

提问by user1854447

I am currently making an assignment for Java but I am stuck. I have to make a birthdate from the three parameters: day, month and year, which are numbers = int. With this I have to put in some checks for valid dates. That part I think is done, but I get stuck at the following:

我目前正在为 Java 分配一个任务,但我被卡住了。我必须从三个参数中创建一个生日:日、月和年,它们是 numbers = int。有了这个,我必须检查一些有效日期。我认为这部分已经完成,但我陷入了以下问题:

I want an if statement to check the day, and if the day is correct, this block of code should be run trough

我想要一个 if 语句来检查这一天,如果这一天是正确的,这块代码应该运行

if (dag >=1 && dag <=31) 
{
    datum = dag; 
}

datumIs a String, because I want to get the date like this: DD-MM-YYY And dagis an Int. So whenever I try to compile this, BlueJ gives an error at this part saying "incompatible types". I assume this is because I try to place a Int in a String. Is this possible in any way, because I can't find out how.

datum是一个字符串,因为我想得到这样的日期:DD-MM-YYY 并且dag是一个 Int。所以每当我尝试编译它时,BlueJ 在这部分给出一个错误,说“不兼容的类型”。我认为这是因为我尝试在字符串中放置一个 Int。这是否可能以任何方式,因为我不知道如何。

回答by Rohit Jain

Use String.valueOfmethod to convert intto string: -

使用String.valueOf方法转换intstring:-

int i = 32;
String str = String.valueOf(i);

And of course follow the advice in @Brian's answeras to what you should rather do in your case.

当然,请遵循@Brian 回答中的建议,了解在您的情况下您应该做什么。

回答by Brian Agnew

Don't make it a string. it's not. I think you should

不要让它成为一个字符串。不是。我觉得你应该

  1. create a Dateobject to represent your date (day/month/year combined)
  2. use SimpleDateFormatto print that date out in the appropriate format
  1. 创建一个Date对象来表示您的日期(日/月/年组合)
  2. 使用SimpleDateFormat以适当的格式打印该日期

That's the proper OO way to do it. Otherwise you end up with a bunch of disparate disconnected variables representing in their combination some object type, but you can't manipulate them atomically, invoke methods on them etc. Holding everything as strings is known as stringly-typing(as opposed to strongly-typing) and is a particularly bad code smell!

这是正确的 OO 方式。否则,您最终会得到一堆不同的断开连接的变量,它们组合起来代表某种对象类型,但您不能以原子方式操作它们,调用它们的方法等。将所有内容保存为字符串被称为字符串类型(与类型相反)键入) 并且是一种特别糟糕的代码气味!

At some stage check out Joda-Timefor a better date/time API than those suggested above. However for the moment I suspect you've got enough on your plate without downloading extra jars.

在某个阶段,请查看Joda-Time以获得比上面建议的更好的日期/时间 API。然而,目前我怀疑你的盘子里已经足够了,而无需下载额外的罐子。