JavaJava · Chapterبەش 4 · Lectureوانە 4.6

Keyboard Input with Scanner and Formatted Outputنێوخستە لە کیبۆردەوە بە Scanner و دەرخستەی ڕێکخراو

Reading the keyboard with Scanner: the import, new Scanner(System.in), nextInt, nextDouble, nextBoolean, next and nextLine, tokens and the Enter that nextInt leaves behind, wrong input and the end of input, hasNextInt, and input from a pipe; formatted output with printf and String.format (%d, %f, %.2f, %s, %n, widths and the , flag); and why a computer set to Kurdish or Arabic number formats can stop a program, with the Locale.ROOT fix.

خوێندنەوەی بە Scanner: import، new Scanner(System.in)، nextInt، nextDouble، nextBoolean، next و nextLine، پارچەکانی و ئەو Enterـەی nextInt بەجێی دەهێڵێت، هەڵە و کۆتایی ، hasNextInt و لە pipeـەوە؛ ڕێکخراو بە printf و String.format (%d، %f، %.2f، %s، %n، پانی و نیشانەی ,)؛ و بۆچی کە بۆ ژمارەی کوردی یان عەرەبی ڕێکخراوە دەتوانێت بوەستێنێت، لەگەڵ چارەسەرەکەی بە Locale.ROOT.

21 min read19 خولەک خوێندنەوە · 24 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Read numbers, words, whole lines and booleans from the keyboard with a Scanner, after a clear prompt.
  • Explain tokens and the newline that nextInt leaves behind, and avoid the nextLine trap.
  • Recognise InputMismatchException and NoSuchElementException, and check input first with hasNextInt.
  • Format output with printf and String.format: decimal places, widths, grouping and %n, also on computers with Kurdish or Arabic number formats.
  • بە Scanner ژمارە، وشە، دێڕی تەواو و لە بخوێنیتەوە، لە دوای ڕوون.
  • پارچەکانی و ئەو nextInt بەجێی دەهێڵێت ڕوون بکەیتەوە و خۆت لە تەڵەی nextLine بپارێزیت.
  • InputMismatchException و NoSuchElementException بناسیتەوە و سەرەتا بە hasNextInt بپشکنیت.
  • بە printf و String.format ڕێک بخەیت: ، پانی، گرووپکردن و %n، هەروەها لەسەر ئەو فۆرماتی ژمارەیان کوردی یان عەرەبییە.

Programs that ask and answerبەرنامەیەک کە پرسیار دەکات و وەڵام دەداتەوە

So far every value was written inside the program, so it gave the same answer every time it ran. Reading from the keyboard lets one program work with any value: it asks, the user types, and it answers. Java reads the keyboard through System.in, the , and prints through System.out, the (Input, processing, output).

تا ئێستا هەموو لەناو نووسرابوون، بۆیە هەر جارێک جێبەجێ دەکرا هەمان وەڵامی دەدایەوە. خوێندنەوەی لە وا دەکات یەک لەگەڵ هەر کار بکات: پرسیار دەکات، دەنووسێت و وەڵام دەداتەوە. Java لە ڕێگەی System.inـەوە دەخوێنێتەوە، کە . لە ڕێگەی System.outـیشەوە چاپ دەکات، کە (سووڕی چارەسەرکردنی زانیاری).

A keyboard sends what you type, 2.5 and Enter, into System.in, the standard input. A Scanner object called input reads it with nextDouble() and stores the double value 2.5 in the variable radius. Note: Scanner turns the characters you type into a Java value.کیبۆرد ئەوەی دەینووسیت، 2.5 و Enter، دەنێرێتە ناو System.in، کە نێوخستەی ستانداردە. ئۆبجێکتێکی Scanner بە ناوی input بە nextDouble دەیخوێنێتەوە و نرخەکە 2.5، کە doubleـە، لە گۆڕاوی radius دادەنێت. تێبینی: Scanner ئەوەی دەینووسیت دەکات بە نرخێکی Java.
From the keys to a variable: keyboard, System.in, Scanner, radiusلە دوگمەکانەوە بۆ : ، ⁦System.in⁩، Scanner، radiusCêIT

Python does the same job with one function, input(), which always gives text (Reading what the user types). Java uses an object of the class Scanner, which can also turn the text into a number for you.

Python هەمان کار بە یەک دەکات، input()، کە هەمیشە دەق دەداتەوە (خوێندنەوەی ئەوەی بەکارهێنەرەکە دەینووسێت). Java Scanner بەکار دەهێنێت، کە دەتوانێت دەقەکە بۆت بکات بە ژمارەش.

Two lines get a Scanner readyدوو دێڕ Scanner ئامادە دەکەن

Scanner is a in the java.util, so the file starts with import java.util.Scanner;, above the class (import). Inside main, Scanner input = new Scanner(System.in); creates a new of the type Scanner and connects it to System.in. input is just a variable name: keyboard or sc work as well.

Scanner لە java.utilـدا، بۆیە فایلەکە بە import java.util.Scanner; دەست پێ دەکات، لە سەرووی (import). لەناو mainـدا، Scanner input = new Scanner(System.in); نوێی جۆری Scanner دروست دەکات و بە System.inـەوە دەیبەستێتەوە. input تەنیا ناوی : keyboard یان scـیش کار دەکەن.

The two lines taken apart. import java.util.Scanner; with java.util marked: Scanner is a class in the package java.util. Scanner input = new Scanner(System.in); with four parts marked: Scanner is the type, a class; input is the variable, any name; new Scanner makes a new Scanner object; System.in means read from the keyboard. Note: then ask the object for values with input.nextInt(), input.nextDouble() and so on.دوو دێڕەکە بەش بەش. import java.util.Scanner; و java.util نیشانە کراوە: Scanner کلاسێکە لە پاکێجی java.util. Scanner input = new Scanner(System.in); و چوار بەشی نیشانە کراوە: Scanner جۆرەکەیە، کلاسێک؛ input گۆڕاوەکەیە، هەر ناوێک؛ new Scanner ئۆبجێکتێکی نوێی Scanner دروست دەکات؛ System.in واتە لە کیبۆردەوە بخوێنەوە. تێبینی: پاشان بە input.nextInt و input.nextDouble و هتد داوای نرخەکان لە ئۆبجێکتەکە بکە.
The import line and the line that creates the Scannerدێڕی import و ئەو دێڕەی Scanner دروست دەکاتCêIT

An object can do jobs: its . Calling a method on an object asks the object to do that job. double radius = input.nextDouble(); asks input to read a number from the keyboard and stores it in radius. Classes and objects of your own come in Classes and objects.

دەتوانێت کار بکات: . بانگکردنی لەسەر داوا لە دەکات ئەو کارە بکات. double radius = input.nextDouble(); داوا لە input دەکات ژمارەیەک لە بخوێنێتەوە و لە radiusـدا هەڵیدەگرێت. و خۆت لە کلاسەکان و ئۆبجێکتەکانـدا دێن.

A first input program: the area of a circleیەکەم بەرنامە بە نێوخستە: ڕووبەری بازنە

This program asks for the radius of a circle and prints its area. Follow it line by line: the prompt, the read, the computation, the answer. Here it ran twice:

ئەم نیوەتیرەی بازنەیەک دەپرسێت و ڕووبەرەکەی چاپ دەکات. دێڕ بە دێڕ بەدوایدا بڕۆ: ، خوێندنەوە، ژماردن، وەڵام. لێرەدا دوو جار جێبەجێ کرا:

ComputeAreaWithConsoleInput.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class ComputeAreaWithConsoleInput {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number for radius: ");
        double radius = input.nextDouble();
        double area = radius * radius * 3.14159;
        System.out.println("The area for the circle of radius " + radius + " is " + area);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

Create the Scanner once, at the start.

Scanner یەک جار دروست بکە، لە سەرەتادا.

Lineدێڕی 6

The prompt: print, so the answer is typed on the same line.

: print، بۆیە وەڵامەکە لە هەمان دێڕدا دەنووسرێت.

Lineدێڕی 7

The program waits here until the user types a number and presses Enter.

لێرەدا چاوەڕێ دەکات تا ژمارەیەک دەنووسێت و Enter دادەگرێت.

The prompt uses print, not println, so the cursor waits right after Enter a number for radius: (print and println). The typed 4 is printed as 4.0, because radius is a double.

print بەکار دەهێنێت، نەک println، بۆیە ڕاستەوخۆ لە دوای Enter a number for radius: چاوەڕێ دەکات (print و println). ئەو 4ـەی نووسرا وەک 4.0 چاپ دەکرێت، چونکە radius جۆری doubleـە.

Two terminals. Left, with System.out.print("Age: "): the user's 20 appears right after Age: on the same line, then Next year you will be 21. Right, with System.out.println("Age:"): Age: is alone on its line and 20 is typed on the next line. Note: the green text is what the user typed.دوو تێرمیناڵ. لای چەپ، بە System.out.print("Age: "): ژمارەی 20ی بەکارهێنەرەکە ڕاستەوخۆ لە دوای Age: لە هەمان دێڕدا دەردەکەوێت، پاشان Next year you will be 21. لای ڕاست، بە System.out.println("Age:"): Age: بە تەنیا لە دێڕی خۆیدایە و 20 لە دێڕی دواتردا دەنووسرێت. تێبینی: دەقە سەوزەکە ئەوەیە کە بەکارهێنەرەکە نووسیویەتی.
A prompt with print and with println (two real runs) بە print و بە println (دوو جێبەجێکردنی ڕاستەقینە)CêIT

A first input program: the area of a circleیەکەم بەرنامە بە نێوخستە: ڕووبەری بازنە

Input without typing: a pipeنێوخستە بەبێ نووسین: pipe

Typing the same test values again and again is slow. In a terminal, a pipe | sends the output of one command into the of a program, which reads it as if it were typed. In bash and zsh, a here-string <<< does the same. The typed value no longer appears, so the answer follows the prompt on the same line:

نووسینی هەمان تاقیکردنەوە جار لە دوای جار هێواشە. لە ، pipe ـی | دەنێرێتە ناو ، کە وەک ئەوەی نووسرابێت دەیخوێنێتەوە. لە bash و zshـدا، ⁦here-string⁩ ـی <<< هەمان کار دەکات. ئیتر دەرناکەوێت، بۆیە وەڵامەکە لە هەمان دێڕی دێت:

BASHType in a terminalلە تێرمیناڵدا بینووسە
echo 2.5 | java ComputeAreaWithConsoleInput
java AskAge <<< 41
Two ways into System.in. A keyboard: typed input that the screen shows. The command echo 2.5 and a pipe |: input that the screen does not show. Both reach the same program, java ComputeAreaWithConsoleInput, which cannot tell the difference. The terminal shows: Enter a number for radius: The area for the circle of radius 2.5 is 19.6349375.دوو ڕێگا بۆ ناو System.in. کیبۆرد: نێوخستەیەک کە شاشە پیشانی دەدات. فەرمانەکەی echo 2.5 و pipe ـی |: نێوخستەیەک کە شاشە پیشانی نادات. هەردووکیان دەگەنە هەمان بەرنامە، java ComputeAreaWithConsoleInput، کە جیاوازییەکە نازانێت. تێرمیناڵەکە پیشان دەدات: Enter a number for radius: The area for the circle of radius 2.5 is 19.6349375.
Typed or piped: the program reads System.in either wayنووسراو یان بە pipe: هەر ⁦System.in⁩ دەخوێنێتەوەCêIT

printf (the shell command, not Java's) can send several lines: printf '20\nShilan\n' | java NextLineTrap. The pipe also works in Windows PowerShell and Command Prompt; <<< is a bash and zsh feature.

printf ( شێڵ، نەک هی Java) دەتوانێت چەند دێڕێک بنێرێت: printf '20\nShilan\n' | java NextLineTrap. pipe لە PowerShell و Command Promptـی Windowsـیشدا کار دەکات؛ <<< تایبەتمەندییەکی bash و zshـە.

One reading method for each typeیەک میتۆدی خوێندنەوە بۆ هەر جۆرێک

A Scanner has a reading method for each kind of value. Each one reads what the user typed and gives it back as a value of its type:

Scanner بۆ هەر جۆرە خوێندنەوەی هەیە. هەریەکەیان ئەوەی نووسیویەتی دەخوێنێتەوە و وەک جۆری خۆی دەیداتەوە:

MethodGives backدەیداتەوەExample inputنموونەی
nextByte()byte127
nextShort()short2020
nextInt()int100000
nextLong()long15000000000
nextFloat()float5.75
nextDouble()double2.5
nextBoolean()booleantrue
next()Stringone word: Aramیەک وشە: Aram
nextLine()Stringthe rest of the line: Aram Kawaئەوەی لە دێڕەکەدا ماوەتەوە: Aram Kawa
Each Scanner method with the type it gives back and something the user may type: nextInt() gives int (20), nextDouble() gives double (2.5), nextBoolean() gives boolean (true), next() gives a String of one word (Aram from Aram Kawa), nextLine() gives a String of the whole line (Aram Kawa). Note: also nextByte(), nextShort(), nextLong() and nextFloat().هەر میتۆدێکی Scanner لەگەڵ ئەو جۆرەی دەیداتەوە و شتێک کە بەکارهێنەرەکە ڕەنگە بینووسێت: nextInt جۆری int (20)، nextDouble جۆری double (2.5)، nextBoolean جۆری boolean (true)، next زنجیرەنووسەیەکی یەک وشەیی (Aram لە Aram Kawa)، nextLine زنجیرەنووسەیەکی هەموو دێڕەکە (Aram Kawa). تێبینی: هەروەها nextByte، nextShort، nextLong و nextFloat.
Each method reads one kind of valueهەر جۆرێک دەخوێنێتەوەCêIT

There is no nextChar(): read a word and take its first character, input.next().charAt(0) (A word or a whole line).

nextChar() بوونی نییە: وشەیەک بخوێنەوە و یەکەم وەربگرە، input.next().charAt(0) (وشەیەک یان هەموو دێڕێک).

One reading method for each typeیەک میتۆدی خوێندنەوە بۆ هەر جۆرێک

Reading five kinds of numbersخوێندنەوەی پێنج جۆری ژمارە

This program reads one value of each whole-number type and a float, then prints them on one line. The empty System.out.println(); prints a blank line first. The second run typed 128 at the first prompt:

ئەم لە هەر جۆرێکی و floatـێک دەخوێنێتەوە، پاشان لە یەک دێڕدا چاپیان دەکات. System.out.println();ـی بەتاڵ سەرەتا دێڕێکی بەتاڵ چاپ دەکات. جێبەجێکردنی دووەم لە یەکەم 128ـی نووسی:

ReadNumbers.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class ReadNumbers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a byte value: ");
        byte byteValue = input.nextByte();

        System.out.print("Enter a short value: ");
        short shortValue = input.nextShort();

        System.out.print("Enter an int value: ");
        int intValue = input.nextInt();

        System.out.print("Enter a long value: ");
        long longValue = input.nextLong();

        System.out.print("Enter a float value: ");
        float floatValue = input.nextFloat();
        System.out.println();
        System.out.println(byteValue + " " + shortValue + " " + intValue + " " + longValue + " " + floatValue);
    }
}

A byte holds only −128 to 127, so 128 is out of range: the program stops with an InputMismatchException and the message Value out of range. A value with the wrong format, such as a word for a number, stops it in the same way. Both are : Wrong input.

byte تەنیا ⁦−128⁩ تا ⁦127⁩ هەڵدەگرێت، بۆیە ⁦128⁩ لە سنوورەکەی دەردەچێت: بە InputMismatchException و پەیامی Value out of range دەوەستێت. بە شێوەی هەڵە، وەک وشەیەک لە جیاتی ژمارە، بە هەمان شێوە دەیوەستێنێت. هەردووکیان : نێوخستەی هەڵە.

One reading method for each typeیەک میتۆدی خوێندنەوە بۆ هەر جۆرێک

Reading true or falseخوێندنەوەی true یان false

A form often needs text, numbers and a yes/no answer. nextBoolean() reads true or false and ignores letter case, so TRUE works too; any other word stops the program:

فۆرمێک زۆرجار پێویستی بە دەق، ژمارە و وەڵامی بەڵێ/نەخێر هەیە. nextBoolean() true یان false دەخوێنێتەوە و گوێ بە پیتی گەورە و بچووک نادات، بۆیە TRUEـیش کار دەکات؛ هەر وشەیەکی تر دەوەستێنێت:

StudentCard.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class StudentCard {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Name: ");
        String name = input.nextLine();
        System.out.print("Age: ");
        int age = input.nextInt();
        System.out.print("Height in metres: ");
        double height = input.nextDouble();
        System.out.print("Library card (true/false): ");
        boolean hasCard = input.nextBoolean();
        System.out.println(name + ", " + age + " years, " + height + " m, card: " + hasCard);
    }
}
Four inputs to nextBoolean(): true gives true, TRUE gives true, false gives false, and yes stops the program with InputMismatchException. Note: any other word, yes or 1 for example, stops the program.چوار نێوخستە بۆ nextBoolean: true ← true، TRUE ← true، false ← false و yes بەرنامەکە بە InputMismatchException دەوەستێنێت. تێبینی: هەر وشەیەکی تر، بۆ نموونە yes یان 1، بەرنامەکە دەوەستێنێت.
What nextBoolean() accepts (from real runs)ئەوەی nextBoolean وەری دەگرێت (لە جێبەجێکردنی ڕاستەقینەوە)CêIT

The name is read first with nextLine(), before the numbers; the Enter that nextInt() leaves behind shows why that order matters. (With the input TRUE the last line also ends card: true.)

ناوەکە سەرەتا بە nextLine() دەخوێنرێتەوە، پێش ژمارەکان؛ ئەو Enterـەی nextInt بەجێی دەهێڵێت پیشانی دەدات بۆچی ئەم ڕیزبەندییە گرنگە. (بە TRUE، دێڕی کۆتاییش بە card: true تەواو دەبێت.)

How Scanner reads: token by tokenScanner چۆن دەخوێنێتەوە: پارچە بە پارچە

What you type waits in an input until a method takes it. Scanner cuts the text into pieces called tokens at : spaces, tabs and line breaks (). nextInt, nextDouble, nextBoolean and next skip whitespace, then take one token. nextLine is different: it takes the rest of the current line, spaces included, and removes the newline at its end.

ئەوەی دەینووسیت لە چاوەڕێ دەکات تا وەریدەگرێت. Scanner دەقەکە لە دەکات بە پارچە (tokens): بۆشایی، تاب و . nextInt، nextDouble، nextBoolean و next تێدەپەڕێنن، پاشان یەک پارچە وەردەگرن. nextLine جیاوازە: ئەوەی لە دێڕی ئێستادا ماوەتەوە وەردەگرێت، بۆشاییەکانیشی تێدایە، پاشان ئەو لە کۆتاییدایە لادەبات.

Animation. The input buffer holds 20, a space, 1.75, Enter, Shilan, a space, Aram, Enter. Step by step: nextInt() takes 20 and stops at the space; nextDouble() skips the space and takes 1.75; next() skips the Enter and takes Shilan; nextLine() takes the rest of the line, " Aram" with its space, and removes the Enter. The variables fill up: age 20, height 1.75, first "Shilan", rest " Aram".
Animation. The input buffer holds 20, a space, 1.75, Enter, Shilan, a space, Aram, Enter. Step by step: nextInt() takes 20 and stops at the space; nextDouble() skips the space and takes 1.75; next() skips the Enter and takes Shilan; nextLine() takes the rest of the line, " Aram" with its space, and removes the Enter. The variables fill up: age 20, height 1.75, first "Shilan", rest " Aram".
Scanner takes the input token by tokenScanner پارچە بە پارچە وەردەگرێتCêIT
Tokens.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class Tokens {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int age = input.nextInt();
        double height = input.nextDouble();
        String first = input.next();
        String rest = input.nextLine();
        System.out.println("age    = " + age);
        System.out.println("height = " + height);
        System.out.println("first  = [" + first + "]");
        System.out.println("rest   = [" + rest + "]");
    }
}

Typed on three lines (20, 1.75, Shilan Aram) or with extra spaces ( 20 1.75 Shilan Aram), the program printed the same four values: for the number methods an Enter is just more whitespace.

کە لە سێ دێڕدا نووسرا (20، 1.75، Shilan Aram) یان بە بۆشایی زیادەوە ( 20 1.75 Shilan Aram)، هەمان چوار چاپ کرد: بۆ ژمارە، Enter تەنیا زیاترە.

A word or a whole line: next() and nextLine()وشەیەک یان هەموو دێڕێک: next و nextLine

next() stops at the first space, so a full name loses its second word. nextLine() reads up to the end of the line. The same input, Aram Kawa, in two programs:

next() لە یەکەم بۆشاییدا دەوەستێت، بۆیە ناوێکی تەواو وشەی دووەمی ون دەکات. nextLine() تا کۆتایی دێڕەکە دەخوێنێتەوە. هەمان ، Aram Kawa، لە دوو :

FirstWord.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class FirstWord {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Your full name: ");
        String name = input.next();
        System.out.println("Hello, " + name + "!");
    }
}
WholeLine.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class WholeLine {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Your full name: ");
        String name = input.nextLine();
        System.out.println("Hello, " + name + "!");
    }
}
The characters A r a m, a space, K a w a and Enter. next() takes only "Aram" and stops at the space; nextLine() takes "Aram Kawa", up to the Enter, which is read but not kept. Note: for a full name, a city or a sentence, use nextLine().نووسەکانی A r a m، بۆشایی، K a w a و Enter. next تەنیا "Aram" وەردەگرێت و لە بۆشاییەکەدا دەوەستێت؛ nextLine "Aram Kawa" وەردەگرێت، تا Enter، کە دەخوێنرێتەوە بەڵام هەڵناگیرێت. تێبینی: بۆ ناوی تەواو، ناوی شار یان ڕستەیەک nextLine بەکار بهێنە.
next() stops at a space, nextLine() at the end of the linenext لە بۆشاییدا دەوەستێت و nextLine لە کۆتایی دێڕCêIT

The Enter that nextInt() leaves behindئەو Enterـەی nextInt بەجێی دەهێڵێت

This program reads a number, then a name. It never waits for the name:

ئەم ژمارەیەک دەخوێنێتەوە، پاشان ناوێک. هەرگیز چاوەڕێی ناوەکە ناکات:

NextLineTrap.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class NextLineTrap {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Age: ");
        int age = input.nextInt();
        System.out.print("Name: ");
        String name = input.nextLine();
        System.out.println("[" + name + "] is " + age);
    }
}

nextInt() takes 20 but leaves the newline of that line in the buffer. nextLine() reads up to the next newline, finds it at once and returns an empty string "": the brackets in the output are empty. The same happens with nextDouble(), next() or nextBoolean() followed by nextLine().

nextInt() ژمارەی 20 وەردەگرێت بەڵام ئەو دێڕە لە جێدەهێڵێت. nextLine() تا داهاتوو دەخوێنێتەوە، یەکسەر دەیدۆزێتەوە و بەتاڵ "" دەگەڕێنێتەوە: کەوانەکانی بەتاڵن. هەمان شت ڕوو دەدات کاتێک nextDouble()، next() یان nextBoolean() بە nextLine() بەدوادا بێت.

Animation. The user types 20 and Enter. nextInt() takes 20; the Enter stays in the input buffer. nextLine() reads up to the Enter, finds it at once and returns "", so the terminal shows Name: [] is 20 and the program never waited for the name. The fix: one extra nextLine() removes the leftover Enter; then nextLine() waits and reads Shilan Aram, and the program prints Shilan Aram is 20.
Animation. The user types 20 and Enter. nextInt() takes 20; the Enter stays in the input buffer. nextLine() reads up to the Enter, finds it at once and returns "", so the terminal shows Name: [] is 20 and the program never waited for the name. The fix: one extra nextLine() removes the leftover Enter; then nextLine() waits and reads Shilan Aram, and the program prints Shilan Aram is 20.
The leftover Enter, and the fixEnterـە بەجێماوەکە و چارەسەرەکەیCêIT

The Enter that nextInt() leaves behindئەو Enterـەی nextInt بەجێی دەهێڵێت

Two ways to avoid the trapدوو ڕێگا بۆ خۆپاراستن لە تەڵەکە

Fix 1: after reading the number, call nextLine() once more and ignore its result. It removes the rest of the number's line:

چارەسەری 1: لە دوای خوێندنەوەی ژمارەکە، جارێکی تر nextLine() بانگ بکە و ئەنجامەکەی فەرامۆش بکە. ئەوەی لە دێڕی ژمارەکەدا ماوەتەوە لادەبات:

NextLineFixed.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class NextLineFixed {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Age: ");
        int age = input.nextInt();
        input.nextLine();                  // throw away the rest of the age line
        System.out.print("Name: ");
        String name = input.nextLine();
        System.out.println(name + " is " + age);
    }
}

Fix 2: read every line with nextLine() and turn the text into a number yourself with Integer.parseInt (trim() removes stray spaces). Text that is not a whole number then stops the program with a NumberFormatException instead:

چارەسەری 2: هەموو دێڕێک بە nextLine() بخوێنەوە و خۆت دەقەکە بە Integer.parseInt بکە بە ژمارە (trim() بۆشاییە زیادەکان لادەبات). ئەو دەقەی نییە ئەوسا بە NumberFormatException دەوەستێنێت:

LinesOnly.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class LinesOnly {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Age: ");
        int age = Integer.parseInt(input.nextLine().trim());
        System.out.print("Name: ");
        String name = input.nextLine();
        System.out.println(name + " is " + age);
    }
}

A third habit avoids the problem completely: read the text first and the numbers after it, as the shop receipt does.

خووی سێیەم بە تەواوی ڕێگە لە کێشەکە دەگرێت: سەرەتا دەقەکە بخوێنەوە و پاشان ژمارەکان، وەک پسوولەی دوکان دەیکات.

Wrong input, and no input at allنێوخستەی هەڵە و هیچ نێوخستەیەک

A Scanner cannot turn every text into every type. When the next token does not fit the method, the program stops with an InputMismatchException. When the input has ended (Ctrl+D on macOS and Linux, Ctrl+Z then Enter on Windows, or the end of a pipe), it stops with a NoSuchElementException. Three runs of a program that asks for an age with nextInt(); in the last one Ctrl+D was pressed at the prompt:

Scanner ناتوانێت هەموو دەقێک بکات بە هەموو جۆرێک. کاتێک پارچەی داهاتوو لەگەڵ ناگونجێت، بە InputMismatchException دەوەستێت. کاتێک کۆتایی هاتووە (⁦Ctrl+D⁩ لە macOS و Linuxـدا، ⁦Ctrl+Z⁩ پاشان Enter لە Windowsـدا، یان کۆتایی pipe)، بە NoSuchElementException دەوەستێت. سێ جێبەجێکردنی کە بە nextInt() تەمەن دەپرسێت؛ لە دوایینیاندا لە ⁦Ctrl+D⁩ داگیرا:

AskAge.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class AskAge {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Age: ");
        int age = input.nextInt();
        System.out.println("Next year you will be " + (age + 1));
    }
}
Five inputs and what happens. 20 to nextInt(): stored. abc to nextInt(): InputMismatchException, not a number. 20.5 to nextInt(): InputMismatchException, not a whole number. 128 to nextByte(): InputMismatchException, too big for a byte, which holds -128 to 127. End of input to nextInt(): NoSuchElementException. Note: input.hasNextInt() looks at the next token first, without taking it.پێنج نێوخستە و ئەوەی ڕوو دەدات. 20 بۆ nextInt: هەڵدەگیرێت. abc بۆ nextInt: InputMismatchException، ژمارە نییە. 20.5 بۆ nextInt: InputMismatchException، ژمارەی تەواو نییە. 128 بۆ nextByte: InputMismatchException، بۆ byte زۆر گەورەیە، کە تەنیا -128 تا 127 هەڵدەگرێت. کۆتایی نێوخستە بۆ nextInt: NoSuchElementException. تێبینی: input.hasNextInt سەرەتا سەیری پارچەی داهاتوو دەکات، بێ ئەوەی هەڵیبگرێت.
When the input does not fit, the program stops with an exceptionکاتێک ناگونجێت، بە دەوەستێتCêIT

20.5 stops nextInt() too (a run with that input gave the same InputMismatchException). Read the stack trace from the top: the exception's name, then the at lines; the last one, AskAge.java:7, is your line (Reading a stack trace). To catch the error and ask again instead of stopping, see A safe input loop; it uses the while (true) loop of break and continue.

20.5ـیش nextInt() دەوەستێنێت (جێبەجێکردنێک بەو هەمان InputMismatchExceptionـی دا). لە سەرەوە بخوێنەوە: ناوی ، پاشان دێڕەکانی at؛ دوایینیان، AskAge.java:7، دێڕی خۆتە (خوێندنەوەی ڕێچکەی هەڵە). بۆ گرتنی هەڵەکە و پرسینەوە لە جیاتی وەستان، بڕوانە خولێکی سەلامەتی نێوخستە؛ ئەو شێوەی while (true)ـی break و continue بەکار دەهێنێت.

Wrong input, and no input at allنێوخستەی هەڵە و هیچ نێوخستەیەک

Look before you take: hasNextInt()سەیرکردن پێش وەرگرتن: hasNextInt

hasNextInt() looks at the next token and answers true if nextInt() could read it. It does not take the token, so the token is still there for the next read. There are hasNextDouble(), hasNextBoolean(), hasNextLine() and hasNext() too.

hasNextInt() سەیری پارچەی داهاتوو دەکات و true دەداتەوە ئەگەر nextInt() بتوانێت بیخوێنێتەوە. پارچەکە وەرناگرێت، بۆیە بۆ خوێندنەوەی دواتر هێشتا ماوە. hasNextDouble()، hasNextBoolean()، hasNextLine() و hasNext()ـیش هەن.

PeekFirst.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class PeekFirst {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Number: ");
        boolean isWholeNumber = input.hasNextInt();   // looks, does not take
        System.out.println("hasNextInt() gives " + isWholeNumber);
        String token = input.next();                   // the token is still waiting
        System.out.println("next() gives " + token);
    }
}
Two runs. The user typed 42: hasNextInt() looks at 42 and gives true; nothing is taken, and next() then gives "42". The user typed abc: hasNextInt() gives false; the token stays, and next() gives "abc".دوو جێبەجێکردن. بەکارهێنەرەکە 42ی نووسی: hasNextInt سەیری 42 دەکات و true دەداتەوە؛ هیچ وەرناگیرێت و پاشان next "42" دەداتەوە. بەکارهێنەرەکە abcـی نووسی: hasNextInt false دەداتەوە؛ پارچەکە دەمێنێتەوە و next "abc" دەداتەوە.
hasNextInt() looks without takinghasNextInt سەیر دەکات بێ ئەوەی وەربگرێتCêIT

Because it gives a boolean, hasNextInt() can be the condition of an if: read the number, or explain what to type (Check the input before reading it).

چونکە دەداتەوە، hasNextInt() دەتوانێت ifـێک بێت: ژمارەکە بخوێنەوە، یان ڕوونی بکەرەوە چی بنووسرێت (پشکنینی نێوخستە پێش خوێندنەوە).

Formatted output: printfدەرخستەی ڕێکخراو: printf

When you print the result of a computation, you often want to control how it looks. A price of 1.2159624413145538 dollars per liter should appear as 1.22. System.out.printf prints a format string in which every , starting with %, is a gap; the values after the string fill the gaps in order:

کاتێک ئەنجامی ژماردنێک چاپ دەکەیت، زۆرجار دەتەوێت شێوەکەی کۆنترۆڵ بکەیت. نرخی ⁦1.2159624413145538⁩ دۆلار بۆ هەر لیترێک دەبێت وەک 1.22 دەربکەوێت. System.out.printf فۆرمات چاپ دەکات کە تێیدا هەر ، کە بە % دەست پێ دەکات، شوێنێکی چۆڵە؛ ئەو لە دوای دێن بە ڕیز شوێنە چۆڵەکان پڕ دەکەنەوە:

