2014-09-03 42 views
-2

我想學習java,我更喜歡看視頻而不是閱讀。任何你可能想分享學習java的技巧。我知道Java很容易學習,但我仍然不知道它是如何工作的。需要關於代碼的一部分的幫助

int sum = 0; 
System.out.println("Enter multi digit number:"); 
Scanner input = new Scanner(System.in); 
int n = input.nextInt(); 
int t = n; 
while (n > 0) { 
    int p = n % 10; 
    sum = sum + p; 
    n = n/10; 
} 
System.out.println("sum of the digits in " + t + " is " + sum); 

對於這段代碼,爲什麼需要int t = n?我知道它顯示了輸入的數字,但爲什麼我不能在system.out上使用n?我曾嘗試代碼沒有INT噸,只是n放在系統輸出,但其顯示我0

+0

因爲在循環中'n'正在改變。所以它首先將它複製到't'。 – Adi 2014-09-03 06:38:23

+2

1.建議對於StackOverflow是無關緊要的。 2.因爲你在循環中改變了'n'。 – Michael 2014-09-03 06:38:32

+0

由於'n'在'while'循環中被重新分配,'n = n/10;',你不會先給它賦一個臨時值,它會丟失,你永遠不會知道它是什麼 – MadProgrammer 2014-09-03 06:38:38

回答

1

您只需將n(實際值)的值保存在t一側。

// takes integer 
int n = input.nextInt(); 
// saves integer, for showing in results 
int t = n; 
// runs loop, takes sum and other stuff below 
while (n > 0) { 
     int p = n % 10; 
     sum = sum + p; 
     // here the n changes, that is why the value was saved in 't' 
     n = n/10; 
} 

..這個只會保存,所以在代碼結束時,您的實際值是由用戶提供的。因爲在循環中,您將n的值除以10來改變它。

0

回答第二個問題的結果

  while (n > 0) { 
       int p = n % 10; 
       sum = sum + p; 
       n = n/10; // n value changes here 
     } 

所以這個循環之後使用n值您需要將其複製到一個臨時變量,例如t

0
 int n = input.nextInt(); // let us imagine value of n = 98 now 

     int t = n; //now value of t = n = 98 

     while (n > 0) { 
       int p = n % 10; //here value of p = 8 
       sum = sum + p; 
       n = n/10; // here value of n = 9 , since n is int no decimal places 
     } 

     // now you can use t to print out the original value entered by user 
     // if u had not saved the value of n into t , 
     // you could not print out the value user entered as value of n is different 
     System.out.println("sum of the digits in " + t + " is " + sum); 

     There are many video tutorial on internet . Search for Bucky Roberts,Java 
     brains,sharmanj etc and pick the one you like