How to read in user inputs to create objects? - java

I'm pretty new to Java still and I'm working on a project for class, and I'm unsure of how I write my program to take the userInput(fileName) and create a new object from that. My instructions are to write a program which reads in a file name from the user and then reads the data from that file, creates objects(type StudentInvoice) and stores them in an ArrayList.
This is where I am right now.
public class StudentInvoiceListApp {
public static void main (String[] args) {
Scanner userInput = new Scanner(System.in);
String fileName;
System.out.println("Enter file name: ");
fileName = userInput.nextLine();
ArrayList<StudentInvoice> invoiceList = new ArrayList<StudentInvoice>();
invoiceList.add(new StudentInvoice());
System.out.print(invoiceList + "\n");
}

You may try to write a class for serializing / deserializing objects from a stream (see this article).

Well, as Robert said, there's not enough information about the format of the data stored in the file. Suppose each line of the file contains all the information for a student. Your program will consist of reading a file by lines and create a StudentInvoice for each line. Something like this:
public static void main(String args[]) throws Exception {
Scanner userInput = new Scanner(System.in);
List<StudentInvoice> studentInvoices = new ArrayList<StudentInvoice>();
String line, filename;
do {
System.out.println("Enter data file: ");
filename = userInput.nextLine();
} while (filename == null);
BufferedReader br = new BufferedReader(new FileReader(filename));
while ( (line = br.readLine()) != null) {
studentInvoices.add(new StudentInvoice(line));
}
System.out.println("Total student invoices: " + studentInvoices.size());
}

Related

Loop through String array to fill it with input from user

just a another noob to Java with a dumb question.
I am trying to create a function that receives a String array and fills it with text input from the user using Bufferedreader (which I currently want to use).
I sort of have the idea in my head but it gives the error cannot find symbol when using the readline() property. How can I achieve this?
public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void fill_array (String parray []){
for(int i = 0; i < parray.length; i++){
parray[i] = in.readline(); //Here it gives me the error
}
}
readLine() and not readline how embarrasing
Hii Scanner is much more simpler than BufferedReader to read input, Let me give you an example :
import java.util.*;
public class Main
{
public static void main(String arp[])
{
Scanner scanner = new Scanner(System.in);
String address = scanner.nextLine(); // read string with spaces
System.out.println("addres : "+ address);
String name = scanner.next(); // read string without spaces
System.out.println("name : "+ name);
Integer age = scanner.nextInt(); // read Integer input
System.out.println("age : "+ age);
}
}
Scanner java api link : https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

How to JUnit test a Method with a Scanner?

I have a class which reads a file and takes in a user input with a scanner and if the scanner equals a part of a line in that file, it will display a string from the same line.
How would I go and create a Junit test method for this?
Here is some of my code that I want a test method for:
Scanner Input = new Scanner(System.in);
String name = Input.nextLine();
BufferedReader br;
try{
br = new BufferedReader(new FileReader(new File(filename)));
String nextLine;
while ((nextLine = br.readLine()) != null)
{
if (nextLine.startsWith("||"))
{
int f1 = nextLine.indexOf("*");
int f2 = nextLine.indexOf("_");
fName = nextLine.substring(f1+1, f2);
if (name.equals(fname))
{
String[] s1 = nextLine.split("_");
String sName = s1[1];
System.out.println(sName);
}
}
}
my data file looks like this
||
*Jack_Davis
*Sophia_Harrolds
I have tried to use this code in my test method
#Test
public void testgetSurname() {
System.out.println("get surname");
String filename = "";
String expResult = "";
String result = fileReader.getSurname(filename);
assertEquals(expResult, result);
filename = "datafiles/names.txt";
String data = "Jack";
InputStream stdin = System.in;
try{
System.setIn(new ByteArrayInputStream(data.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());
} finally {
System.setIn(stdin);
expResult = "Davis";
}
String result = fileReader.getSurname(filename);
assertEquals(expResult, result);
}
try this for example:
You could enhance it by simulate the console automatically (see below)
#Test
public void test_scan() throws Exception
{
Myclass myobject=new myobject(); // with args
myobject.load(filename); // you must definie the filename
String result=myobject.scaninput_and_compare(); // you must use scan in, and compare
if (!result.equals(what_I_am_expecting) throw new Exception("EXCEPTION scaninput_and_compare");
// If you arrive here, it's OK
}
If you want to automatize the console input, use that:
Courtesy of: JUnit: How to simulate System.in testing?
String data = "What_I_could_put_in_console";
InputStream stdin = System.in;
System.setIn(new ByteArrayInputStream(data.getBytes()));
Scanner scanner = new Scanner(System.in);
System.setIn(stdin);
Beware of catch Exception inside, to finish with a "good" System.in It's ok for a test alone, for several, you should verify.
With your code:
public String scaninput_and_compare(String filename)
{
Scanner Input = new Scanner(System.in);
String name = Input.nextLine();
BufferedReader br;
try{
br = new BufferedReader(new FileReader(new File(filename)));
String nextLine;
while ((nextLine = br.readLine()) != null)
{
if (nextLine.startsWith("||"))
{
int f1 = nextLine.indexOf("*");
int f2 = nextLine.indexOf("_");
fName = nextLine.substring(f1+1, f2);
if (name.equals(fname))
{
String[] s1 = nextLine.split("_");
String sName = s1[1];
return sName;
}
}
}
// NO GOOD
return "lose";
}
#Test
public void test_scan() throws Exception
{
Myclass myobject=new myobject(); // with args
String filename="good_filename";
// MOCK System.in
String data = "Jack";
InputStream stdin = System.in;
System.setIn(new ByteArrayInputStream(data.getBytes()));
String result=myobject.scaninput_and_compare(filename); // you must use scan in, and compare
// RESTABLISH System.in
Scanner scanner = new Scanner(System.in);
System.setIn(stdin);
if (!result.equals("Davis") throw new Exception("EXCEPTION scaninput_and_compare");
// If you arrive here, it's OK
}
BETTER design, and testing more easy: separate your scanner of System.in, from your file parsing. Just do a function with (filename, fname), and it will be direct to test :
assertEquals(myobject.scaninput_and_compare(filename,"Jack"), "Davis");
One way to do it:
Step 1
Refactor your code, so that Scanner is one of the parameters passed into your method.
Step 2
For your test, use constructor Scanner(File file) or Scanner(String source) to feed "what would the user type" - while in the real world (from your main() you'd create Scanner(System.in)
or
Refactor your code to get a protected Scanner getScanner() { } and then use a Mocking framework (I like Mockito) to mock that method and return your String-prepped Scanner (see Step 2)
Requested example (the refactoring)
/**
* Reads the next line from the Scanner
*/
protected String getNextLine(Scanner scanner) {
//You know how to do that.
}
/**
* Check if file contains that name and return matching line.
* Throws NameNotFoundException (you'd need to create) if not found.
*
* If it were my code, i'd refactor even more and pass in List<String>
* here with the lines from the file
*/
public String matchSurname(String name, File dataFile) throws NameNotFoundException {
//Iterate over file...
if(isMatchingSurname(name, line)) {
return line;
}
// end iteration
//Still here? Throw Exception!
throw new NameNotFoundException();
}
/**
* Checks if given Name matches the read line
*/
public boolean isMatchingSurname(String name, String lineFromFile) {
//All the checks
}
Now you've broken your problem down in nice small bites. Unit testing would now be for individual methods only - so one for testing reading a line from Scanner, one for testing the Matching logic and one for correct file iteration.

JAVA IO, Read values from txt file and send to method params

I am trying to write a program that will perform a calculation from a text file input.
The text file contains the following columns: amount1, amount2, amount3
I have a method named Calculate which takes in these parameters and does the calculation and subsequent actions.
I also have a main method as follows, but am experiencing troubles in getting the tokens into the Calculate mthod parametsrs,
please refer to code below:
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class myProgram
{
public static void main(String[] args) throws IOException {
File file = new File( "data.txt");
Scanner infile = new Scanner(file);
while (infile.hasNext() ){
String str = infile.nextLine();
StringTokenizer st = new StringTokenizer(str, ", ");
// I want to get the output of each of the tokens into the parameters of my Calculate class here
}
infile.close();
}
You are trying to read a csv file so better use a CSVReader rather than implementing of your own. OpenCSV is one of the available choice. Here is sample to read a csv file:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
String amount1 = nextLine[0];
String amount2 = nextLine[1];
String amount3 = nextLine[2];
// yourMethod(amount1,amount2,amount3);
}

Java Read from file to Array runtime error

import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();

User Input File Console/Command Line - Java

Most examples out there on the web for inputting a file in Java refer to a fixed path:
File file = new File("myfile.txt");
What about a user input file from the console? Let's say I want the user to enter a file:
System.out.println("Enter a file to read: ");
What options do I have (using as little code as possible) to read in a user specified file for processing. Once I have the file, I can convert to string, etc... I'm thinking it has to do with BufferedReader, Scanner, FileInputStream, DataInputStream, etc... I'm just not sure how to use these in conjunction to get the most efficient method.
I am a beginner, so I might well be missing something easy. But I have been messing with this for a while now to no avail.
Thanks in advance.
To have the user enter a file name, there are several possibilities:
As a command line argument.
public static void main(String[] args) {
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
}
By asking the user to type it in:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
Use a java.io.BufferedReader
String readLine = "";
try {
BufferedReader br = new BufferedReader(new FileReader( <the filename> ));
while ((readLine = br.readLine()) != null) {
System.out.println(readLine);
} // end while
} // end try
catch (IOException e) {
System.err.println("Error Happened: " + e);
}
And fill the while loop with your data processing.
Regards,
Stéphane

Categories

Resources