PricePerLiter.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class PricePerLiter {
    public static void main(String[] args) {
        double cost = 25.90;      // dollars
        double liters = 21.3;
        double price = cost / liters;
        System.out.println("Price per liter: " + price);
        System.out.printf("Price per liter: %.2f%n", price);
    }
}
The call System.out.printf("Price per liter: %.2f%n", price); taken apart: the text Price per liter: is copied as it is; %.2f is a gap for a number; %n is a new line; price is the value that fills the gap. Below, %.2f in large type: % starts a specifier, .2 means 2 digits after the point, f means a number with a fraction (a double). The terminal shows Price per liter: 1.22.بانگکردنی System.out.printf("Price per liter: %.2f%n", price); بەش بەش: دەقی Price per liter: وەک خۆی چاپ دەکرێت؛ %.2f شوێنی ژمارەیەکە؛ %n دێڕی نوێیە؛ price ئەو نرخەیە کە شوێنەکە پڕ دەکاتەوە. لە خوارەوە، %.2f بە پیتی گەورە: % دەستپێکی دیاریکەرێکی فۆرماتە، .2 واتە 2 تاکژمارە لە دوای فاریزەکە، f واتە ژمارەیەکی کەرتی (double). تێرمیناڵەکە Price per liter: 1.22 پیشان دەدات.
A printf call taken apartبانگکردنێکی printf بەش بەشCêIT

%.2f prints a number with exactly two digits after the decimal point, and %n ends the line. Python writes the same specifier inside an f-string: f"{price:.2f}" (Format specifiers).

%.2f ژمارەیەک بە ڕێک دوو لە دوای چاپ دەکات و %n دێڕەکە تەواو دەکات. Python هەمان لەناو ⁦f-string⁩ـێکدا دەنووسێت: f"{price:.2f}" (دیاریکەرەکانی فۆرمات).

Formatted output: printfدەرخستەی ڕێکخراو: printf

Two decimal places, roundedدوو خانەی دەیی، نزیککراوە

The .2 counts : digits after the point. It does not count significant digits: 1.22 has two decimal places but three significant digits. The printed value is rounded half up, and the variable itself does not change, only the printed text:

.2 دەژمێرێت: دوای . گرنگ ناژمێرێت: 1.22 دوو و سێ گرنگی هەیە. بە نزیک دەکرێتەوە و خودی ناگۆڕێت، تەنیا دەقە چاپکراوەکە:

PrintfDemo.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class PrintfDemo {
    public static void main(String[] args) {
        System.out.printf("%.2f%n", 2.345);
        System.out.printf("%.2f%n", 1.215962441314554);
        System.out.printf("%.0f%n", 2.5);
        System.out.printf("%8.3f|%n", Math.PI);
        System.out.printf("%d items, %s%n", 3, "done");
    }
}
The digits of 1.2159624413145538 in cells: the 2 and 1 after the point are kept, the next digit is 5, so the value rounds up to 1.22. Note: 1.22 has 2 decimal places but 3 significant digits (1, 2, 2).تاکژمارەکانی 1.2159624413145538 لە خانەدا: 2 و 1ی دوای فاریزەکە دەمێننەوە، تاکژمارەکەی دواتر 5ـە، بۆیە نرخەکە بۆ سەرەوە نزیک دەکرێتەوە و دەبێتە 1.22. تێبینی: 1.22 دوو خانەی دەیی و سێ تاکژمارەی گرنگی هەیە (1، 2، 2).
%.2f keeps two decimal places%.⁦2f⁩ دوو دەهێڵێتەوەCêIT

printf never ends the line by itself, so finish a format string with %n. %n writes the line ending of the computer's ; \n also works, as in println text (Escape sequences).

printf هەرگیز خۆی دێڕەکە تەواو ناکات، بۆیە فۆرمات بە %n تەواو بکە. %n کۆتایی دێڕی دەنووسێت؛ \nـیش کار دەکات، وەک لە دەقی printlnـدا (هێما تایبەتەکان).

More specifiers: %d, %f, %s, %c, %b, %%دیاریکەرەکانی فۆرماتی زیاتر: %d، %f، %s، %c، %b، %%

Each specifier has a conversion letter for one kind of value. Using the wrong one is an error at run time (see Common mistakes). The real output of the program below:

هەر پیتێکی گۆڕینی هەیە بۆ یەک جۆر . بەکارهێنانی پیتی هەڵە هەڵەیەکە لە کاتی جێبەجێکردندا (بڕوانە هەڵە باوەکان). ڕاستەقینەی ئەم خوارەوە:

SpecifierForبۆExampleنموونەPrintsچاپ دەکات
%da whole number4242
%fa decimal number, 6 places، 6 3.141593.141590
%.1f1 decimal place1 3.141593.1
%stext (any value)دەق (هەر )"Duhok"Duhok
%cone characterیەک 'A'A
%ba boolean5 > 3true
%%a percent signنیشانەی سەدی7575%
%na line endingکۆتایی دێڕ
Specifiers.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Specifiers {
    public static void main(String[] args) {
        System.out.printf("[%d]%n", 42);
        System.out.printf("[%5d]%n", 42);
        System.out.printf("[%-5d]%n", 42);
        System.out.printf("[%05d]%n", 42);
        System.out.printf("[%,d]%n", 1250000);
        System.out.printf("[%f]%n", 3.14159);
        System.out.printf("[%.1f]%n", 3.14159);
        System.out.printf("[%8.2f]%n", 3.14159);
        System.out.printf("[%-8.2f]%n", 3.14159);
        System.out.printf("[%,.2f]%n", 1234567.891);
        System.out.printf("[%s]%n", "Duhok");
        System.out.printf("[%10s]%n", "Duhok");
        System.out.printf("[%-10s]%n", "Duhok");
        System.out.printf("[%c]%n", 'A');
        System.out.printf("[%b]%n", 5 > 3);
        System.out.printf("[%d%%]%n", 75);
    }
}

More specifiers: %d, %f, %s, %c, %b, %%دیاریکەرەکانی فۆرماتی زیاتر: %d، %f، %s، %c، %b، %%

Width and flags: lining values upپانی و نیشانەکان: ڕێکخستنی نرخەکان

A number between % and the letter is a width: the least number of character places. Numbers are pushed to the right of the field. Flags change that: - puts the value on the left, 0 fills with zeros, and , adds the locale's . Precision comes after a point: %8.2f is 8 places wide with 2 decimal places.

ژمارەیەک لە نێوان % و پیتەکەدا پانیـیە: کەمترین ژمارەی شوێنی . ژمارەکان دەخرێنە لای ڕاستی خانەکە. نیشانەکان ئەمە دەگۆڕن: - دەخاتە لای چەپ، 0 بە سفر پڕی دەکاتەوە و , زیاد دەکات. وردی لە دوای خاڵێک دێت: %8.2f پانییەکەی 8 شوێنە و 2 هەیە.

Specifiers and what they print, one character per cell, spaces shown as small marks: %5d of 42 gives three spaces and 42; %-5d gives 42 and three spaces; %05d gives 00042; %8.2f of 3.14159 gives four spaces and 3.14; %-10s of "Duhok" gives Duhok and five spaces; %,d of 1250000 gives 1,250,000. Note: if the width is too small, Java never cuts the value; it uses as many places as it needs.دیاریکەرەکانی فۆرمات و ئەوەی چاپی دەکەن، هەر نووسەیەک لە خانەیەکدا، بۆشاییەکان بە نیشانەی بچووک: %5d بۆ 42 سێ بۆشایی و 42 دەدات؛ %-5d ژمارەی 42 و سێ بۆشایی؛ %05d ژمارەی 00042؛ %8.2f بۆ 3.14159 چوار بۆشایی و 3.14؛ %-10s بۆ "Duhok" وشەی Duhok و پێنج بۆشایی؛ %,d بۆ 1250000 ژمارەی 1,250,000. تێبینی: ئەگەر پانییەکە کەم بێت، Java هەرگیز نرخەکە نابڕێت؛ هێندەی پێویستی بێت شوێن بەکار دێنێت.
A width is a number of character placesپانی بریتییە لە ژمارەی شوێنی CêIT

