Java-Read Text Files And Store Them As Arrays - java

I have the following piece of code. I do not understand why its not working.
I'd really appreciate help on this.
import java.util.Scanner;
import java.io.*;
class ReadFiles {
String [] codes = new String[99];
int i = 0;
private Scanner readCodes;
public void openCodesFile() {
try {
readCodes = new Scanner(new File("C:/Users/Carlo/Desktop/Files/codes.txt"));
} catch (Exception e) {
System.out.println("Could not locate the data file!");
}
}
public void readCodesFile() {
while(readCodes.hasNext()) {
codes[i] = readCodes.nextLine();
i++;
System.out.println(codes[i]);
}
}
public void closeCodesFile() {
readCodes.close();
}
}
class NewHardware {
public static void main(String[] args) {
ReadFiles codesRead = new ReadFiles();
codesRead.openCodesFile();
codesRead.readCodesFile();
codesRead.closeCodesFile();
}
}
The output prints out "null" a bunch of times.
Also, I want to be able to not only print out the codes but use the codes array in the class NewHardware and manipulate it (print it out, truncate it, etc).
I was thinking of doing the following with readCodesFile():
public String readCodesFile() {
while(readCodes.hasNext()) {
codes[i] = readCodes.nextLine();
i++;
System.out.println(codes[i]);
}
return (codes[i]);
}
Or something but it hasn't worked just yet. Am I on the right track?
Oh, just wanted to add that the text contains the following:
G22
K13
S21
I30
H15
N23
L33
E19
U49
EDIT:
Thanks to Tony and Churk below to help me with my idiocy. I am accepting Tony's answer basically because he challenged me to think but Churk's answer is just as valuable.
For the second part of my question (where I asked about being able to use it in class NewHardware), I did the following:
class NewHardware {
public static void main(String[] args) {
ReadFiles codesRead = new ReadFiles();
codesRead.openCodesFile();
codesRead.readCodesFile();
for (int i = 0; i < 9; i++) {
System.out.println("\n\n" + codesRead.codes[i]);
}
codesRead.closeCodesFile();
}
}
This is of course not the final program code but this has helped me get the basic idea. Hope this helps others too.

codes[i] = readCodes.nextLine();
i++;
System.out.println(codes[i]);
You are printing codes[i++]

Look carefully at your readCodesFile() method. Look at every line. What is it doing? Can you explain it to us?

Related

Anonymous inner class example validity concern

