Cara Mengambil Input dan Menampilkan Output java
92 / 100

How to Take Input and Display Output in java programming

How to Take Input and Display Output java, As we know, A computer program consists of three main components, that is: input, process, and output. we have discussed before https://www.acmatrix.web.id/memahami-struktur-dan-aturan-penulisan-sintaks-java/

Advertisements
  • Input: the value we enter into the program
  • Process: step by step is done to manage the input into something useful
  • Output: processing results

All programming languages ​​have provided functions for input and output.

Java itself already provides three classes to take input:

  1. Class Scanner;
  2. Class BufferReader;
  3. dan Class Console.

The three classes are for taking input in text-based programs (console). As for the GUI, use other classes such as JOptionPane and inputbox on the form.

As for the output, Java provides functions print(), println(), and format().

Taking Input with Class Scanner java

Scanner is class which provides functions for taking input from the keyboard.

So that we can use Scanner, we need to import it into code:

import java.util.Scanner;

For further details…

Let's Practice

Now is the 2nd meeting, so create a new package named meeting2 on source packages.

Right click on souce packages, then select new package:

Membuat package baru

Then fill in the package name with meeting2, then click Finish:

Mengisi nama package

After that, continue by creating class (java class) new in package meeting2:

Membuat class baru

Give it a name: DataKaryawan. Then click Finish:

Finish

After that, please follow the code below:

package pertemuan2;

// mengimpor Scanner ke program
import java.util.Scanner;

public class DataKaryawan {

    public static void main(String[] args) {
        // deklarasi variabel
        String nama, alamat;
        int usia, gaji;

        // membuat scanner baru
        Scanner keyboard = new Scanner(System.in);

        // Tampilkan output ke user
        System.out.println("### Pendataan Karyawan PT. Petani Kode ###");
        System.out.print("Nama karyawan: ");
        // menggunakan scanner dan menyimpan apa yang diketik di variabel nama
        nama = keyboard.nextLine();
        // Tampilkan outpu lagi
        System.out.print("Alamat: ");
        // menggunakan scanner lagi
        alamat = keyboard.nextLine();

        System.out.print("Usia: ");
        usia = keyboard.nextInt();

        System.out.print("Gaji: ");
        gaji = keyboard.nextInt();


        // Menampilkan apa yang sudah simpan di variabel
        System.out.println("--------------------");
        System.out.println("Nama Karyawan: " + nama);
        System.out.println("Alamat: " + alamat);
        System.out.println("Usia: " + usia + " tahun");
        System.out.println("Gaji: Rp " + gaji);
    }

}

Important to note, the use of functions to retrieve data depends on the type of data used.

Example, the data type is String, then the function or method used is nextLine().

Likewise with other data types, Integer use nextInt(), Double use nextDouble(), etc.

After completing the program, please run. Right click then select Run File or press the button [Shift]+[F6].

Output program dengan scanner

Taking Input with the BufferReader Class

Class BufferReader actually not only to take input from the keyboard only.

This class can also be used to read input from files and networks.

This class is located in the package java.io.

Please import to be able to use class BufferReader.

import java.io.BufferedReader;

Let's try…

Please create a new class named ContohBufferReader, then fill it with the following code.

package pertemuan2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ContohBufferReader {

    public static void main(String[] args) throws IOException {

        String nama;

        // Membuat objek inputstream
        InputStreamReader isr = new InputStreamReader(System.in);

        // membuat objek bufferreader
        BufferedReader br = new BufferedReader(isr);

        // Mengisi varibel nama dengan Bufferreader
        System.out.print("Inputkan nama: ");
        nama = br.readLine();

        // tampilkan output isi variabel nama
        System.out.println("Nama kamu adalah " + nama);

    }

}

It turned out to be class BufferReader can't work alone. He also needs a friend that is: class InputStreamReader and class IOException.

Now let's try to run the program:

Menjalankan program Java

Difference BufferReader with Scanner seen from the function or method used.

Scanner use next(), whereas BufferReader use readLine().

Then for the integer data type, BufferReader using the function read() just. We can see this in hint autocomplete .

hint buffer

Tips: Press Ctrl+Spasi when writing code to display hint autocomplete .

Retrieving Input with the Console Class

Class Console almost equal to BufferReader. He also uses functions readLine() to take input.

But…

This class can only be used in the console environment, like Terminal and CMD.

Class Console can't be used directly on Netbeans.

So therefore, we have to compile manually.

To use this class, we need to import it first.

import java.io.Console;

Let's try…

Create a new file named InputConsole.java with the following contents:

import java.io.Console;

public class InputConsole {
    public static void main(String[] args) {

        String nama;
        int usia;

        // membuat objek console
        Console con = System.console();

        // mengisi variabel nama dan usia dengan console
        System.out.print("Inputkan nama: ");
        nama = con.readLine();
        System.out.print("Inputkan usia: ");
        usia = Integer.parseInt(con.readLine());

        // mengampilkan isi variabel nama dan usia
        System.out.println("Nama kamu adalah: " + nama);
        System.out.println("Saat ini berusia " + usia + " tahun");
    }
}

Take note: in the code above, we use functions Integer.parseInt(con.readLine()) for integer data type. It means, we change the data type String to Integer.

Because Console does not have an integer return value for the function read().

Carry on…

After that, compile via Terminal or CMD. Open terminal, then go to the directory where the code is stored.

Type command: javac InputConsole.java to compile.

After that, type command java InputConsole to run it:

Input console Java

Displaying Output

We already know several ways to take input from the keyboard for text-based programs.

Now what about the output?

There are several functions already provided by Java:

  1. Function System.out.print()
  2. Function System.out.println()
  3. Function System.out.format()

What are the differences between these functions??

Let's discuss…

Function print() vs println()

Function print() and println() both are used to display text.

Then what's the difference?

Function print() will display the text as is. Whereas println() will display text with added newline.

Let's try in code:

package eksperimen;

public class PrintVsPrinln {

    public static void main(String[] args) {

        System.out.print("ini teks yang dicetak dengan print()");
        System.out.println("sedangkan ini teks yang dicetak dengan println()");
        System.out.print("pake print() lagi");

    }

}

Now see the output:

Perbedaan fungsi print dengan println

Concatenating Strings

When using function print() nor println(), sometimes we need to take text from a variable and combine it with other text.

For example like this:

We have variables namaDepan and namaBelakang:

String namaDepan = "Petani";
String namaBelakang = "Kode";

Then we want to display it with the function print(), then we just have to put it in there.

System.out.print(namaDepan);
System.out.print(namaBelakang);

The code will generate: PetaniKode

Actually we don't have to use two functions print(), because we can combine it with operator +.

Example:

System.out.print(namaDepan + namaBelakang);

So that there is a space, just add a space:

System.out.print(namaDepan + " " + namaBelakang);

Format String

As for concatenating more complex Strings, we can use function format().

Example:

package eksperimen;

public class FormatString {

    public static void main(String[] args) {

        String namaDepan = "Petani";
        String namaBelakang = "Kode";

        System.out.format("Nama saya %s %s %n", namaDepan, namaBelakang);

    }

}

Take note: there we use the symbol %s to retrieve the value of the variable next to it. %s means string.

Advertisements

Besides %s, there are also other symbols:

Advertisements
  • %d for decimal or number;
  • %f for fractional numbers;
  • %n for new line, can also use \n;
  • and many more, check in java documentation
  • .
Format String

source : https://www.petanikode.com/java-input-output/

By admin

Writer

Leave a Reply

Your email address will not be published. Required fields are marked *