Eclipse环境下如何从扫描文件中打印选中的目标字符串?
Hey there! Let's get your ticket selection feature working smoothly. I notice your code is missing some key parts—like reading the actual event data from the files and handling the final selection output. Let's break this down step by step and put it all together.
First, Let's Fix the Scanner Buffer Issue
When you use scan.nextInt(), it leaves a newline character in the input buffer, which can cause weird behavior later if you use scan.nextLine(). We'll add a quick scan.nextLine() after each nextInt() to clear that buffer right away.
Create Reusable Helper Methods
Instead of writing duplicate code for reading dataNamai.txt and dataIsvyka.txt, let's make a helper method to read any file into a list of strings. This keeps your code clean and easier to update later. We'll also add a method to display numbered options consistently.
Complete the Missing Logic
We'll finish the dataNamai() and dataIsvyka() methods to load event options from their files, then handle the final selection output in getTicket(). Plus, we'll add input validation to handle invalid number picks gracefully.
Here's the completed code with all these fixes:
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class teller { static Scanner scan = new Scanner(System.in); static String[] rungtyniuBilietai = {"1) Namų rungtynės", "2) Išvykos rungtynės"}; static File dataNamai = new File("src/dataNamai.txt"); static File dataIsvyka = new File("src/dataIsvyka.txt"); static String name; static int number; static int number2; // Store loaded event options to access later for selection static List<String> currentEventOptions = new ArrayList<>(); public static void main(String[] args) { try { getName(); } catch (FileNotFoundException e) { System.out.println("Error loading event files: " + e.getMessage()); } } public static void getName() throws FileNotFoundException { System.out.println("Prašome įvesti savo vardą:"); name = scan.nextLine(); System.out.println("\nSveiki, - " + name + ", Klaipėdos 'Neptūno' fane!"); getTicket(); } public static void getTicket() throws FileNotFoundException { System.out.println("\nPrašome pasirinkti skaičių rungtynių , į kurias norite įsigyti bilietus:"); for (String option : rungtyniuBilietai) { System.out.println(option); } number = scan.nextInt(); scan.nextLine(); // Clear leftover newline from nextInt() // Load and display corresponding event options if (number == 1) { dataNamai(); } else { dataIsvyka(); } // Get user's specific event selection System.out.println("\nPrašome pasirinkti norimą rungtynių variantą:"); number2 = scan.nextInt(); scan.nextLine(); // Clear newline buffer again // Validate selection and output result if (number2 >= 1 && number2 <= currentEventOptions.size()) { String selectedEvent = currentEventOptions.get(number2 - 1); System.out.println("\nYou have selected: " + selectedEvent); } else { System.out.println("\nNeteisingas pasirinkimas! Bandykite dar kartą."); getTicket(); // Restart selection if input is invalid } } public static void dataNamai() throws FileNotFoundException { currentEventOptions = readFileLines(dataNamai); displayOptions(currentEventOptions); } public static void dataIsvyka() throws FileNotFoundException { currentEventOptions = readFileLines(dataIsvyka); displayOptions(currentEventOptions); } // Helper: Read all lines from a file into a list private static List<String> readFileLines(File file) throws FileNotFoundException { List<String> lines = new ArrayList<>(); Scanner fileScanner = new Scanner(file); while (fileScanner.hasNextLine()) { lines.add(fileScanner.nextLine()); } fileScanner.close(); return lines; } // Helper: Display numbered options to the user private static void displayOptions(List<String> options) { for (int i = 0; i < options.size(); i++) { System.out.println((i + 1) + ") " + options.get(i)); } } }
Key Changes Explained:
- Added a
main()method to actually start your program (it was missing before!). readFileLines()handles all file reading logic once, so you don't repeat code for home/away games.displayOptions()ensures all numbered lists look consistent for the user.- Added input validation to catch invalid number picks and restart the selection process.
- Fixed the scanner buffer issue to prevent unexpected empty inputs.
- Stored loaded event options in
currentEventOptionsso we can easily fetch the selected string later.
How It Runs:
- User enters their name, then picks home or away games.
- Program loads the corresponding event file and shows numbered game options.
- User selects a number—if valid, it prints "You have selected: " plus the game string from the file.
- If the user picks an invalid number, it prompts them to try again.
Just make sure your dataNamai.txt and dataIsvyka.txt files have one game event per line (e.g., "Klaipėda vs Vilnius, 2024-10-05") and they're in the correct src/ directory.
内容的提问来源于stack exchange,提问作者user9278936