I was trying to review some of the Java language using a spark chart I had once bought. Regarding the use of anonymous inner classes they give this example :
Dice rollDice() {
return new Dice() {
int number = (int)( Math.random() * 6 ) + 1;
};
}
Problem is, I do not see how this would work, and can not get the compiler to accept it as a method within another class. The compiler complains about each reference to Dice "symbol can not be found."
Am I not understanding their example correctly or is this completely invalid code? Thanks in advance!
p.s. if this is working code, could someone provide me with an example of how it can be used?
Edit: I have found something that finally makes sense
The syntax for an anonymous inner class is shown below
new SuperClassName/InterfaceName() {
// Implement or override methods in superclass or interface
// Other methods if necessary
}
This above code is passed to a method that takes an instance of Superclass or completely implements the Interface. For instance, a method that has an EventHandlerparameter and we have not already defined a class that implements the handle(ActionEvent e) method.
enlargeButton.setOnAction(
new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
circlePane.enlarge();
}
});
In this way, it will truly be anonymous. I think the example given in Java's own tutorial to be very poor.
It looks like you've mostly answered your own question and you will probably want to go through some full tutorial or documentation to understand things fully, but here are some answers to your immediate questions.
Your first sample code wont compile until you have a Dice class or interface you can extend. So as an example you can get this code to compile:
class Dicey {
interface Dice {
}
Dice rollDice() {
return new Dice() {
int number = (int) (Math.random() * 6) + 1;
};
}
public static void main(String... none) {
Dice dice = new Dicey().rollDice();
// dice.number; <-- not available
}
}
Now you can do this, but as you suspect this is not a very useful things to do (for a few reasons) but the biggest problem is that after you create this anonymous instance there isn't really a way to get to the .number member.
More usually you would have an anonymous subclass implement some methods on the interface, so that you can actually do something with it. So for example
class HelloAnonymous {
interface Hello {
String say();
}
Hello hello(String world) {
return new Hello() {
public String say() {
return world;
}
};
}
public static void main(String... none) {
System.out.println(new HelloAnonymous().hello("world").say());
// prints 'world'
}
}
gives you a way of making fantastically useful Hello objects that can say something. Having said all this, writing anonymous inner classes is fairly old school because functional interfaces now largely replace the need for them. So in this example you could have:
class HelloAnonymous {
#FunctionalInterface
interface Hello {
String say();
}
// old school
Hello hello(String world) {
return new Hello() {
public String say() {
return world;
}
};
}
// with lambda notation
Hello alsoHello(String world) {
return () -> {
return world;
};
}
public static void main(String... none) {
System.out.println(new HelloAnonymous().hello("world").say());
System.out.println(new HelloAnonymous().alsoHello("world").say());
}
}
since I don't know about 'Dice' class I cannot write same method but I try some thing similar to that. It compile and work can access 'number' variable by using reflection. My opinion is it is not very useful. Following is my code:
public class TestClass {
public static void main(String a[]){
TestClass aClass = rollDice();
try {
System.out.println("value of number : " + aClass.getClass().getDeclaredField("number").getInt(aClass));
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
static TestClass rollDice() {
return new TestClass() {
int number = (int) (Math.random() * 6) + 1;
};
}
}
That example is extremely broken. Throw that source away. Try this:
import java.util.Random;
public class DieFactory {
interface Die { int roll(); }
static Die create(long seed) {
Random random = new Random(seed);
return new Die() {
#Override
public int roll() {
return random.nextInt(6) + 1;
}
};
}
// Now you can roll 2 dice pretty easily.
public static void main(String [] args) {
DieFactory.Die die1 = DieFactory.create(42);
DieFactory.Die die2 = DieFactory.create(24);
for (int i = 0; i < 40; i++) {
System.out.println(die1.roll() + die2.roll());
}
}
}
Incidentally, the word "dice" is plural for the singular "die."

ArrayChecker failure?

I have a problem with the following code:
Import java.util.ArrayList;
public class Car {
private String car;
private Car genCar = new Car();
ArrayList<String> allCars = new ArrayList<>();
public void setCar() {
genCar.setModel();
genCar.setCreator();
car = genCar.getModel() + "made by" + genCar.getCreator();
}
public void checkDouble() {
for (String search : allCars) {
while (search.equals(car)) {
setCar();
}
}
allCars.add(car);
}
public void repeater(){
for(int i = 0; i<52; i++){
setCar();
checkDouble();
}
}
}
Whenever I try to check for duplicates (which this code does) my program still puts the duplicate in the array when I actually try to avoid it this way.
Any solution so this works?
You do this:
public void checkDouble()
{
for (String search : allCars)
{
while (search.equals(car))
{
setCar();
}
}
allCars.add(car);
}
The problem with this is that, once you found a double, you generate a new car using setCar(), but you do not search the entire list again.
Do something like:
public void avoidDoubles()
{
while allCars.contains(car)
{
setCar(); // generate new, different car
}
allCars.add(car);
}
FWIW, you might want to change the name of some of the functions. I would call setCar() generateNewCar() or newCar().
I'm not sure what you're trying to do, but in checkDouble you are finding a duplicate and then adding it to the list.
If I understand you correctly, you don't need the loops, All you need to do is to use ArrayList.contains()
if(allCars.contains(someString))
{
System.err.println("Duplicate...");
} else
{
//setCar, addCar, etc.
}

how to properly process numeric input from files?

I'm trying to process a file with a variety of strings. Ultimately I'm interested in the numbers contained in the file, and want to disregard everything else. Some of the numbers will have "$" in front of them. I still want to include these numbers, but am not sure of the optimal way to do it.
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("asdf.txt"));
while (input.hasNext()) {
if (input.hasNextInt()) {
process(input.nextInt());
} else {
processString(input.next());
}
}
}
public static void processString(String phrase) {
if (phrase.startsWith("$")) {
phrase = phrase.substring(1);
try {
int number = Integer.parseInt(phrase);
process(number);
} catch (NumberFormatException e) {
}
}
}
public static void process(int number) {
// ... foo ...
}
This a simplified version of what I have, and my full version works. I want to avoid using try/catch statement inside of processString and was wondering if there was a more elegant way of accomplishing this.

