简体   繁体   中英

java and reading from .txt files

public class CreditCardHolder
{
/**
 * This method is used to hold credit card numbers
 */
    public static void main(String[] args) throws Exception
    {
        File cardNumbers = new File("creditcardnumbers.txt");
        Scanner cardNumbersInput = new Scanner(cardNumbers);

        cardNumbersInput.useDelimiter("|" + System.getProperty("line.separator"));

        while(cardNumbersInput.hasNextInt())
        {
            int cardNumber = Integer.parseInt(cardNumbersInput.next());
            System.out.printf("%d", cardNumber);
        }

        cardNumbersInput.close();
    }

WHy is this only printing the first line in my .txt file i need it to print whatever is in the file i currently have four numbers like so
4929253776358751
4716026803447186
4539032933695186
5473350227612088

Change to:

public static void main(String[] args) throws FileNotFoundException{
    File cardNumbers = new File("creditcardnumbers.txt");
    Scanner cardNumbersInput = new Scanner(cardNumbers);

    while(cardNumbersInput.hasNextLine()) {
        String cardNumber = cardNumbersInput.nextLine();
        System.out.println(cardNumber);
    }

    cardNumbersInput.close();
}

test hasNextLine() instead hasNextInt() and use nextLine() instead nextInt() as well since you needn't to parse/format anything. For simplicity you should use println instead printf since you have no formatting or so one. And of course avoid use custom delimitter assuming the default one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM