I am trying to copy the contents of a .txt file to an array and print it to the console.
The code requires a main method with two scanners (one to read input from the user, and the second to read the file), a method to make the array, and a method to print the array.
I have successfully managed to make an array and print it, but the output is not ideal. It is scattered and difficult to read. Can someone help me to improve my output so it reads more like a list?
Here is my code:
public class CutupSongCreator {
// Creates two Scanner objects; one reads input from console, the other scans a file
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in); // SCANNER ONE (reads input)
System.out.print("What is the input filename? ");
String filename = console.next();
File f = new File(filename);
while (!f.exists()) {
System.out.print("That file does not exist. Try again: ");
filename = console.next();
f = new File(filename);
}
Scanner input = new Scanner(f); // SCANNER TWO (reads file)
SongLine[] arr = makeArray(input);
printArray(arr);
// Sort by genre
// System.out.print("What genre are you looking for: ");
// String genretype = console.next();
// if (genretype == input.next()) {
// System.out.print("You can't just make up a genre. Try again: ");
// genretype = console.next();
// }
// listLinesByGenre(arr, genretype);
}
// Creates an array of SongLines from a set of lines
public static SongLine[] makeArray(Scanner reader) {
int total = reader.nextInt(); // First int = # of lines
SongLine[] arr = new SongLine[total]; // New array to hold the length of the file
for(int i = 0;i < total; i++) {
String genre = reader.next();
int lineNumber = reader.nextInt();
String words = reader.nextLine();
SongLine temp = new SongLine(genre, lineNumber, words);
arr[i] = temp;
}
reader.close();
return arr;
}
// Prints out the elements of an array
public static void printArray(SongLine[] songs) {
System.out.println(Arrays.toString(songs));
}
}
My code makes use of a constructor class, which I could post if needed, but I think I just do not understand how to read or use the constructor file. Below are the current and desired output. The desired shows the genre, lineNumber, and script, and I would like to print it looking as so.
Current Output
Desired Output
Thank you.
Related
This is for a school project that I'm doing. I need to take data from a file and use setter methods to assign the next part of the line to different parts of a class. I have to assign all of that information for multiple instances in an array.
public static void main(String[] args) throws Exception {
//declarations and input
Scanner input = new Scanner(System.in);
System.out.println("Enter the file to read from: ");
String fileIn = input.next();
System.out.println("Enter the number of accounts in the file: ");
int number = input.nextInt();
System.out.println("Enter the file to output the distribution list to: ");
String fileOut = input.next();
//call function
Account[]students = (readFile(fileIn, number));
System.out.println("Done with File");
}
public static Account[] readFile(String file, int column) throws Exception
{
File myFile = new File(file);
Scanner fileInput = new Scanner(myFile);
Account[]students = new Account[column];
while(fileInput.hasNext())
{
for(int i=0; i<=column; i++)
{
students[i].setID(fileInput.nextInt());
students[i].setName(fileInput.next());
students[i].setUsername(fileInput.next());
students[i].setPassword(fileInput.next());
students[i].setEmail(students[i].getUsername()+"#mail.nwmissouri.edu");
}
}
return students;
}
When I test it out I get this error:
Exception in thread "main" java.lang.NullPointerException
at project6driver.Project6Driver.readFile(Project6Driver.java:36)
at project6driver.Project6Driver.main(Project6Driver.java:22)
36 is the first time I'm using the setter method inside my for loop. I don't understand why this doesn't work, can somebody point me in the right direction?
I have a file that I am importing and what I want do is ask for the user's input and use that as the basis for finding the right line to examine. I have it set up like this:
public class ReadLines {
public static void main(String[] args) throws FileNotFoundException
{
File fileNames = new File("file.txt");
Scanner scnr = new Scanner(fileNames);
Scanner in = new Scanner(System.in);
int count = 0;
int lineNumber = 1;
System.out.print("Please enter a name to look up: ");
String newName = in.next();
while(scnr.hasNextLine()){
if(scnr.equals(newName))
{
String line = scnr.nextLine();
System.out.print(line);
}
}
}
Right now, I am just trying to get it to print out to see that I have captured it, but that's not working. Does anyone have any ideas? Also, if it matters, I can't use try and catch or arrays.
Thanks a lot!
You need to cache the line in a local variable so you can print it out later. Something like this should do the trick:
while(scnr.hasNextLine()){
String temp = scnr.nextLine(); //Cache variable
if (temp.startsWith(newName)){ //Check if it matches
System.out.println(temp); //Print if match
}
}
Hope this helps!
I'd do something in the lines of:
Scanner in = new Scanner(System.in);
System.out.print("Please enter a name to look up: ");
String name = in.next();
List<String> lines = Files.readAllLineS(new File("file.txt").toPath(), StandardCharsets.UTF_8);
Optional<String> firstResult = lines.stream().filter(s -> s.startsWith(name)).findFirst();
if (firstResult.isPresent) {
System.out.print("Line: " + firstResult.get());
} else {
System.out.print("Nothing found");
}
I'm writing a program to read data from files with various sports statistics. Each line has information about a particular game, in say, basketball. If a particular line contains an "#" symbol, it means that one of the teams is playing at home. I'm trying to count the lines that contain an "#" and output that to the user as the Number of Games in which either team played at home. The first file has that 9 games were played at home for some team, but my output keeps printing out 0 rather than 9. How can I fix this?
Here's the relevant code:
public static void numGamesWithHomeTeam(String fileName) throws IOException{
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = input1.nextLine();
Scanner lineScan = new Scanner(line);
int count = 0;
while(input1.hasNextLine()){
if(line.contains("#")){
count++;
input1.nextLine();
} else{
input1.nextLine();
}
}
System.out.println("Number of games with a home team: " + count);
}
Your line variable always has the first line's value. You should set line in the loop, something like that.
while(input1.hasNextLine()){
if(line.contains("#")){
count++;
line = input1.nextLine();
} else{
line = input1.nextLine();
}
Edit: On the second look your code has other problem: the last line is never checked. You should not initialize line (set to null) and do the check after nextLine():
public static void numGamesWithHomeTeam(String fileName) throws IOException{
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = null;
Scanner lineScan = new Scanner(line);
int count = 0;
while(input1.hasNextLine()){
line = input1.nextLine();
if(line.contains("#")){
count++;
}
}
System.out.println("Number of games with a home team: " + count);}
I have to read in integers from an input file based on whether or not a string that appears before them is a certain keyword "load". There is no key number telling how many numbers are about to be inputted. These numbers must be saved to an array. In order to avoid creating and updating a new array for each additional number scanned, I'd like to use a second scanner to first find the amount of integers, and then have the first scanner scan that many times before reverting back to testing for strings. My code:
public static void main(String[] args) throws FileNotFoundException{
File fileName = new File("heapops.txt");
Scanner scanner = new Scanner(fileName);
Scanner loadScan = new Scanner(fileName);
String nextInput;
int i = 0, j = 0;
while(scanner.hasNextLine())
{
nextInput = scanner.next();
System.out.println(nextInput);
if(nextInput.equals("load"))
{
loadScan = scanner;
nextInput = loadScan.next();
while(isInteger(nextInput)){
i++;
nextInput = loadScan.next();
}
int heap[] = new int[i];
for(j = 0; j < i; j++){
nextInput = scanner.next();
System.out.println(nextInput);
heap[j] = Integer.parseInt(nextInput);
System.out.print(" " + heap[j]);
}
}
}
scanner.close();
}
My problem seems to be that scanning via loadscan, the secondary scanner only meant for integers, also moves the primary scanner forward. Is there any way to stop this from happening? Any way to make the compiler treat scanner and loadscan as separate objects despite them preforming the same task?
You may certainly have two Scanner objects read from the same File object simultaneously. Advancing one will not advance the other.
Example
Assume that the contents of myFile are 123 abc. The snippet below
File file = new File("myFile");
Scanner strFin = new Scanner(file);
Scanner numFin = new Scanner(file);
System.out.println(numFin.nextInt());
System.out.println(strFin.next());
... prints the following output...
123
123
However, I don't know why you would want to do that. It would be much simpler to use a single Scanner for your purposes. I called mine fin in the following snippet.
String next;
ArrayList<Integer> readIntegers = new ArrayList<>();
while (fin.hasNext()) {
next = fin.next();
while (next.equals("load") {
next = fin.next();
while (isInteger(next)) {
readIntegers.Add(Integer.parseInt(next));
next = fin.next();
}
}
}
I'm trying to alternate a file but keeping some lines intact based on a user input. (Details below code)
public class RemoveLines {
public static void main(String[] args)
throws FileNotFoundException {
// prompt for input file name
Scanner console = new Scanner(System.in);
System.out.print("Type first file name to use: ");
String filename1 = console.nextLine();
System.out.print("Type second file name to use: ");
String filename2 = console.nextLine();
System.out.println("enter an integer: ");
int n = console.nextInt();
Scanner input = new Scanner(new File(filename1)); //put the first file as input
PrintStream output = new PrintStream(new File(filename2)); //put the second file as output
int count =0;
while(input.hasNextLine()){
count ++;
while(n<=count){
output.println(); // this is where i don't know what to place
}
}
}
}
the program should prompt the user to enter 2 file names and an integer n.
it should create a second file that contains the first n lines of the first file, while keeping it intact. If the first file contains less than n lines then the second file will contain all the lines of the first file.
i've started writing the while loop, but i am not sure what command i should include in order to have the desired output.
thank you.
Have a try with the following code:
int count = 0;
while (count < n) {
if (input.hasNextLine()) {
output.println(input.nextLine()); // this is where i don't know what to place
count++;
}else
{
break;
}
}
/**
* Close scanner
*/
input.close();
console.close();
output.close();
while(input.hasNextLine()){
count ++;
while(n<=count){
output.println(input.nextLine());
} else {
break;
}
}
You should also check the the input file exists.
And also you should close your input and output. I will not matter in this trivial case but it's something you should do in more complex applications.
You should open PrintStream with the append option set to true (which is false by default) -
PrintStream output = new PrintStream(new File(filename2, **true**));
Then you can do something like below -
String inputLine = scanner.readLine();
output.append(inputLine);