java – 在if / else构造中声明变量
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 在if / else构造中声明变量,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1536字,纯文字阅读大概需要3分钟。
内容图文
我在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 – 在if / else构造中声明变量全部内容,希望文章能够帮你解决java – 在if / else构造中声明变量所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。