Problem Defined: I store bookname and bookauthor variable data in file using tostring to buffer writer, When i run program next time program read the file but not to store data back to the variable
Please write read code and and variable data storing from file in JAVA
...........................................................................................................................................................
Three Classes One is Main Class,Second is filewriting class and One Class having book add function.Source Code is given here
import java.util.Scanner;
import java.io.*;
public class AddBook extends Filewriting{
public int add;
public AddBook(int add){this.add=add;}
public String bookname[] = new String[15];
public String bookauthor[] = new String[15];
public int price[] = new int[15];
public void addbook(){
for(int i=0;i<add;i++){
System.out.println("Enter the Book Title:");
Scanner input=new Scanner(System.in);
bookname[i]=input.nextLine();
System.out.println("Enter the Book Author:");
Scanner scan=new Scanner(System.in);
bookauthor[i]=input.nextLine();
System.out.println("Enter the Book Price:");
Scanner input1=new Scanner(System.in);
price[i]=input1.nextInt();
}
}
public String toString(int j)
{
return String.format("BookName:%s%nBookAuthor:%s%nBookPrice:%d%n%n................................................................................................................................%n",bookname[j],bookauthor[j],price[j]);
}
}
import java.util.*;
import java.io.*;
public class Filewriting {
public int add;
public void filewriting(){
System.out.println("How many Books you want to added:");
Scanner in=new Scanner(System.in);
add=in.nextInt();
try{
File file = new File("Hello1.txt");
// creates New file
file.createNewFile();
Writer writer = new FileWriter("Hello1.txt",true);
BufferedWriter bufferWriter = new BufferedWriter(writer);
AddBook obj=new AddBook(add);
obj.addbook();
for ( int i = 0; i < add; i++){
// bufferWriter.write(obj.bookname[i] + obj.bookauthor[i] +obj.price[i]);
bufferWriter.write(obj.toString(i));
}
bufferWriter.close();
}
catch(Exception e)
{
}
}
/* // Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
fr.close(); */
}
import java.util.Scanner;
import java.io.*;
public class Test{
public static void main(String args[]){
System.out.println("Enter 1 to Add Books:");
System.out.println("Enter 2 to Check Store Books again in Variable:");
Scanner input=new Scanner(System.in);
int i=input.nextInt();
if(i==1){
System.out.println("You Press B");
Filewriting fw=new Filewriting();
fw.filewriting();
}
if(i==2)
{
Filewriting fw=new Filewriting();
AddBook obj=new AddBook(fw.add);
for ( int j = 0; j < 2; j++) // for storing 2 variables data
{
System.out.println(obj.bookname[j]); // just check bookname,shows null
}
}
// Please write code that we read the file as well as data is stored again in Variables
}
}
I see You can write Data in File as not well.From your Code it is impossible to Store data in your variables.You must set and get Methods in your program in order to store variables.Following Program Code is help you to storing file data to variable perfectly.
................................................................................
public class Book {
public String name;
public String author;
public int price;
public Book(){
this("","",0);
}
public Book(String name,String author,int price){
setName(name);
setAuthor(author);
setPrice(price);
}
public void setName(String name){
this.name= name ;
}
public void setAuthor(String author){
this.author = author ;
}
public void setPrice(int price){
this.price = price ;
}
public String getName(){
return name;
}
public String getAuthor(){
return author;
}
public int getPrice(){
return price;
}
}
import java.io.*;
import java.util.*;
public class ReadText {
Scanner input,a;
public void OpenBook(){
File f = new File("Hello1.txt");
if ( f.exists()){
System.out.println("Welcome Ur File IS Open....."+f);
}
else
{
System.out.println("Error... File DOes not exits");
System.exit(1);
}
try {
input = new Scanner(new File("Hello1.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void ReadBook(){
Book b = new Book();
while((input.hasNext())){
b.setName(input.nextLine());
b.setAuthor(input.nextLine());
b.setPrice(Integer.parseInt(input.nextLine()));
System.out.printf("Book Name:%s\nBook Author:%s\nBook Price:%d\n",b.getName(),b.getAuthor(),b.getPrice());
}
}
}
Related
I need to open file but it give me an error in the main function
I'm trying to let the user but the file name if it is not correct the program will give an error message and terminate the program
Here is my program.
//import java.io.File;
//import java.io.PrintWriter;
import java.util.Scanner;
import java.io.*; // file input/output
import java.io.IOException;
public class Stock{
String name;
String symbol;
double Price;
//Random randomNumbers = new Random();//Generate random numbers
Stock(){ // no-argument constructor
name="";
symbol="";
Price=0.0;
}
Stock(String n,String s,double p){ //constructor with argument
name=n;
symbol=s;
Price=p;
}
public void setname(String name){//mutators to set the value of name
this.name=name;
}
public void setsymbol(String symbol){//mutators to set the value of symbol
this.symbol=symbol;
}
public void setnextPrice(double price){
this.Price = price;
}
public String getname(){//accessor to get the name
return name;
}
public String getsymbol(){ //accessor to get the symbol
return symbol;
}
public double getPrice(){//accessor to get currentPrice
return Price;
}
public void openfile()throws IOException{
String f="";
System.out.print("Please enter the file name: "+f);
if (f.equals("stocks.txt")){
Scanner x;
x= new Scanner(new File("stocks.txt"));
//PrintWriter outputFile = new PrintWriter("output.txt");
String name = x.nextLine();
System.out.println(name);
}
else{
System.out.println("File Not Found");
return;
}
}
}
I assume you are trying to read a file named stocks.txt and get it's contents line by line, you can do this in multiple ways
using Files API
import java.nio.file.Files;
import java.nio.file.Paths;
List lines = Files.readAllLines(Paths.get(uri),
Charset.defaultCharset());
iterate over this list and get content
using Scanner
File file = new File("stock.txt");
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
Using
File file = new File("stocks.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
System.out.println(dis.readLine());
}
}
catch (..) {}
you can use either one of way to achieve it, using Files API is easier way.
I have an assignment for school that's all about using files, HashMap and ArrayList. This assignment requires 4 classes.
The first class is called FileReader and reads a txt file which is written line by line and each field that we need is separated by ";", for example ("Columbia University";"USA";78.86;2012). Each line contains 2 strings (university name and country) and 2 numbers (score and year). The FileReader class after reading the txt file returns its content in an arraylist.
The second class of the assignment is called UniversityScores and it has 4 fields (uniname, country, score, year), a constructor, accessor methods for all fields and a toString method.
The third class is the heart of our program. This class is called FileEditor and creates a Hashmap<Integer,ArrayList<UniversityScores>> where the key is the year field of each object and value I guess is the rest of the line. My problem is filling the right way the HashMap.
Also, my final 4th class is called FileWriter which creates a new txt and writes inside of it. All my classes work as supposed to except my FileEditor class. Any help needed. Thank you in advance!
Edit
I am supposed to write some other methods as well. For now my problem is the FileEditor class. I also posted the TestFiles class which contains the main function.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
class FileReader{
private String fileName;
private Scanner scanner;
private File file;
private ArrayList<String> arrayList;
private String line;
public FileReader(String otherFileName){
this.fileName = otherFileName;
this.file = new File(fileName);
}
public boolean initReader(){
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("Just caught a FileNotFoundException.");
}
if(file.exists()){
return true;
}
else{
return false;
}
}
public ArrayList<String> readFile(){
this.arrayList = new ArrayList<String>();
while (scanner.hasNextLine()) {
this.line = scanner.nextLine();
arrayList.add(line);
}
arrayList.remove(0);
//System.out.println(arrayList);
return arrayList;
}
public void closeReader(){
scanner.close();
System.out.println("Scanner closed");
}
}
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
class FileWriter{
private String path;
private PrintWriter writer;
private File outputFile;
public FileWriter(String otherPath){
this.path = otherPath;
this.outputFile = new File(path);
}
public boolean initWriter(){
try{
writer = new PrintWriter(path);
}
catch (FileNotFoundException e){
System.out.println("just caught an exception");
}
if(outputFile.exists()){
return true;
}
else{
return false;
}
}
public void writeFile(){
writer.println("The first line");
writer.println("The second line");
writer.println("Christos");
}
public void closeWriter(){
writer.close();
System.out.println("Writer closed");
}
}
class UniversityScore{
private String name;
private String country;
private double score;
private int year;
public UniversityScore(String otherName, String otherCountry, double otherScore, int otherYear){
this.name = otherName;
this.country = otherCountry;
this.score = otherScore;
this.year = otherYear;
}
public String getName(){
return name;
}
public String getCountry(){
return country;
}
public double getScore(){
return score;
}
public int getYear(){
return year;
}
public String toString(){
String outputString = name + "\t" + country + "\t" + score + "\t" + year;
return outputString;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
class FileEditor{
private HashMap<Integer, ArrayList<UniversityScore>> scores = new HashMap<Integer, ArrayList<UniversityScore>>();
private ArrayList<String> lines;
public FileEditor(ArrayList<String> otherLines){
this.lines = otherLines;
}
public void fillHashMap(){
// that's where I need help
}
}
public class TestFiles {
public static void main(String[] args){
FileReader reader = new FileReader("universities.txt");
if(reader.initReader()){
FileEditor editor = new FileEditor(reader.readFile());
reader.closeReader();
editor.fillHashMap();
FileWriter writer = new FileWriter("universities_2015_output.txt");
if(writer.initWriter()){
writer.writeFile(editor.getScoresOfYear(2015));
writer.closeWriter();
}
else{
System.out.println("Error creating file");
}
System.out.println("Average university score of year 2015: "+editor.getAverageOfYear(2015));
System.out.println("Min university score of year 2015: "+editor.getMinOfYear(2015));
System.out.println("Max university score of year 2015: "+editor.getMaxOfYear(2015));
}
else{
System.out.println("Error opening file");
}
}
}
You will need a way to parse your lines into UniversityScore objects.
Now that you have all the scores, you can add it to your map, according to their year values (may be score but the type doesn't match nor makes practical sense), for example:
for(String line : lines){
String[] vals = line.split(";");
UniversityScore score = new UniversityScore(vals[0],vals[1],Double.parseDouble(vals[2]),Integer.parseInt(vals[3]))
if(scores.containsKey(score.getYear()){ // If the key exists
scores.get(score.getYear()).add(score);
}else{ // If the key doesn't exist, it must be created and added to the map
ArrayList<UniversityScore> newList = new ArrayList<>();
newList.add(score);
scores.put(score.getYear(), newList)
}
}
I noticed your map has an Integer key which corresponds to the year property of a score, so I assumed the map's keys are the years and not the scores as you suggested.
I didn't check if the code works, but it should at least give you an idea on how to fill your map.
It looks like you're being tasked with reading data from a file, and then generating some stats about the data in the file.
Currently, you're simply plopping each line in the ArrayList.
Looks like your next step is to go through each item in that list, and create a UniversityScore object. This is where you will have to parse each string into values that can be assigned to the various fields in the UniversityScore object. When you have done that, put the current line number (as an Integer key) and UniversityScore (as the value) in your HashMap.
Once you have done that, you will have to write the missing methods getScoresOfYear(Integer year), getAverageOfYear(int year), getMinOfYear(int year), and getMaxOfYear(int year) in the editor class.
try this:
public void fillHashMap() {
for(String line : lines) {
String [] fields = line.split(";");
UniversityScores us = new UniversityScores(fields[0], fields[1], fields[2], fields[3]);
if (scores.keySet().contains(us.getScore())) {
scores.get(us.getScore()).add(us);
}
else {
ArrayList<UniversityScores> t = new ArrayList<UniversityScores>();
t.add(us);
scores.put(us.getScore(), t);
}
}
}
I'm getting a ClassCastException when I deserialize my object from a file. When I check the file the object is there, so I know it's being serialized correctly. For some reason the code breaks when trying to retrieve the object. The idea is to allow the user to check, by date, all the workouts they've recorded in their log. Also, I've tried implementing a comparator, but I kept getting the same error and I'm all out of ideas. Any help would be much appreciated.
Here is the code that is causing the trouble:
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
}
Here is the workoutLog class:
public class WorkoutLog implements Serializable{
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
I'm including the body of the code for context
package com.alejandro;
import com.alejandro.Utilities.SerializationUtil;
import com.alejandro.model.Exercise;
import com.alejandro.model.Workout;
import com.alejandro.model.WorkoutLog;
import com.sun.istack.internal.NotNull;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.TreeMap;
public class Logger {
public static final String COMPLETE_KEY = "COMPLETE";
public static final String INCOMPLETE_KEY = "INCOMPLETE";
public static final String ADD_KEY = "ADD";
public static final String CHECK_KEY = "CHECK";
public static final String EXIT_KEY = "EXIT";
public static void main(String[] args) throws IOException, ClassNotFoundException {
Logger logger = new Logger();
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
File file = new File("workout.txt");
//im going to need to ask if the user wants to add a workout, close the program, or select a workout
String userInput = checkUserIntention();
//the switch statement goes through all the possible user inputs
switch(userInput){
case Logger.ADD_KEY:
printInstructions();
do{
logger.promptForExerciseData(workout);
}while(!checkIfUserIsDone());
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
break;
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
} catch(EOFException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(ClassCastException E){
E.printStackTrace();
}
break;
case Logger.EXIT_KEY:
System.out.println("\nExiting program...");
break;
}
}
//I'm using this method to explain to the user how to use the program
protected static void printInstructions(){
System.out.println("\nWelcome to Mr.Strong!\n");
System.out.println("This program was developed to help powerlifters keep a log of their lifts.\n");
System.out.println("Because of this, the program will only recognize the following lifts:\n");
System.out.println("Squat, Bench, Deadlift, Press.\n");
System.out.println("The program is case-sensitive, make sure the information is entered as stated above.\n");
}
//this method asks the user for information about the lifts stores them in a workout object
//the methods used here are all organized throught the page, its just to keep things cleaner and separate
protected void promptForExerciseData(Workout workout){
Exercise exercise = new Exercise();
askForExerciseIdentity(exercise);
askForNumsRelLifts(exercise);
workout.getExerciseList().add(exercise);
}
//this will check to see if the user is done inputting the exercises he did, if he finished the program ends.
protected static boolean checkIfUserIsDone(){
Scanner scanner = new Scanner(System.in);
boolean isUserDone = false;
System.out.println("\nEnter: 'complete'" + ", if you are done. " +
"If not, enter:'incomplete " + ".\n");
String answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.COMPLETE_KEY)){
isUserDone = true;
} else if(answer.trim().toUpperCase().equals(Logger.INCOMPLETE_KEY)){
isUserDone = false;
} else{
checkIfUserIsDone();
}
return isUserDone;
}
//check if user wants to add, review, or close
protected static String checkUserIntention(){
String answer = "a";
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease choose an option:\n" +
"1-) Add a workout. Enter 'Add'.\n" +
"2-) Check a workout Enter 'Check'.\n" +
"3-) Exit the program. Enter 'Exit'\n");
answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.ADD_KEY) ||
answer.trim().toUpperCase().equals(Logger.CHECK_KEY)||
answer.trim().toUpperCase().equals(Logger.EXIT_KEY)){
return answer.toUpperCase();
}else{
System.out.println("Incorrect input.");
checkUserIntention();
}
return answer;
}
//all of this part is asking for the exercise data
//this is the part that asks for exercise id
protected void askForExerciseIdentity(Exercise exercise){
Scanner scanner = new Scanner(System.in);
do{
System.out.println("\nEnter a lift:\n");
String exerciseIdentity = scanner.nextLine();
if(exerciseIdentity.equals(exercise.SQUAT_KEY)){
exercise.setExerciseIdentity(exercise.SQUAT_KEY);
}else if(exerciseIdentity.equals(exercise.PRESS_KEY)){
exercise.setExerciseIdentity(exercise.PRESS_KEY);
}else if(exerciseIdentity.equals(exercise.BENCH_KEY)){
exercise.setExerciseIdentity(exercise.BENCH_KEY);
}else if(exerciseIdentity.equals(exercise.DEADLIFT_KEY)){
exercise.setExerciseIdentity(exercise.DEADLIFT_KEY);
}else {
exercise.setExerciseIdentity(null);
System.out.println("Please enter a valid exercise.");
}}while(exercise.getExerciseIdentity() == null);
}
//this is the part that aks for numbers
protected void askForNumsRelLifts(Exercise exercise){
exercise.setWeightUsed(askForWeightUsed());
exercise.setNumOfReps(askForNumOfReps());
exercise.setNumOfSets(askForNumOfSets());
}
protected double askForWeightUsed(){
Scanner scanner = new Scanner(System.in);
double weightUsed;
do{
try{
System.out.println("\nEnter weight used:\n");
weightUsed = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
weightUsed = 0;
}
} while(weightUsed == 0);
return weightUsed;
}
protected double askForNumOfSets(){
Scanner scanner = new Scanner(System.in);
double numOfSets;
do{
try{
System.out.println("\nEnter sets done:\n");
numOfSets = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
numOfSets = 0;
}
}while(numOfSets == 0);
return numOfSets;
}
protected double askForNumOfReps(){
Scanner scanner = new Scanner(System.in);
double reps;
do{
try{
System.out.println("\nEnter reps done:\n");
reps = Double.parseDouble(scanner.nextLine());
} catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
reps = 0;
}
}while(reps == 0);
return reps;
}
}
Here is workout included:
public class Workout implements Serializable{
protected ArrayList<Exercise> mExerciseList;
protected Date mDateCreated;
public Workout(){
mExerciseList = new ArrayList<>();
mDateCreated = new Date();
}
public ArrayList<Exercise> getExerciseList(){
return mExerciseList;
}
public String getDate(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sdf.format(mDateCreated);
}}
Here is the seralizationutil:
import com.alejandro.model.WorkoutLog;
import java.io.*;
public class SerializationUtil{
public static Object deserialize(File filename) throws IOException, ClassNotFoundException{
FileInputStream fis = new FileInputStream(filename);
Object obj = new Object();
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
while(fis.available()>0){
obj = ois.readObject();
}
ois.close();
return obj;
}
public static void serialize(Object object, File filename) throws IOException{
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.close();
}}
Here is what the compiler gives me:
java.lang.ClassCastException: java.lang.Object cannot be cast to com.alejandro.model.WorkoutLog
at com.alejandro.Logger.main(Logger.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
just try this simple example, i have modified your code extensively
one more thing, I dont know what implementation you have under SerializationUtil so i created my own implementation
My example works without any issue
package week4;
import java.io.Serializable;
import java.util.TreeMap;
public class WorkoutLog implements Serializable {
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
}
package week4;
import java.io.Serializable;
public class Workout implements Serializable {
String date = "2016-01-13";
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
package week4;
import java.io.File;
import java.io.IOException;
public class TestWorkOut {
public static void main(String[] args) throws IOException, ClassNotFoundException {
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
/* I had path to workout.txt as D:\\workout.txt*/
File file = new File("D:\\workout.txt");
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
}
}
package week4;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializationUtil {
public static void serialize(WorkoutLog workoutLog, File filename) {
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(workoutLog);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static WorkoutLog deserialize(File filename) {
FileInputStream fis = null;
ObjectInputStream in = null;
WorkoutLog workout = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
workout = (WorkoutLog) in.readObject();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return workout;
}
}
Output
Workout saved in...workout.txt
Deserializing from:...workout.txt
[2016-01-13]
Hey I'm making a program that takes words+definitions from a text document, scrambles them, then quizzes you on them. The words are structured as (word: definition). I finished the code for the project but for some reason the console stays blank after I compile. The code consists of three classes that I'll display below:
Class 1 :-
public class VocabularyWord {
private String word, definition;
public VocabularyWord(String w, String d){
word=w;
definition=d;
}
public String getDefinition(){
return definition;
}
public String getWord(){
return word;
}
public String toString(){
return word+" "+definition;
}
}
Class 2 :-
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class VocabularyTest {
private ArrayList<VocabularyWord>words;
private int c;
public VocabularyTest() throws FileNotFoundException{
words=new ArrayList<VocabularyWord>();
ArrayList<String> str=new ArrayList<String>();
File inputFile = new File("Vocabulary.txt");
Scanner input = new Scanner(inputFile);
while(input.hasNextLine()){
str.add(input.nextLine());
processStrings(str);
for(int i = 0; i<100; i++)
swapWords();
}
}
private void processStrings(ArrayList<String>lines){
int pos=0;
for(int i=lines.size()-1; i>=0; i--){
pos=lines.get(i).indexOf(":");
String s=lines.get(i).substring(0, pos);
String ss=lines.get(i).substring(pos+1, lines.get(i).length());
VocabularyWord p=new VocabularyWord(s,ss);
words.add(p);
c++;
}
}
private void swapWords(){
int x=(int) (Math.random()*words.size());
int xx=(int)(Math.random()*words.size());
while(x==xx)
xx=(int)(Math.random()*words.size());
Collections.swap(words, xx, x);
}
public void quiz(){
System.out.println("hi");
int n=0;
Scanner kb=new Scanner(System.in);
for(int i=words.size()-1; i>=0; i--){
System.out.println(words.get(i).getDefinition());
if(kb.nextLine().equals(words.get(i).getWord())){
System.out.println("Nice Job!");
n++;
}
else
System.out.println(words.get(i).getWord());
}
System.out.println("You got "+n+" correct!");
}
}
Class 3 :-
import java.io.FileNotFoundException;
public class VocabTestTester {
public static void main(String[] args)throws FileNotFoundException{
VocabularyTest test= new VocabularyTest();
test.quiz();
}
}
I'm guessing that your VocabularyTest constructor is failing, possibly that you're not finding the file adequately, although I'd expect to see an exception from this. You'd do well to check this.
Print "hi" on the first line of the VocabularyTest constructor, print out the file path, and check that it matches the path that you expect, and then print out the words read in to the console.
e.g.,
public VocabularyTest() throws FileNotFoundException{
System.out.println("In VocabularTest Constructor");
words=new ArrayList<VocabularyWord>();
ArrayList<String> str=new ArrayList<String>();
File inputFile = new File("Vocabulary.txt");
System.out.println(inputFile.getAbsolutePath());
Scanner input = new Scanner(inputFile);
while(input.hasNextLine()){
System.out.println(input.nextLin());
}
I'm trying to make it so my program
chooses a file
reads the code one line at a time
uses an interface to do three different things
convert to uppercase
count the number of characters
save to a file ("copy.txt")
I'm stuck with the formatting parts. For instance, I'm not sure where the println commands needs to be. Any help will definitely be appreciated. I'm a beginner and still learning basic things.
Interface for Processing Individual Strings:
public interface StringProcessor
{
void process(String s);
}
Processing Class:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import javax.swing.JFileChooser;
class FileProcessor
{
private Scanner infile;
public FileProcessor(File f) throws FileNotFoundException
{
Scanner infile = new Scanner(System.in);
String line = infile.nextLine();
}
public String go(StringProcessor a)
{
a.process(line);
}
}
Driver Class:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import javax.swing.JFileChooser;
public class Driver
{
public static void main(String[] args) throws FileNotFoundException
{
JFileChooser chooser = new JFileChooser();
File inputFile = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
inputFile = chooser.getSelectedFile();
}
FileProcessor infile = new FileProcessor(inputFile);
int total=0;
}
}
This Would Make Each Line Uppercase:
public class Upper implements StringProcessor
{
public void process(String s)
{
while (infile.hasNextLine())
{
System.out.println(infile.nextLine().toUpperCase());
}
}
}
This Would Count Characters:
public class Count implements StringProcessor
{
public void process(String s)
{
while (infile.hasNextLine())
{
int charactercounter = infile.nextLine().length();
total = total+charactercounter;
}
}
}
This Would Print to a File:
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class Print implements StringProcessor
{
public void process(String s)
{
PrintWriter out = new PrintWriter("copy.txt");
while (infile.hasNextLine())
{
out.println(infile.nextLine());
}
out.close();
}
}
Java was one of the first programming languages I learned and once you get it, it's so beautiful. Here is the solution for you homework, but now you have a new homework assignment. Go and figure out what is doing what and label it with notes. So next time you have a similar problem you can go over your old codes and cherry pick what you need. We were all noobs at some point so don't take it to bad.
StringProcessor.java
public interface StringProcessor {
public String Upper(String str);
public int Count(String str);
public void Save(String str, String filename);
}
FileProcessor.java
import java.io.FileWriter;
public class FileProcessor implements StringProcessor{
public FileProcessor(){
}
// Here we get passed a string and make it UpperCase
#Override
public String Upper(String str) {
return str.toUpperCase();
}
// Here we get passed a string and return the length of it
#Override
public int Count(String str) {
return str.length();
}
// Here we get a string and a file name to save it as
#Override
public void Save(String str, String filename) {
try{
FileWriter fw = new FileWriter(filename);
fw.write(str);
fw.flush();
fw.close();
}catch (Exception e){
System.err.println("Error: "+e.getMessage());
System.err.println("Error: " +e.toString());
}finally{
System.out.println ("Output file has been created: " + filename);
}
}
}
Driver.java
import java.io.File;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class Driver {
#SuppressWarnings("resource")
public static void main(String[] args){
System.out.println("Welcome to the File Processor");
Scanner scan = new Scanner(System.in);
System.out.print("\nWould you like to begin? (yes or no): ");
String startProgram = scan.next();
if(startProgram.equalsIgnoreCase("yes")){
System.out.println("\nSelect a file.\n");
JFileChooser chooser = new JFileChooser();
File inputFile = null;
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
inputFile = new File(chooser.getSelectedFile().getAbsolutePath());
try{
Scanner file = new Scanner(inputFile);
file.useDelimiter("\n");
String data = "";
FileProcessor fp = new FileProcessor();
while (file.hasNext()){
String line = file.next();
System.out.println("Original: " +line);
System.out.println("To Upper Case: " +fp.Upper(line));
System.out.println("Count: " +fp.Count(line));
System.out.println();
data += line;
}
System.out.println("\nFile Processing complete!\n");
System.out.print("Save copy of file? (yes or no): ");
String save = scan.next();
if(save.equalsIgnoreCase("yes")){
fp.Save(data, "copy.txt");
System.out.println("\nProgram Ending... Goodbye!");
}else{
System.out.println("\nProgram Ending... Goodbye!");
}
}catch (Exception e){
e.printStackTrace();
}
}
}else{
System.out.println("\nProgram Ending... Goodbye!");
}
}
}
text.txt
some text here to test the file
and to see if it work correctly
Just a note when you save the file "copy.txt", it will show up in your project folder.
As your problem operates on streams of characters, there is already a good Java interface to implement. Actually, they are two abstract classes: FilterReader or FilterWriter — extending either one will work. Here, I've chosen to extend FilterWriter.
For example, here is an example of a Writer that keeps track of how many characters it has been asked to write:
import java.io.*;
public class CharacterCountingWriter extends FilterWriter {
private long charCount = 0;
public CharacterCountingWriter(Writer out) {
super(out);
}
public void write(int c) throws IOException {
this.charCount++;
out.write(c);
}
public void write(char[] buf, int off, int len) throws IOException {
this.charCount += len;
out.write(buf, off, len);
}
public void write(String str, int off, int len) throws IOException {
this.charCount += len;
out.write(str, off, len);
}
public void resetCharCount() {
this.charCount = 0;
}
public long getCharCount() {
return this.charCount;
}
}
Based on that model, you should be able to implement a UpperCaseFilterWriter as well.
Using those classes, here is a program that copies a file, uppercasing the text and printing the number of characters in each line as it goes.
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
try (CharacterCountingWriter ccw = new CharacterCountingWriter(new FileWriter(args[1]));
UpperCaseFilterWriter ucfw = new UpperCaseFilterWriter(ccw);
Writer pipeline = ucfw) { // pipeline is just a convenient alias
String line;
while (null != (line = in.readLine())) {
// Print count of characters in each line, excluding the line
// terminator
ccw.resetCharCount();
pipeline.write(line);
System.out.println(ccw.getCharCount());
pipeline.write(System.lineSeparator());
}
pipeline.flush();
}
}