Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Reading Floating-Point Numbers | Handling Different Types of Input
Java User Input Essentials

bookReading Floating-Point Numbers

Свайпніть щоб показати меню

When you need to read numbers with decimals—such as prices, weights, or measurements—you will use the nextDouble() method from the Scanner class. This method reads the next token from the input as a double, which is Java's data type for representing floating-point numbers. The double type allows you to handle values that have a fractional component, unlike integers which only represent whole numbers. Using nextDouble() is straightforward: after creating your Scanner object, call this method when you expect the user to input a decimal number. This is especially useful for applications that require calculations involving money, scientific data, or any measurement that isn't always a whole number.

PriceReader.java

PriceReader.java

copy
123456789101112131415
package com.example; import java.util.Scanner; public class PriceReader { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the price of the item: "); double price = scanner.nextDouble(); System.out.println("You entered: $" + price); scanner.close(); } }

It is important to understand the distinction between nextInt() and nextDouble() when reading user input. The nextInt() method is designed to read whole numbers—values without any decimal point. If you try to use nextInt() when the user enters a value like 3.99, the program will throw an error because nextInt() cannot process the fractional part. In contrast, nextDouble() is specifically made to handle numbers that include a decimal point. Use nextInt() for counts, ages, or anything that must be a whole number, and use nextDouble() for prices, measurements, or any value that may include decimals.

question mark

Which Scanner method should you use to read a decimal number such as 19.95 from user input?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 2

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 2. Розділ 2
some-alt