Michael Duffett
Michael Duffett

Reputation: 87

Getting Input From Files

I am attempting to read from text files and print them out, and this program I have works how I want it to, except instead of printing out after every space in the text file I want it to print it out after every comma.

Here is my code:

package com.filetoscreen;

import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class readFile {


    private Scanner x;

    public void openFile(){
        try{
            x = new Scanner(new File("input.txt"));
        }
        catch(Exception e){
            System.out.println("Couldn't find input.txt");
        }
    }

    public void readFile(){
        while(x.hasNext()){
            String a = x.next();
            System.out.print(a + " ");


            JFrame frame = new JFrame("Game Name Generator");
            frame.setSize(1400, 1200);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setBackground( Color.black );
            JLabel label = new JLabel(a + " ", SwingConstants.CENTER);
            frame.add(label);
            label.setFont(new Font("SansSerif", Font.BOLD, 75));
            label.setForeground(Color.BLUE);
            frame.setLocationRelativeTo(null);
            frame.setResizable(true);
            frame.setVisible(true);
        }
    }

    public void closeFile(){
        x.close();
    }
}

I call these in another class, so I won't bother putting that in there.

Upvotes: 0

Views: 43

Answers (1)

Quagaar
Quagaar

Reputation: 1287

Set comma as delimiter for the Scanner:

    final Scanner s = new Scanner(new StringReader("a b, c d, ef"));
    s.useDelimiter(",");
    while (s.hasNext()) {
        System.out.println(s.next());
    }

Upvotes: 1

Related Questions