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?
Related
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.
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 need to write a program that reads and stores an inputted file in Java in a double array. The number of values in the file is stored in the first line of the file, then the actual data values follow.
Here is what I have so far:
public static void main(String[] args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("Please enter the name of the input file: ");
String inputFileName = console.next();
Scanner in = new Scanner(inputFileName);
int n = in.nextInt();
double[] array = new double[n];
for( int i = 0; i < array.length; i++)
{
array[i] = in.nextDouble();
}
console.close();
}
Input File is as follows:
10
43628.45
36584.94
76583.47
36585.34
86736.45
46382.50
34853.02
46378.43
34759.42
37658.32
As of now, regardless of the file name I input, I am getting an exception message:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Project6.main(Project.java:33)
new Scanner(String) constructor scans the specified String. Not the file denoted by the pathname in the string.
If you want to scan the file, use
Scanner in = new Scanner(new File(inputFileName));
Check the following code. Scanner must be provided with File instead of just String as shown in the following snippet:
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter the name of the input file: ");
String inputFileName = console.nextLine();
Scanner in = null;
try {
in = new Scanner(new File(inputFileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int n = in.nextInt();
double[] array = new double[n];
for (int i = 0; i < array.length; i++) {
array[i] = in.nextDouble();
}
for (double d : array) {
System.out.println(d);
}
console.close();
}
}
Sample output:
Please enter the name of the input file: c:/hadoop/sample.txt
43628.45
36584.94
76583.47
36585.34
86736.45
46382.5
34853.02
46378.43
34759.42
37658.32
I'm trying to load some data to a GUI from a text file using a scanner. I have two sections in my text file: Clubs and Members. The code runs okay for the Clubs section. For example, if I have 4 clubs in my list, all of them will be displayed, but for the Members section doesn't matter how many members are in the list, only the first member will be displayed. Here is my code:
public void load (String fileName) throws FileNotFoundException {
FileInputStream fileIn = new FileInputStream("Clubs.txt");
Scanner scan = new Scanner(fileIn);
while (scan.hasNextLine()){
String line = scan.nextLine();
if(line.equals("Members")){
String firstName = scan.next();
String lastName = scan.next();
Pupil p1 = new Pupil( firstName, lastName);
pupils[nbrPupils] = p1;
nbrPupils ++;
}
else if(line.equals("Clubs")){
while (scan.hasNext()){
String club = scan.nextLine();
Club aNewClub = new Club(club);
clubs[nbrClubs] = aNewClub;
nbrClubs ++;
}
}
Hint: you're doing while (scan.hasNext()) in the Clubs section, but you don't do so in the Members section.
convert from while loop to if condition because you just want to check if there is a next line
else if (line.equals("Clubs")) {
if (scan.hasNext()) {/////here if you use while loop , it will loop until the file is finish
String club = scan.nextLine();
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
new ReadFile().load("");
}
public void load (String fileName) throws FileNotFoundException {
FileInputStream fileIn = new FileInputStream("C:\\Clubs.txt");
Scanner scan = new Scanner(fileIn);
boolean membersfound =false;
while (scan.hasNextLine()){
String line = scan.nextLine();
if(line.equals("Members") || membersfound){
String firstName = scan.next();
String lastName = scan.next();
System.out.println("Member "+firstName +":"+ lastName);
}
else if(line.equals("Clubs") ){
while (scan.hasNext()){
String club = scan.nextLine();
if( club.equals("Members")){
membersfound = true;
break;
}
System.out.println("Clubname :" + club
);
}
}
}
}
}
I could have modified the whole program . But i wanted to show you your mistake
Sample clubs.txt file
Members
member1
member2
member3
Clubs
club1
club2
club3
When you do scan.nextLine() it moves the scanner to the line after the one you currently read in. So if you continue to do scan.next() the scanner will start from the end of your current line (in this case line) and reads what's after it.
See here it says:
"Advances this scanner past the current line and returns the input that was skipped"
What you can to is just call split() or substring() on line and extract the information you need.
I want to know how I could take keyboard input and save it as a variable so I can use it with the code below.
Code:
public void readMaze(){
Scanner reader = null;
try {
reader = new Scanner(new FileReader("Maze.txt"));
colSize = reader.nextInt();
rowSize = reader.nextInt();
finishRow = reader.nextInt();
finishCol = reader.nextInt();
startRow = reader.nextInt();
startCol = reader.nextInt();
Instead of having "Maze.txt" I want to have a variable there that can change every time I run the program so I won't have to keep editing the program when I want to use a different file.
You can capture the file name using your Scanner itself:
System.out.println("Please input the file name to use: ");
Scanner reader = new Scanner(System.in);
String fileName = reader.next();
Then proceed with your method as usual, reusing the same Scanner variable for a new Scanner object, this time passing filename you captured earlier:
try {
reader = new Scanner(new FileReader(fileName));
...
}
With this, you'll be able to dynamically change the filename while your program is running.
I would probably use command line arguments:
public static void main(String[] args)
{
final String mazeFilename = args[0]; // perhaps check if args.length > 0
...
}
then
java YourPrgm Maze.txt
You could try scanning them in through the console and changing them from Strings to ints.
public static void main(String[] args) {
int colSize, rowSize, finishRow, finishCol, startRow, startCol = 0;
// note, through console
Scanner in = new Scanner(System.in);
System.out.print("Enter colSize:");
colSize = Integer.parseInt(in.nextLine());
System.out.print("Enter rowSize:");
rowSize = Integer.parseInt(in.nextLine());
System.out.print("Enter finishRow:");
finishRow = Integer.parseInt(in.nextLine());
System.out.print("Enter finishCol:");
finishCol = Integer.parseInt(in.nextLine());
System.out.print("Enter startRow:");
startRow = Integer.parseInt(in.nextLine());
System.out.print("Enter startCol:");
startCol = Integer.parseInt(in.nextLine());
}
}