在if / else构造中声明一个变量 [英] declaring a variable inside of if/else construct

查看:161
本文介绍了在if / else构造中声明一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am solving a basic Java string problem on CodingBat.com (extraFront).

任务是给定任意长度的字符串,首先返回两个字符重复三遍。第一个示例是我最终直观地完成的操作:

The task is to, given a string of any length, return the two first characters repeated three times. This first example is what I ended up doing intuitively:

public String extraFront(String str) {

  if (str.length() <= 2){
    String front = str;
  }else{
    String front = str.substring(0,2);
  }
  return front+front+front;
}

这给了我一个错误, front无法解决。我猜想我需要在循环外定义变量,因此我将代码更改为以下代码,该代码可以正常工作:

Which gives me an error, front can not be resolved. I guessed that I needed to define the variable outside the loop, so I changed the code to the following, which works without errors:

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? Is this a peculiarity of how CodingBat handles the code, or is this actually an error? And if it is, why exactly is this incorrect code? And if it is not incorrect, is it bad style?

推荐答案


令我困惑的是为什么应该有所作为,因为无论如何都要声明变量,不是吗?

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

这是范围确定的问题。变量仅在声明该变量的块内可见。这与CodingBat无关-它是Java语言的一部分。摘自JLS的第部分>:

It's a matter of scoping. A variable is only visible within the block where it's declared. This has nothing to do with CodingBat - it's part of the Java language. From section 6.3 of the JLS:


声明的范围是程序的区域,在该区域中可以使用简单的引用引用声明的实体名称,只要可见(第6.4.1节)。

...

块中的局部变量声明(第14.4节)的范围是该块的其余部分在其中出现该声明,从其自己的初始化程序开始,并在本地变量声明语句的右侧包括其他任何声明器。

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.

I d还敦促您了解条件运算符,可以在以下情况下提供帮助:

I'd also urge you to learn about the conditional operator, which can help in these situations:

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

这篇关于在if / else构造中声明一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