🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this guide, you will learn about the Scanner hasNext() method in Java programming and how to use it with an example.
1. Scanner hasNext() Method Overview
Definition:
The hasNext() method of the Scanner class in Java checks if there is another token available in the input of this scanner. This method is particularly useful in loops to check if there's more data to process.
Syntax:
public boolean hasNext()
Parameters:
This method does not take any parameters.
Key Points:
- The method returns true if there's another token available, otherwise, it returns false.
- This method is blocking, which means if you call it, it might wait indefinitely until there's more input (like if the input source is the console).
- It does not advance the scanner past any input.
2. Scanner hasNext() Method Example
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter some words, type 'exit' to quit:");
while(scanner.hasNext()) {
String word = scanner.next();
if("exit".equalsIgnoreCase(word)) {
break;
}
System.out.println("You entered: " + word);
}
}
}
Output:
Enter some words, type 'exit' to quit: hello You entered: hello world You entered: world exit
Explanation:
In this example, the program prompts the user to enter words. It uses the hasNext() method to determine if there is another word available in the input. The loop keeps reading words until the user enters 'exit', which will break out of the loop.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment