【发布时间】: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