Method
Java Scanner.hasNextLine()
Checks whether another line exists without advancing the scanner; may block on live input.
Formal Syntax & Structure
java syntaxjava
public boolean hasNextLine()Working Example
Example Snippetjava
import java.util.Scanner;class Inventory { private final int[] stock = new int[3]; private void checkId(int id) { if (id < 0 || id >= stock.length) throw new IllegalArgumentException("Unknown item"); } int count(int id) { checkId(id); return stock[id]; } void add(int id, int quantity) { checkId(id); if (quantity <= 0 || quantity > 100 - stock[id]) throw new IllegalArgumentException("Invalid quantity or capacity"); stock[id] += quantity; } void take(int id, int quantity) { checkId(id); if (quantity <= 0 || quantity > stock[id]) throw new IllegalArgumentException("Insufficient stock or invalid quantity"); stock[id] -= quantity; }}public class Main { static void run(Scanner input, Inventory inventory) { for (int step = 0; step < 20 && input.hasNextLine(); step++) { String line = input.nextLine(); if (line.length() > 80) { System.out.println("Error: command too long"); continue; } String[] parts = line.strip().split("\\s+"); try { switch (parts[0]) { case "quit" -> { if (parts.length != 1) throw new IllegalArgumentException("Use quit"); return; } case "show" -> { if (parts.length != 2) throw new IllegalArgumentException("Use show ID"); System.out.println("Stock: " + inventory.count(Integer.parseInt(parts[1]))); } case "add", "take" -> { if (parts.length != 3) throw new IllegalArgumentException("Use add/take ID QUANTITY"); int id = Integer.parseInt(parts[1]); int quantity = Integer.parseInt(parts[2]); if (parts[0].equals("add")) inventory.add(id, quantity); else inventory.take(id, quantity); System.out.println("Stock: " + inventory.count(id)); } default -> throw new IllegalArgumentException("Unknown command"); } } catch (NumberFormatException e) { System.out.println("Error: use integer values"); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } } } public static void main(String[] args) { try (Scanner input = new Scanner("add 0 5\ntake 0 2\ntake 0 9\nshow 0\nquit\nadd 0 1\n")) { run(input, new Inventory()); } System.out.println("Session ended"); }}