2011-11-23 77 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. 
    } 
}