java定义变量str_java – 在if / else构造中声明变量

我在CodingBat.com(extraFront)上解决了一个基本的Java字符串问题.

任务是给定一个任意长度的字符串,返回重复三次的两个第一个字符.第一个例子是我最终直观地做的事情:

public String extraFront(String str) {

if (str.length() <= 2){

String front = str;

}else{

String front = str.substring(0,2);

}

return front+front+front;

}

哪个给我一个错误,前面无法解决.我猜我需要在循环外定义变量,所以我将代码更改为以下代码,它可以正常工作:

public String extraFront(String str) {

String front;

if (str.length() <= 2){

front = str;

}else{

front = str.substring(0,2);

}

return front+front+front;

}

令我困惑的是为什么这应该有所作为,因为无论如何变量将被宣布,不是吗?这是CodingBat如何处理代码的特性,还是这实际上是一个错误?如果是,为什么这个错误的代码到底是什么?如果它不是不正确的,它是不好的风格?

解决方法:

What puzzles me is why this should make a difference, as the variable is going to declared anyway, will it not?

这是一个范围问题.变量仅在声明它的块中可见.这与CodingBat无关 – 它是Java语言的一部分.从section 6.3 of the JLS开始:

The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is visible (§6.4.1).

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.

我还恳请您了解conditional operator,它可以在以下情况下提供帮助:

String front = str.length() <= 2 ? str : str.substring(0, 2);

标签:java,variables,declaration

来源: https://codeday.me/bug/20190901/1780062.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值