Project compiles but not displaying info in compiler - java

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());
}

Related

Read From Text File "dictionary.txt"

Below is an example of my code. I have a text file called dictionary.txt that I am trying to read from and I keep getting an error in the constructor line. I am unsure how to build the constructor to read the dictionary.txt file and how that interacts with name = new File("dictionary.txt");
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class WordLists{
//instance variables
private String[] words; //array of words taken in
private int wordCount;
private File name;
private Boolean hasLetter;
//constructor
public WordLists(String "WHAT GOES HERE?") throws FileNotFoundException {
//throws exception because it takes and scans a file
wordCount=0;
name=new File("dictionary.txt");
hasLetter=null;
Scanner listScanner=new Scanner(name);
while(listScanner.hasNextLine()){
listScanner.nextLine();
wordCount++;
}
listScanner.close();
words=new String [wordCount];
Scanner secondScanner=new Scanner(name);
for(int i=0; i<wordCount; i++){
words[i]=secondScanner.nextLine();
}
secondScanner.close();
}
Instead of saying it throws a file not found exception in the constructor, say it at the class name. If that doesn’t work, try a try catch syntax instead of throwing an exception in the class
The String in the constructor line should be a variable corresponding to the file path of the .txt file you're trying to read.
Additionally, work on formatting your code to make it easier to read. With formatting, adding in the string variable to the constructor, and then a main method to run the whole thing, the finished class should look something like this:
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class WordLists {
//instance variables
private String[] words; //array of words taken in
private int wordCount;
private File name;
private Boolean hasLetter;
Scanner listScanner, secondScanner;
//constructor
public WordLists(String path) throws FileNotFoundException{
//throws exception because it takes and scans a file
wordCount = 0;
name = new File(path);
hasLetter = false;
listScanner = new Scanner(name);
secondScanner = new Scanner(name);
while(listScanner.hasNextLine()){
listScanner.nextLine();
wordCount++;
}
words = new String [wordCount];
for(int i = 0; i < wordCount; i++){
words[i] = secondScanner.nextLine();
}
listScanner.close();
secondScanner.close();
}
public static void main(String[] args){
try {
WordLists w = new WordLists("dictionary.txt");
}catch (FileNotFoundException e){
e.printStackTrace();
}
System.out.println("Done");
}
}

Radix Sort- Calling Expected exceptions

I am working on a program that uses Radix Sort that reads in words from a file and sorts in ascending order. In order to do this, we must check that all the words in the file are the same length and there is nothing in the file but letter (no symbols, etc). I have the sort working, but I cannot catch whether the strings are the same length or if there are any symbols. Any help on how to write these exception catches would be appreciated.
This is my radix Sort class. There are two comments on where I need to catch the exceptions.
import java.util.ArrayList;
import java.util.Queue;
public class RadixSort implements RadixSortADT {
private ArrayList<String> string;
private ArrayList<LinkedQueue<String>> queues;
private String result;
public RadixSort(ArrayList<String> words) {
string = new ArrayList<>();
queues = new ArrayList<>();
initializeList();
initializeWords(words);
}
public void initializeList() {
for(int i = 0; i < 26; i++){
queues.add(new LinkedQueue<String>());
}
}
public void initializeWords(ArrayList<String> w) {
for(int i = 0; i < w.size(); i++){
string.add(w.get(i).toLowerCase());
}
}
public void sort() {
if(string.isEmpty()){
throw new EmptyCollectionException("File");
}
//Exception needed for string length comparisons
//Exception needed for nonletters in string
for(int j = string.get(0).length()-1; j>= 0; j--){
for(int k = 0; k <string.size(); k++){
char c = string.get(k).charAt(j);
queues.get(c-97).enqueue(string.get(k));
}
int i = 0;
for(int n = 0; n <queues.size(); n++){
while(!queues.get(n).isEmpty()){
string.set(i++, queues.get(n).dequeue());
}
}
}
}
public String toString(){
String result = "";
for(String words: string){
result += words + " ";
}
return result;
}
public boolean isAlpha(ArrayList<String> string2) {
return string2.contains("[a-zA-Z]+");
}
}
This is the driver that was provided for me in order to create the Radix Sort class
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class RadixSortDriver {
public static void main(String[] args) throws FileNotFoundException{
int i = 0;
ArrayList<String> words = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Enter the name of the file to import words");
String filename = scan.nextLine();
//String filename = "four.txt";
Scanner inFile = new Scanner(new File(filename));
while(inFile.hasNext()) {
words.add(inFile.nextLine());
}
RadixSort r = new RadixSort(words);
System.out.println("Unsorted List:\n" + r);
r.sort();
System.out.println("\n\nSorted List:\n" + r);
}
}
This is the Junit Test class that was provided for us in order to catch the exceptions
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import org.junit.Test;
public class RadixSortTest {
#Test
public void testsort1() throws FileNotFoundException {
ArrayList<String> words = new ArrayList<>();
Scanner inFile = new Scanner(new File("four.txt"));
while(inFile.hasNext()) {
words.add(inFile.nextLine());
}
RadixSort evaluator = new RadixSort(words);
evaluator.sort();
assertEquals("atom barn crew goat home kite love rain soap xray yarn ", evaluator.toString());
}
#Test
public void testsort5() throws FileNotFoundException {
ArrayList<String> words = new ArrayList<>();
Scanner inFile = new Scanner(new File("fourUpper.txt"));
while(inFile.hasNext()) {
words.add(inFile.nextLine());
}
RadixSort evaluator = new RadixSort(words);
evaluator.sort();
assertEquals("atom barn crew goat home kite love rain soap xray yarn ", evaluator.toString());
}
#Test(expected=EmptyCollectionException.class)
public void testsort7() throws FileNotFoundException {
ArrayList<String> words = new ArrayList<>();
Scanner inFile = new Scanner(new File("empty.txt"));
while(inFile.hasNext()) {
words.add(inFile.nextLine());
}
RadixSort evaluator = new RadixSort(words);
evaluator.sort();
fail("Empty list Exception not caught");
}
#Test(expected=InvalidRadixSortException.class)
public void testsort10() throws FileNotFoundException {
ArrayList<String> words = new ArrayList<>();
Scanner inFile = new Scanner(new File("error3.txt"));
while(inFile.hasNext()) {
words.add(inFile.nextLine());
}
RadixSort evaluator = new RadixSort(words);
evaluator.sort();
fail("Invalid Length Exception not caught");
}
}
Finally, this is the exception class that was created so we knew what exception to call
public class InvalidRadixSortException extends RuntimeException
{
/**
* Sets up this exception with an appropriate message.
* #param collection the name of the collection
*/
public InvalidRadixSortException(String error)
{
super("The list of words contained an invalid " + error);
}
}
Use this method to throw exceptions:
private void validateWords() {
int length = string.get(0).length();
for (int j = 0; j < string.size(); j++) {
if (string.get(j).length() != length) {
throw new InvalidRadixSortException("Invalid String Length");
}
if (!string.get(j).matches("[a-zA-Z]+")) {
throw new InvalidRadixSortException("Contains Non-Letters");
}
}
}

How to Store Variable Data back from file in Java

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());
}
}
}