Call data from a string array to another class

public class QuestionBank {
public static void main(String[] args) {
int k = 0;
String Bank[][] = {{"The sun is hot.","A. True","B. Flase","A"},
{"Cats can fly.","A. True","B. False","B"}};
}
}
Above is my QuestionBank class that creates a 2X4 string array. First column being the question, 2nd and 3rd being the answer choices, and 4th being the correct answer.
Below is my RealDeal class.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class RealDeal {
public static void main(String[] args) {
input = JOptionPane.showInputDialog(Bank[0][0]\nBank[0][1]\nBank[0][2]);
if (input == Bank[0][3]) {
input = 10;
} else {
input = 0;
}
total = input/1;
JOptionPane.showMessageDialog(null,"You scored a " + total + " out of 10. Great job!");
System.exit(0);
}
}
What I'm trying to do is to get Bank[0][0], Bank[0][1], and Bank[0][2] to output on my RealDeal class and then to check whether Bank[0][3] matches with the users input. Can anyone please help me with this. Im really new to java so if anyone could actually draw out the answer and explain it to me that would be great.
I think the best way is reading a good Java book and become familiar with the language itself and then try to solve this by your own. If you then have a real question there is no problem asking it here again. But your code is... not really working at all.
I don't think this portal is a "please do my work for me" portal.
To call anything from another class you will need to either setup a method for a return or make the variables public.
So:
public class Class1
{
// for method 1
public String s1 = "This is a string"
// for method 2
public Class1 {}
public returnString()
{
return s1;
}
}
public class CLASS2
{
public static void main(String args[])
{
// get the class
cls1 = new Class1();
// retrieving - method 1
String str = cls1.s1;
// retrieving - method2
str = cls1.returnString();
}
}

Java method parameter for creating new object of different class

