Java中的减量运算
所以我刚刚开始了一门IT课程,作为其中的一部分,我们正在学习用Java编写代码;我下周有一个作业,虽然我已经弄明白了,但我有一个问题,为什么它会起作用:P 目标是编写一段代码,读取一个数字,将其递减,将其变为负数,然后输出 这就是我最初的想法:Java中的减量运算,java,operator-keyword,decrement,Java,Operator Keyword,Decrement,所以我刚刚开始了一门IT课程,作为其中的一部分,我们正在学习用Java编写代码;我下周有一个作业,虽然我已经弄明白了,但我有一个问题,为什么它会起作用:P 目标是编写一段代码,读取一个数字,将其递减,将其变为负数,然后输出 这就是我最初的想法: import java.util.Scanner; // imports the Scanner utility to Java public class Question3 { public static void main(Strin
import java.util.Scanner;
// imports the Scanner utility to Java
public class Question3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// defines the scanner variable and sets it to recognize inputs from the user
System.out.println("Please enter a number: ");
//prompts captures a number form the screen
int a = s.nextInt();
// defines an integer variable('a') as to be set by input from the scanner
--a;
// decrement calculation( by 1)
-a;
//inverts the value of a
System.out.println("Your number is: " + a );
// outputs a line of text and the value of a
但是,Eclipse(我正在使用的IDE)无法识别一元减号运算符('-'),因此无法工作。我将其修改为如下所示:
import java.util.Scanner;
// imports the Scanner utility to Java
public class Question3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// defines the scanner variable and sets it to recognize inputs from the user
System.out.println("Please enter a number: ");
//prompts captures a number form the screen
int a = s.nextInt();
// defines an integer variable('a') as to be set by input from the scanner
--a;
// decrement calculation( by 1)
System.out.println("Your number is: " + (-a) );
// outputs a line of text and the inverse of the variable 'a'
我的问题是,为什么一元负号在第二个实例中有效而在第一个实例中无效?因为您没有指定一元负号的结果。预减量包括赋值
a = -a; // <-- like this.
a=-a;// 正如Elliott Frisch所解释的,在访问原始变量之前,必须使用否定运算符(-
)将值重新分配回原始变量
但是为什么减量运算符(--
)不要求您这样做呢?这是因为a--
或多或少代表a=a-1
。它的写作速度更快,而且很普遍,每个人都知道它的意思
--a
类似于
a = a - 1;
这意味着它首先计算a-1
的值,然后使用a=…
it将该值分配回a
但在-a
的情况下,您只是在计算负值,但它不会将其重新分配回a
。所以,由于您并没有使用那个计算出的值做任何事情,它将丢失,所以编译器会通知您,您的代码并没有执行您可能认为它会执行的操作
尝试使用显式地将该结果分配回a
a = -a;
在此指令之后,a
将保存新值,您可以在任何地方使用该值
使用时,此问题将消失
System.out.println("Your number is: " + (-a) );
因为现在编译器看到计算值-a
正在被使用(作为传递给println
方法的值的一部分)
就你而言
-a;
这是一份声明
"Your number is: " + (-a)
这是一个表达
"Your number is: " + (-a)