【问题标题】:Decrement operation in JavaJava中的减法运算
【发布时间】:2015-10-09 17:35:38
【问题描述】:

所以我刚刚开始了 IT 课程,作为其中的一部分,我们正在学习用 Java 编写代码;我有一个下周的任务,虽然我想通了,但我只是想知道它为什么有效:P

目标是编写一段代码,读取一个数字,将其递减,将其变为负数,然后输出。

这是我最初的:

  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' 

我的问题是,为什么一元减号在第二种情况下起作用,但在第一种情况下不起作用?

【问题讨论】:

    标签: java operator-keyword decrement


    【解决方案1】:
    --a
    

    类似于

    a = a - 1;
    

    这意味着它首先计算a-1 的值,然后使用a = ... 将该值分配回a

    但在-a 的情况下,您只是在计算负值,但它不会将其重新分配回a。因此,由于您没有对计算出的值做任何事情,它会丢失,因此编译器会通知您,您的代码没有按照您的想法执行。

    尝试使用

    将该结果显式分配回a
    a = -a;
    

    在这条指令之后a 将保持新的价值,你可以在任何地方使用。


    使用时此问题消失

    System.out.println("Your number is: " + (-a) );
    

    因为现在编译器发现正在使用计算值 -a(作为传递给 println 方法的值的一部分)。

    【讨论】:

      【解决方案2】:

      因为您没有分配一元减号的结果。预减量包括一个赋值。

       a = -a; // <-- like this.
      

      在第二次使用(打印)中,您正在使用打印例程中的值(而不是更新a)。

      【讨论】:

        【解决方案3】:

        正如 Elliott Frisch 所解释的,您必须使用否定运算符 (-) 将值重新分配回原始变量,然后才能访问它。

        但为什么减量运算符 (--) 不要求您这样做?这是因为a-- 或多或少是syntactic sugar 对于a = a - 1。它只是写起来更快,而且很常见,每个人都知道它的含义。

        【讨论】:

          【解决方案4】:
          -   Unary minus operator; negates an expression
          

          你的情况

           -a;  
          

          这是一个声明。

          "Your number is: " + (-a) 
          

          这是一种表达方式。

          【讨论】:

            猜你喜欢
            • 2015-09-07
            • 1970-01-01
            • 1970-01-01
            • 2022-11-16
            • 1970-01-01
            • 2014-03-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多