我试图创建一个程序,使字符串s1等于某些文本,具体取决于hours变量。问题是当我运行程序时s1找不到。我刚刚开始使用Java,所以我不确定这是否真的效率低下,或者它是不是很简单,我不知道。
代码:
export default Vue.component('radioButton', {
template,
props: ['name', 'label', 'id', 'value']
})
答案 0 :(得分:2)
变量的范围是声明变量的块。块从开口花括号开始,并在匹配的闭合花括号处停止。因此,您要声明三个不同的变量,这些变量在其块之外是不可见的(这就是为什么Java允许您使用相同的名称将其声明三次)。
在块之外声明变量一次:
String s1;
if (b5) {
s1 = "You have played for " + arr[0] + " hours!";
}
...
答案 1 :(得分:2)
试试这个..
int[] arr;
arr = new int[2];
arr[0] = 1;
boolean b1 = arr[0] > 1;
boolean b2 = arr[0] < 1;
boolean b4 = 0 > arr[0];
boolean b3 = b4 && b2;
boolean b5 = b1 || b3;
String s1 = "";
if (b5) {
s1 = "You have played for " + arr[0] + " hours!";
}
else if (arr[0] == 1) {
s1 = "You have played for 1 hour!";
}
else if (arr[0] == 5) {
s1 = "You have not played at all!";
}
else {
s1 = "Memory Error in arr[0], Are the hours negative? Is it there?";
}
System.out.print (s1);
}
答案 2 :(得分:0)
您需要在main方法的开头定义String s1,如下所示:
String s1;
稍后,当您设置s1(在if,else语句中)时,您可以写:
s1 = "You have played for......";
这样,s1将在代码的开头声明。
答案 3 :(得分:0)
代码块内部发生了什么,保留在该代码块中。如果您在if block
中声明变量,则if block
之外的变量不可见 - 甚至不在else if
和else
个案例中。您的代码不应该编译,因为之前没有声明最后的s1
。
String s1;
if (b5) {
s1 = "You have played for " + arr[0] + " hours!";
}
else if (arr[0] == 1) {
s1 = "You have played for 1 hour!";
}
else if (arr[0] == 5) {
s1 = "You have not played at all!";
}
else {
s1 = "Memory Error in arr[0], Are the hours negative? Is it there?";
}
System.out.print(s1);
这应该可以正常工作。