Menjumlah hasil jumlah - Java - Publisher - Royz Rambo
Ilham Penta
Site menu
Section categories
My articles [6]
Java [14]
Java Programming
Flash [6]
Flash
URL web dan Tutorial [29]
Petualangan [1]
Our poll
Rate my site
Total of answers: 19
Statistics

Total online: 2
Guests: 2
Users: 0
Login form
Main » Articles » Java

Menjumlah hasil jumlah
masukkan tahun : 2010
proses yg akan dilakukan : 2+0+1+0


String a = "2010";
int hasil = 0;
int angka [] = new int [a.length()];

for(int counter = 0; counter<a.length(); counter++){
angka[counter] = (int) (a.charAt(counter) - '0');
hasil += angka[counter];
}

kalo nggak dikurangi dengan '0', misalnya a.charAt(counter) = '0' maka jika di-casting hasilnya akan menjadi 48.
CMIIW.
karakter '6' itu nilai ASCII-nya = 54
gimana biar jadi 6? 54 - 48 = 6
nah 48 itu apa? 48 adalah nilai ASCII karakter '0'


kita input int 2010
nanti keluarnya array of char {'2','0','1','0'}


int angka = 2010;
String stringDariAngka = ""+2010;

//kalau mau jadi char tinggal

char hasilChar [] = new char[stringDariAngka.length()];

for(int counter = 0; counter<stringDariAngka.length();counter++){
hasilChar[counter] = stringDariAngka.charAt(counter);
}


non-rekrusi

int sum = 0;
while(input > 0)
{
sum += input % 10;
input /= 10;
}
class Coba {

    public static void main(String[] arguments) {
        int input = 6789;
        int sum = 0;
        while (input > 0) {
            sum += input % 10;
            input /= 10;
            System.out.println("sum: "+sum);
            System.out.println("Input: "+input);
        }
    }
}



Source: http://www.kaskus.us/showthread.php?t=4526419
Category: Java | Added by: penta (2010-11-23)
Views: 624 | Comments: 1 | Tags: penjumlahan, rekrusi, menjumlah | Rating: 0.0/0
Total comments: 0
Name *:
Email *:
Code *:
Search
Site friends
  • Create a free website
  • Copyright Penta.Inc © Powered By: Senjapala