Widths make columns: every row printed with the same format string has the same layout, as in the shop receipt. Python's widths work the same way (Neat numbers and columns).

پانی ستوون دروست دەکات: هەر ڕیزێک بە هەمان فۆرمات چاپ بکرێت هەمان ڕێکخستنی دەبێت، وەک لە پسوولەی دوکانـدا. پانی لە Pythonـیشدا بە هەمان شێوە کار دەکات (ژمارە و ستوونی ڕێک).

More specifiers: %d, %f, %s, %c, %b, %%دیاریکەرەکانی فۆرماتی زیاتر: %d، %f، %s، %c، %b، %%

String.format: format without printing⁦String.format⁩: فۆرماتکردن بەبێ چاپکردن

String.format takes the same format string and values but returns the text instead of printing it, so you can store it, join it or print it later. Since Java 15 a string can also format itself with formatted(…):

String.format هەمان فۆرمات و وەردەگرێت، بەڵام لە جیاتی چاپکردن دەقەکە دەگەڕێنێتەوە، بۆیە دەتوانیت هەڵیبگریت، بیبەستیت یان دواتر چاپی بکەیت. لە ⁦Java 15⁩ـەوە دەتوانێت بە formatted(…) خۆی فۆرمات بکات:

FormatToText.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class FormatToText {
    public static void main(String[] args) {
        double price = 1.215962441314554;
        String text = String.format("%.2f", price);   // made, not printed
        System.out.println("Stored text: " + text);
        String row = String.format("%-8s|%6.1f|", "Duhok", 21.456);
        System.out.println(row);
        System.out.println("%.3f".formatted(price));     // Java 15 and later
    }
}

printf is a short way to write System.out.print(String.format(…)). Building whole texts with it is taught in Building text.

printf ڕێگایەکی کورتە بۆ نووسینی System.out.print(String.format(…)). دروستکردنی دەقی تەواو پێی لە دروستکردنی دەقـدا دەخوێنرێت.

Computers set to Kurdish or Arabicئەو کۆمپیوتەرانەی بە کوردی یان عەرەبی ڕێکخراون

Java takes its default number format, the format , from the 's region settings. Scanner reads numbers in that format and printf writes them in it. In Central Kurdish (Iraq), ckb_IQ, and Arabic (Iraq), ar_IQ, the decimal point is ٫ and the digits are ٠–٩ (Point, comma or ٫). If your computer's region format is one of them, Java may use it. Any computer can test this with the options -Duser.language and -Duser.country:

Java فۆرماتی بنەڕەتیی ژمارە، واتە فۆرمات، لە ڕێکخستنەکانی ناوچەی وەردەگرێت. Scanner ژمارەکان بەو فۆرماتە دەخوێنێتەوە و printf بەو فۆرماتە دەیاننووسێت. لە کوردیی ناوەندی (عێراق) ckb_IQ و عەرەبی (عێراق) ar_IQـدا، ٫ـە و ٠–٩ن (خاڵ، کۆما یان ٫). ئەگەر فۆرماتی ناوچەی یەکێک لەمانە بێت، ڕەنگە Java بەکاری بهێنێت. هەر دەتوانێت بە بژاردەکانی -Duser.language و -Duser.country ئەمە تاقی بکاتەوە:

LocaleDemo.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Locale;
import java.util.Scanner;

public class LocaleDemo {
    public static void main(String[] args) {
        System.out.println("Format locale: " + Locale.getDefault(Locale.Category.FORMAT));
        Scanner input = new Scanner(System.in);
        System.out.print("Radius: ");
        double radius = input.nextDouble();
        double area = Math.PI * radius * radius;
        System.out.printf("Area: %.2f%n", area);
        System.out.printf("Students: %,d%n", 1250000);
        System.out.println("println: " + area);
    }
}
BASHType in a terminalلە تێرمیناڵدا بینووسە
java -Duser.language=en -Duser.country=US LocaleDemo
java -Duser.language=ckb -Duser.country=IQ LocaleDemo
java -Duser.language=ckb -Duser.country=IQ LocaleDemo
Four runs of the same program. English (US), en_US: Radius 2.5 gives Area: 19.63. Central Kurdish (Iraq), ckb_IQ, typed 2.5: InputMismatchException. ckb_IQ, typed ٢٫٥: Area: ١٩٫٦٣. ckb_IQ with Locale.ROOT: Radius 2.5 gives Area: 19.63. Note: Scanner and printf follow the format locale; println never does. The fix: new Scanner(System.in).useLocale(Locale.ROOT) and System.out.printf(Locale.ROOT, "Area: %.2f%n", area);چوار جێبەجێکردنی هەمان بەرنامە. ئینگلیزی (ئەمریکا)، en_US: نیوەتیرەی 2.5 ← Area: 19.63. کوردیی ناوەندی (عێراق)، ckb_IQ، 2.5 نووسرا: InputMismatchException. ckb_IQ، ٢٫٥ نووسرا: Area: ١٩٫٦٣. ckb_IQ بە Locale.ROOT: نیوەتیرەی 2.5 ← Area: 19.63. تێبینی: Scanner و printf شوێن ڕێکخستنی ناوچەیی دەکەون؛ println هەرگیز. چارەسەر: new Scanner(System.in).useLocale(Locale.ROOT) و System.out.printf(Locale.ROOT, "Area: %.2f%n", area);
The same program with different number formatsهەمان و جیاوازCêIT

Under ckb_IQ, 2.5 stopped the program, while ٢٫٥ worked and printed ١٩٫٦٣ and ١٬٢٥٠٬٠٠٠. Arabic (Iraq) gave the same output, and German (de_DE) wanted 2,5. println printed 19.634954084936208 every time: it never uses the locale.

لە ژێر ckb_IQـدا، 2.5 وەستاند، لە کاتێکدا ٢٫٥ کاری کرد و ١٩٫٦٣ و ١٬٢٥٠٬٠٠٠ـی چاپ کرد. عەرەبی (عێراق) هەمان دا و ئەڵمانی (de_DE) 2,5ـی دەویست. println هەموو جارێک 19.634954084936208ـی چاپ کرد: هەرگیز بەکار ناهێنێت.

Computers set to Kurdish or Arabicئەو کۆمپیوتەرانەی بە کوردی یان عەرەبی ڕێکخراون

The fix: Locale.ROOTچارەسەر: ⁦Locale.ROOT⁩

When a program must read and print 2.5 on every computer, fix the locale in the code: new Scanner(System.in).useLocale(Locale.ROOT) for input and printf(Locale.ROOT, …) for output. Locale.ROOT is a neutral locale with . and , and the digits 0–9; it needs import java.util.Locale;.

کاتێک دەبێت لەسەر هەموو 2.5 بخوێنێتەوە و چاپ بکات، لە کۆددا دیاری بکە: new Scanner(System.in).useLocale(Locale.ROOT) بۆ و printf(Locale.ROOT, …) بۆ . Locale.ROOT بێلایەنە بە . و , و ⁦0–9⁩؛ پێویستی بە import java.util.Locale; هەیە.

LocaleFix.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Locale;
import java.util.Scanner;

public class LocaleFix {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in).useLocale(Locale.ROOT);
        System.out.print("Radius: ");
        double radius = input.nextDouble();
        double area = Math.PI * radius * radius;
        System.out.printf(Locale.ROOT, "Area: %.2f%n", area);
        System.out.printf(Locale.ROOT, "Students: %,d%n", 1250000);
    }
}

The other side: with Locale.ROOT the Scanner refuses ٢٫٥, even on a ckb_IQ computer (InputMismatchException). Tell the user which form to type.

ڕووی تری پرسەکە: بە Locale.ROOT، Scanner ٢٫٥ ڕەت دەکاتەوە، تەنانەت لەسەر ckb_IQـیش (InputMismatchException). بە بڵێ کام شێوە بنووسێت.

