2015-10-09 110 views
1

所以我剛剛開始了一門IT課程,並且作爲其中的一部分,我們正在學習使用Java編寫代碼;我有一個下週的任務,雖然我已經想通了,但我只是有一個問題,爲什麼它的工作原理:P在Java中減少操作

目標是編寫一段代碼,讀取一個數字,減少它,轉動它是負面的,然後輸出它。

這是我原本:

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' 

我的問題是,爲什麼會在二審中一元減工作,但不是第一?

回答

1
--a 

類似於

a = a - 1; 

,這意味着在第一,它計算的a-1值,然後用它a = ...值分配回a

但在-a的情況下,您只是計算負值,但不會將其重新分配回a。所以,因爲你是沒有做任何與計算值它會丟失,所以編譯器通知你,你的代碼不會做你認爲它會做的事。

這一結果儘量明確分配回a

a = -a; 

該指令a之後將舉行,你可以在任何地方使用新的價值。


此問題,當您使用

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

因爲現在編譯器看到的是計算值-a正在使用(作爲傳遞給println方法值部分)消失。

1

因爲您沒有分配一元減號的結果。前遞減包括一項任務。

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

在第二次使用(打印),您在打印日常使用值(而不是更新a)。

0

正如Elliott Frisch解釋的那樣,您必須使用否定運算符(-)將值重新分配回原始變量,然後才能訪問它。

但爲什麼減量運算符(--)不要求您這樣做?這是因爲a--或多或少syntactic sugara = a - 1。這只是寫得更快,而且每個人都知道它的含義是很常見的。

0
- Unary minus operator; negates an expression 

在你的情況

-a; 

這是一個說法。

"Your number is: " + (-a) 

這是一個表達式。