2011-11-23 76 views
2

在这个程序中,如果我输入10时说输入一个值什么是输出? num1变成了10,而num2是6,我不明白num1 = num1是什么意思? 10 = 10 + 2 = 12请解释这个java代码

我想我理解它,它需要10从用户,然后num1被分配的num1 + 2的值,它是12。num2然后变成num112然后12/6 = 2

输出:2

import java.util.*; 

public class Calculate 
{ 
    public static void main (String[] args) 
    { 
     Scanner sc = new Scanner(system.in); 
     int num1, num2; 
     num2 = 6; 
     System.out.print("Enter value"); 
     num1 = sc.nextInt(); 
     num1 = num1 + 2; 
     num2 = num1/num2; 
     System.out.println("result = " + num2); 
    } 
} 
+1

这将是数字2 – Joe

+3

欢迎来到堆栈溢出。在未来的问题中,请将您的确切代码复制粘贴到您的问题中(** not ** retype)。由于任务'{',缺少'''等,因此您在此输入的内容不会编译。 –

回答

4

它指定的num1 + 2值回num1

所以是的,如果num1 = 10,值12将被存储在num1

然后这将除以6,离开2

此外,它从来没有说过num1 = num1,你不能隔离这样的陈述的部分 - 陈述,作业,是num1 = num1 + 2

0

在Java中,等号=是赋值运算符。它评估右侧的表达式并将结果值分配给左侧的变量。因此,如果num1在语句num1 = num1 + 2;之前的值为10,那么在该语句之后它将具有值12

0
num1 = sc.nextInt(); 
num1 = num1 +2; 
num2 = num1/num2; 

在这些语句,=赋值运算符,而不是平等的经营者。当你读它,不要说“等于”,而是“被赋予的价值”:

num1 is assigned the value of sc.nextInt(). 

所以,现在NUM1为10

num1 is assigned the value of num1 + 2 

所以,现在NUM1 12

num2 is assigned the value of num1/num2, or 
num2 is assigned the value of 12/6 

所以,NUM2现在是2

0
  1. 它从用户号码输入。
  2. 向用户输入的数字添加2。
  3. 将此值除以6并将结果添加到num2变量。
  4. 向用户打印“结果=某个数字”。
1

你必须明白的是,num1不会成为一个固定的数字(例如10),它仍然是一个变量。根据定义,变量会有所不同。

当你说x = 10然后x = x+1,到底发生了什么是这样的:y = x + 1,然后x = y

0
num1 = num1 +2; 

意味着要添加2到您NUM1。这可以表示为

num1 += 2; //which means the same as above 

程序的结果将由整数除法你在做决定:

num2 = num1/num2; 
1
int num1, num2; 
num2 = 6; // Now num2 has value 6 
System.out.print(Enter value"); 
num1 = sc.nextInt(); // Now num1 has value 10, which you just entered 
num1 = num1 +2; // num1 is being assigned the value 10 + 2, so num1 becomes 12 
num2 = num1/num2; // Now num1 = 12 and num2 = 6; 12/6 = 2 
System.out.println("result = "+num2); 

你应该得到的2的输出;看到上面的评论...

1
public class Calculate { 
    public static void main (String[] args) { 
     Scanner sc = new Scanner(system.in); // Whatever you read from System.in goes into the "sc" variable. 
     int num1, num2;      // num1 = 0. num2 = 0. 
     num2 = 6;        // num2 = 6. 
     System.out.print(Enter value"); 
     num1 = sc.nextInt();     // Read in the next integer input and store it in num1. 
     num1 = num1 +2;      // num1 gets 2 added to it and stored back in num1. 
     num2 = num1/num2;      // num1 gets divided by num2 and the (integer) result is stored in num2. 
     System.out.println("result = "+num2); // Print out the result which is stored in num2. 
    } 
}