String.format(locale, "%,.2f", 12345.678) in five locales, one character per cell: Locale.US 12,345.68; Locale.ROOT 12,345.68; ckb-IQ ١٢٬٣٤٥٫٦٨; ar-IQ ١٢٬٣٤٥٫٦٨; de-DE 12.345,68. The decimal point and the thousands separator are marked. Note: Locale.ROOT keeps 12,345.68 on every computer.String.format(locale, "%,.2f", 12345.678) لە پێنج ڕێکخستنی ناوچەییدا، هەر نووسەیەک لە خانەیەکدا: Locale.US 12,345.68؛ Locale.ROOT 12,345.68؛ ckb-IQ ١٢٬٣٤٥٫٦٨؛ ar-IQ ١٢٬٣٤٥٫٦٨؛ de-DE 12.345,68. فاریزە و جیاکەرەوەی هەزاران نیشانە کراون. تێبینی: Locale.ROOT لەسەر هەموو کۆمپیوتەرێک 12,345.68 دەهێڵێتەوە.
One number in five locales (a real run)یەک ژمارە لە پێنج (جێبەجێکردنی ڕاستەقینە)CêIT

Use Locale.ROOT for numbers that other programs read back. To show numbers the way a Kurdish reader expects, a Kurdish locale is right: String.format(Locale.forLanguageTag("ckb-IQ"), "%,.2f", x) gave ١٢٬٣٤٥٫٦٨ (Grouping thousands). The locale also changes capital letters (Capitals and the computer's language) and month names (Month names).

Locale.ROOT بۆ ئەو ژمارانە بەکار بهێنە کە تر دەیانخوێننەوە. بۆ پیشاندانی ژمارە بەو شێوەیەی خوێنەرێکی کورد چاوەڕێی دەکات، کوردی دروستە: String.format(Locale.forLanguageTag("ckb-IQ"), "%,.2f", x) ١٢٬٣٤٥٫٦٨ـی دا (گرووپکردنی هەزاران). پیتی گەورە (پیتی گەورە و زمانی کۆمپیوتەر) و ناوی مانگەکانیش دەگۆڕێت (ناوی مانگەکان).

A complete program: a shop receiptبەرنامەیەکی تەواو: پسوولەی دوکان

This program puts the lesson together. It reads the customer's name first, a whole line, so no leftover newline can spoil it, then two whole numbers. The prices are named constants. %-10s puts text on the left of ten places; %5d and %,9d push numbers to the right, the second with thousands separators; %.2f rounds the average:

ئەم وانەکە کۆ دەکاتەوە. سەرەتا ناوی کڕیارەکە دەخوێنێتەوە، دێڕێکی تەواو، بۆیە هیچ بەجێماو تێکی نادات، پاشان دوو . نرخەکان . %-10s دەق لە لای چەپی دە شوێن دادەنێت؛ %5d و %,9d ژمارەکان دەبەنە لای ڕاست، دووەمیان بە ؛ %.2f تێکڕاکە نزیک دەکاتەوە:

Receipt.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class Receipt {
    public static void main(String[] args) {
        final int NOTEBOOK_PRICE = 1500;   // dinars
        final int PEN_PRICE = 250;
        Scanner input = new Scanner(System.in);
        System.out.print("Customer: ");
        String customer = input.nextLine();
        System.out.print("Notebooks: ");
        int notebooks = input.nextInt();
        System.out.print("Pens: ");
        int pens = input.nextInt();

        int notebookTotal = notebooks * NOTEBOOK_PRICE;
        int penTotal = pens * PEN_PRICE;
        int total = notebookTotal + penTotal;
        double average = (double) total / (notebooks + pens);

        System.out.println();
        System.out.println("Receipt for " + customer);
        System.out.printf("%-10s%5s%9s%9s%n", "Item", "Qty", "Price", "Total");
        System.out.printf("%-10s%5d%,9d%,9d%n", "Notebook", notebooks, NOTEBOOK_PRICE, notebookTotal);
        System.out.printf("%-10s%5d%,9d%,9d%n", "Pen", pens, PEN_PRICE, penTotal);
        System.out.printf("%-24s%,9d IQD%n", "Total", total);
        System.out.printf("Average per item: %.2f IQD%n", average);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 9

Text first, numbers after: no nextLine trap.

سەرەتا دەق، پاشان ژمارە: تەڵەی nextLine نییە.

Lineدێڕی 22-25

One format string per kind of row keeps the columns straight.

یەک فۆرمات بۆ هەر جۆرە ڕیزێک ستوونەکان ڕێک دەهێڵێتەوە.

The receipt lined up in columns marked with their specifiers: %-10s for Item, Notebook, Pen and Total, on the left; %5d for Qty (3, 4); %,9d for Price (1,500, 250); %,9d for Total (4,500, 1,000, 5,500 IQD). Note: text is left-aligned and numbers right-aligned, with commas; one format string per row keeps every row the same width.پسوولەکە لە ستووندا ڕێکخراوە و هەر ستوونێک دیاریکەری فۆرماتەکەی لەسەرە: %-10s بۆ Item، Notebook، Pen و Total، لە لای چەپ؛ %5d بۆ Qty (3، 4)؛ %,9d بۆ Price (1,500، 250)؛ %,9d بۆ Total (4,500، 1,000، 5,500 IQD). تێبینی: دەق لە لای چەپ و ژمارەکان لە لای ڕاستن، بە جیاکەرەوەی هەزاران؛ یەک زنجیرەنووسەی فۆرمات بۆ هەر ڕیزێک هەموو ڕیزەکان هاوپان دەکات.
Widths line the receipt up in columnsپانییەکان پسوولەکە لە ستووندا ڕێک دەخەنCêIT

Common mistakesهەڵە باوەکان

You wroteنووسیتWhat happensچی ڕوو دەداتFixچارەسەر
no import java.util.Scanner;بێ import java.util.Scanner;cannot find symbol ... class Scanner (2 errors)Add the import above the class.import لە سەرووی زیاد بکە.
new Scanner()no suitable constructor found for Scanner(no arguments)Give it the source: new Scanner(System.in).سەرچاوەکەی پێ بدە: new Scanner(System.in).
nextLine() right after nextInt()nextLine() ڕاستەوخۆ لە دوای nextInt()returns """" دەگەڕێنێتەوەAn extra nextLine(), or read only lines.nextLine()ـێکی زیادە، یان تەنیا دێڕ بخوێنەوە.
nextInt() and the user types abcnextInt() و abc دەنووسێتInputMismatchExceptionCheck with hasNextInt(), or catch the exception.بە hasNextInt() بپشکنە، یان بگرە.
printf("%d", 2.5)IllegalFormatConversionException: d != java.lang.Double%f or %.2f for decimals%f یان %.2f بۆ
printf("%d + %d = %d%n", 2, 3)MissingFormatArgumentException: Format specifier '%d'One value for every specifier.بۆ هەر .
printf("Total: %.2f", x) twiceprintf("Total: %.2f", x) دوو جارTotal: 12.50Total: 3.00End the format string with %n. فۆرمات بە %n تەواو بکە.
"…of radius" + radius…of radius2.5 is …A space inside the quotes.بۆشاییەک لەناو .
close() on a Scanner, then a new Scanner on System.inclose() لەسەر Scanner، پاشان Scannerـێکی نوێ لەسەر System.inNoSuchElementExceptionUse one Scanner for the whole program.یەک Scanner بۆ هەموو بەکار بهێنە.
2.5 on a ckb_IQ computer2.5 لەسەر ckb_IQInputMismatchExceptionuseLocale(Locale.ROOT)useLocale(Locale.ROOT)

Practiceڕاهێنان

ExerciseڕاهێنانFour operationsچوار کاری بیرکاری

Read two whole numbers and print their sum, difference, product and quotient, the quotient with two decimal places.

دوو بخوێنەوە و کۆ، جیاوازی، لێکدان و دابەشکردنیان چاپ بکە؛ دابەشکردنەکە بە دوو .

Hintئاماژە

Use %d for the ints and %.2f for the quotient.

%d بۆ intـەکان و %.⁦2f⁩ بۆ دابەشکردنەکە بەکار بهێنە.

Show answerوەڵامەکە پیشان بدە
FourOperations.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class FourOperations {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("First whole number: ");
        int a = input.nextInt();
        System.out.print("Second whole number: ");
        int b = input.nextInt();
        System.out.printf("%d + %d = %d%n", a, b, a + b);
        System.out.printf("%d - %d = %d%n", a, b, a - b);
        System.out.printf("%d * %d = %d%n", a, b, a * b);
        System.out.printf("%d / %d = %.2f%n", a, b, (double) a / b);
    }
}

(double) a / b divides as decimals; a / b alone would give 3 (Integer division).

(double) a / b بە شێوەی دەیی دابەش دەکات؛ a / b بە تەنیا 3ی دەدا (دابەشکردنی ژمارەی تەواو).

ExerciseڕاهێنانCelsius to Fahrenheitسیلیزی بۆ فەهرەنهایت

Read a temperature in °C and print it in °F with one decimal place: F=C×9/5+32F = C \times 9 / 5 + 32.

پلەی گەرمییەک بە °C بخوێنەوە و بە °F بە یەک چاپی بکە: F=C×9/5+32F = C \times 9 / 5 + 32.

Show answerوەڵامەکە پیشان بدە
CelsiusToFahrenheit.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class CelsiusToFahrenheit {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Temperature in Celsius: ");
        double celsius = input.nextDouble();
        double fahrenheit = celsius * 9 / 5 + 32;
        System.out.printf("%.1f C = %.1f F%n", celsius, fahrenheit);
    }
}

Test with values you know: −40 °C is −40 °F (Test with answers you know).

بە چەند تاقی بکەرەوە کە وەڵامەکانیان دەزانیت: ⁦−40 °C⁩ دەکاتە ⁦−40 °F⁩ (تاقیکردنەوە بە وەڵامی ناسراو).

ExerciseڕاهێنانName first, then ageسەرەتا ناو، پاشان تەمەن

Ask for a full name and an age, then print <name> will be <age + 1> next year. Make sure the full name is read.

ناوێکی تەواو و تەمەنێک بپرسە، پاشان <name> will be <age + 1> next year. چاپ بکە. دڵنیا بە کە هەموو ناوەکە دەخوێنرێتەوە.

Show answerوەڵامەکە پیشان بدە
NextYear.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class NextYear {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Full name: ");
        String name = input.nextLine();
        System.out.print("Age: ");
        int age = input.nextInt();
        System.out.println(name + " will be " + (age + 1) + " next year.");
    }
}

Reading the name first with nextLine() avoids the leftover-newline trap.

خوێندنەوەی ناوەکە بە nextLine() لە سەرەتادا ڕێگە لە تەڵەی بەجێماو دەگرێت.

ExerciseڕاهێنانPredict the outputپێشبینیی دەرخستە بکە

What does each line print? [%6.2f] with 3.14159 · [%-6d] with 42 · [%06d] with 42 · [%,d] with 2026000 · [%.0f] with 7.5 · [%s|%s] with "Hawler" and 7

هەر دێڕێک چی چاپ دەکات؟ [%6.2f] بە ⁦3.14159⁩ · [%-6d] بە ⁦42⁩ · [%06d] بە ⁦42⁩ · [%,d] بە ⁦2026000⁩ · [%.0f] بە ⁦7.5⁩ · [%s|%s] بە ⁦"Hawler"⁩ و 7

Show answerوەڵامەکە پیشان بدە
Predict.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Predict {
    public static void main(String[] args) {
        System.out.printf("[%6.2f]%n", 3.14159);
        System.out.printf("[%-6d]%n", 42);
        System.out.printf("[%06d]%n", 42);
        System.out.printf("[%,d]%n", 2026000);
        System.out.printf("[%.0f]%n", 7.5);
        System.out.printf("[%s|%s]%n", "Hawler", 7);
    }
}

%.0f rounds half up, so 7.5 becomes 8; %s prints any value, even a number.

%.0f نیوە بەرەو سەرەوە نزیک دەکاتەوە، بۆیە ⁦7.5⁩ دەبێتە 8؛ %s هەر چاپ دەکات، تەنانەت ژمارەش.

ExerciseڕاهێنانAt the fruit shopلە میوەفرۆشی

Read the kilos of grapes (a decimal) and the price of one kilo in dinars (a whole number), then print the cost with thousands separators and two decimal places.

کیلۆی تری () و نرخی یەک کیلۆ بە دینار () بخوێنەوە، پاشان تێچووەکە بە و دوو چاپ بکە.

Show answerوەڵامەکە پیشان بدە
FruitShop.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class FruitShop {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Kilos of grapes: ");
        double kilos = input.nextDouble();
        System.out.print("Price of 1 kilo (dinars): ");
        int pricePerKilo = input.nextInt();
        double cost = kilos * pricePerKilo;
        System.out.printf("%.2f kg x %,d = %,.2f dinars%n", kilos, pricePerKilo, cost);
    }
}

%,.2f combines the comma flag and the precision.

%,.2f نیشانەی کۆما و وردی پێکەوە کۆ دەکاتەوە.

Summaryکورتە

  • import java.util.Scanner; and Scanner input = new Scanner(System.in); get a Scanner ready; create one for the whole program.
  • nextInt, nextDouble, nextBoolean, next take one token; nextLine takes the rest of the line.
  • After nextInt() the newline stays: add an extra nextLine() before reading a line.
  • Wrong input: InputMismatchException; no input: NoSuchElementException; hasNextInt() checks first.
  • printf/String.format: %d %f %.2f %s %c %b %% %n, widths (%5d) and flags (-, 0, ,).
  • Scanner and printf follow the format locale; Locale.ROOT keeps 2.5 and 19.63 on every computer.
  • import java.util.Scanner; و Scanner input = new Scanner(System.in); Scanner ئامادە دەکەن؛ یەکێک بۆ هەموو دروست بکە.
  • nextInt، nextDouble، nextBoolean، next یەک پارچە وەردەگرن؛ nextLine ئەوەی لە دێڕەکەدا ماوەتەوە وەردەگرێت.
  • لە دوای nextInt() دەمێنێتەوە: پێش خوێندنەوەی دێڕێک nextLine()ـێکی زیادە دابنێ.
  • هەڵە: InputMismatchException؛ بێ : NoSuchElementException؛ hasNextInt() سەرەتا دەپشکنێت.
  • printf/String.format: %d %f %.2f %s %c %b %% %n، پانی (%5d) و نیشانەکان (-، 0، ,).
  • Scanner و printf شوێن فۆرمات دەکەون؛ Locale.ROOT 2.5 و 19.63 لەسەر هەموو دەهێڵێتەوە.
Review questionsپرسیارەکانی پێداچوونەوە
Why does nextLine() sometimes return an empty string?بۆچی nextLine() هەندێک جار زنجیرەنووسەیەکی بەتاڵ دەگەڕێنێتەوە؟

Because an earlier nextInt() (or nextDouble(), next()) left the newline of its line in the buffer.

چونکە nextInt()ـێکی پێشوو (یان nextDouble()، next()) دێڕەکەی لە جێهێشتووە.

What does %.2f count: decimal places or significant digits?%.2f چی دەژمێرێت: خانەی دەیی یان تاکژمارەی گرنگ؟

Decimal places: digits after the point. 1.22 has two of them.

: دوای . ⁦1.22⁩ دوانی هەیە.

A program prints ١٩٫٦٣ on one computer and 19.63 on another. Why?بەرنامەیەک لەسەر کۆمپیوتەرێک ١٩٫٦٣ و لەسەر یەکێکی تر 19.63 چاپ دەکات. بۆچی؟

printf uses the computer's format locale; printf(Locale.ROOT, …) makes the output the same everywhere.

printf فۆرماتی بەکار دەهێنێت؛ printf(Locale.ROOT, …) لە هەموو شوێنێک وەک یەک دەکات.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Comparisons, Booleans and if…elseبەراوردکردن، بوولیانەکان و ⁦if…else⁩

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.

Appearanceڕووکار

Modeدۆخ
Styleشێواز
Coloursڕەنگەکان

Saved on this device only.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.