I have searched high and low for a solution to this problem, and finally signed up here to see if someone can point me to what is undoubtedly a really simple solution that is evading me. I'm working on MIT's OpenCourse to teach myself Java and am stumped on this problem.
I have two classes, Library and Book. The program keeps track of books created for each library, their location, and whether or not they are checked out. I am given the main method for Library that cannot be edited. Instead its methods must be built to produce the desired output. The issue I am having is determining the argument syntax to pass to a method in Library that creates a new Book in the main method of Library.
Relevant Library Code:
package mitPractice;
public class Library {
String library_address;
static String library_hours = "Libraries are open daily from 9AM to 5PM";
Book[] catalog;
//List of Methods for Libraries
public Library(String address) {
library_address = address;
}
public static void printOpeningHours() {
System.out.println(library_hours);
}
public void addBook(/*unsure what parameter to add here*/) {
catalog[ (catalog.length + 1)] = //unknown parameter
}
public static void main(String[] args) {
//Create two libraries
Library firstLibrary = new Library("10 Main St.");
Library secondLibrary = new Library("228 Liberty St.");
//Add four books ***This block of code is the problem and is uneditable
firstLibrary.addBook(new Book("A Game of Thrones"));
firstLibrary.addBook(new Book("Rama"));
firstLibrary.addBook(new Book("Understanding Space"));
firstLibrary.addBook(new Book("Way of the Clans"));
So my question is how to make the method compatible with the code given in the main method? I have attempted numerous combinations for arguments to pass to addBook() and none seem to deliver.
Book code:
package mitPractice;
public class Book {
Boolean isCheckedOut = false;
String book_title;
public Book(String title) {
book_title = title;
}
public void Borrow() {
isCheckedOut = true;
}
public void Return() {
isCheckedOut = false;
}
public boolean isBorrowed() {
if (isCheckedOut == true) {
return true;
} else {
return false;
}
}
public String getTitle() {
return book_title;
}
/*public static void main(String[] args) {
Book example = new Book("A Game of Thrones");
System.out.println("Title: " + example.getTitle());
System.out.println("Borrowed?: " + example.isBorrowed());
example.Borrow();
System.out.println("Borrowed?: " + example.isBorrowed());
example.Return();
System.out.println("Borrowed?: " + example.isBorrowed());
}*/
}
You want the parameter to be of type Book:
public void addBook(Book newBook) {
catalog[(catalog.length + 1)] = newBook;
}
This will throw an ArrayIndexOutOfBoundsException though, because you're trying to put an element in the array after the last index. You'll need to keep track of how many books have been added and rebuild your array when it gets full. Like this:
private int numberOfBooks = 0;
public void addBook(Book newBook) {
numberOfBooks++;
if(numberOfBooks >= catalog.length) {
// Rebuild array
Book[] copy = new Book[catalog.length * 2]
for(int i=0; i<catalog.length; i++){
copy[i] = catalog[i];
}
catalog = copy;
}
catalog[numberOfBooks] = newBook;
}
Or use a collection like java.util.ArrayList.
So instead of having this line:
Book[] catalog;
You might have
ArrayList<Book> catalog = new ArrayList<Book>();
This creates an ArrayList which is a Java implementation of a dynamically sized array.
Then your addBook method might look like this:
public void addBook(Book newBook) {
catalog.add(newBook);
}
In order to use ArrayList you'll need to include this line at the beginning of the file, after the package mitPractice; line:
import java.util.ArrayList;
This always ends in array out of bounds :
public void addBook(/*unsure what parameter to add here*/) {
catalog[ (catalog.length + 1)] = //unknown parameter
}
Actually, the best would be to use List :
public class Library {
List<Book> catalog = new ArrayList<>();
...
}
Then you can simply do this :
public void addBook(Book book) {
catalog.add(book);
}
Try this code. This will add a book to a very important data structure called an ArrayList found in the util package in java. A programmer has to import this before the class statement but after any package statement. The code also uses a method from your Book API to print the title when a book is successfully added to the ArrayList. ArrayLists are favourable over Arrays because an java.util.ArrayList can expand without problems whereas an Array is a fixed size and is not so dynamic.
Check out this code I modified of the Library class that compiles and runs.
package mitPractice;
import java.util.ArrayList;
public class Library {
String library_address;
static String library_hours = "Libraries are open daily from 9AM to 5PM";
ArrayList<Book> books = new ArrayList<Book>();
//List of Methods for Libraries
public Library(String address) {
library_address = address;
}
public static void printOpeningHours() {
System.out.println(library_hours);
}
public void addBook(Book b/*unsure what parameter to add here*/) {
books.add(b); // add the book to the ArrayList
System.out.println("The book: " + b.getTitle() + " was successfully added.");
}
public static void main(String[] args) {
//Create two libraries
Library firstLibrary = new Library("10 Main St.");
Library secondLibrary = new Library("228 Liberty St.");
//Add four books ***This block of code is the problem and is uneditable
firstLibrary.addBook(new Book("A Game of Drones"));
firstLibrary.addBook(new Book("Raman Noodles"));
firstLibrary.addBook(new Book("Understanding Space"));
firstLibrary.addBook(new Book("Way of the Yoga Baywatch Babes"));
} // end main
} // end Library class
I hope this helps some.
All the best,
user_loser

Categories