Java read words from file, and ask if it is an anagram

I am trying to create a code in Java, which is going to read two words from anagram.txt file, and see if those two words are anagrams. I am getting an error java.lang.NullPointerException.
I am not sure what am I doing wrong, so any suggestions? I guess that o2.Anagram() needs to have some variables, but I want it to call Strings from txt file... I am a beginner, so don't laugh at me :) Thank you!
This is a class that reads from txt file:
import java.io.File;
import java.util.Scanner;
public class Klasa {
public Scanner x;
String s1;
String s2;
public void openFile(){
try{
x = new Scanner(new File("C:\\anagram.txt"));
}
catch(Exception e){
System.out.println("Error");
}
}
public void readFile(){
while (x.hasNext()){
String s1 = x.next();
String s2 = x.next();
}
}
public void closeFile(){
x.close();
}
}
This is a class that should compare two words from anagram.txt and see if they are anagrams:
import java.util.*;
import java.io.*;
public class isAnagram extends Klasa{
public void Anagram(){
boolean status = true;
if(s1.length() != s2.length()){
status = false;
}
else{
char[] s1Array = s1.toLowerCase().toCharArray();
char[] s2Array = s2.toLowerCase().toCharArray();
Arrays.sort(s1Array);
Arrays.sort(s2Array);
status = Arrays.equals(s1Array, s2Array);
}
//Output
if(status)
{
System.out.println(s1+" and "+s2+" are anagrams");
}
else
{
System.out.println(s1+" and "+s2+" are not anagrams");
}
}
}
And this is main class:
public class mainClass{
public static void main(String[] args){
Klasa o1 = new Klasa();
o1.openFile();
o1.readFile();
o1.closeFile();
isAnagram o2 = new isAnagram();
o2.Anagram();
}
}
Instead of using Scanner for opening a file,you should use FileReader/FileWriter classfor opening and editing the file.Then use Scanner class to read the text from the file.

I'm stuck building a line reader with interfaces in Java

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();
}
}

Categories