Follow me

Rabu, 27 November 2013

Program Java Menampilkan Bilangan Faktorial

import java.io.*;
public class Faktorial {
    public static void main(String[] args) {
        String input = "";
        int i, jlh = 1;
        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Input bilangan n!, n : ");
        try {
            input = buffer.readLine();
        } catch (Exception e) {
        }
        int a = Integer.valueOf(input);
        System.out.print("Penyelesaian faktorial\n" + a + "! = ");
        if (a < 1) {
            System.out.println("Silahkan masukkan angka lebih besar dari 0");
        } else {
            for (i = 1; i <= a; i++) {
                System.out.print(i);
                if (i < a) {
                    System.out.print(" x ");
                }
                jlh = jlh * i;
            }
            System.out.println("\n   = " + jlh);
        }
    }
}

Contoh Program Penasaran


I need to write a method that accepts two ints as arguments, a min and a max. On the first line i need to print all numbers in that range (inclusive). On the next line I start with min+1, print all numbers up to max, and then go back to the front of the range and print min. Next line I start with min+2, and so on until I have repeated this starting with each number in the range.Very hard to explain, here's two examples: Say I pass 1 and 5 as the min and max arguments. I want the method to print this:

12345
23451
34512
45123
51234
 
Or if 3 and 9 were passed, I would expect this:

3456789
4567893
5678934
6789345
7893456
8934567
9345678
 
I've tried all kinds of things, I'm sure there is an easy way to do this that I am not realizing. I'm supposed to do this without arrays or arrayLists. I think I have a good base to work with, but I just can't figure out where to go from here. My base code prints this:

12345
2345
345
45
5
 
And this:

3456789
456789
56789
6789
789
89
9
 
I'm stumped. Here's my code:

public void printSquare(int min, int max){
   for (int i=min; i<=max; i++){
      for (int j=i; j<=max; j++){
         System.out.print(j);         
      }
   System.out.println();   
   }
}