Text game assistance - java

this may be a simple fix and a silly question but I am still new to learning java. I am currently working on a code for class that bases on a text game. The code below is what was given to us out of our text book to work on the game. I changed the actual text in the text file mainly and did not do much to the code but I am receiving the following error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at BradySkuza58.getRoom(BradySkuza58.java:143)
at BradySkuza58.loadRoomsFromFile(BradySkuza58.java:90)
at BradySkuza58.main(BradySkuza58.java:39)
This is the code I used for the text game.
import java.util.Scanner;
class Room
{
int roomNumber;
String roomName;
String description;
int numExits;
String[] exits = new String[20];
int[] destinations = new int[20];
}
public class BradySkuza58
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
// initialize rooms from file
Room[] rooms = loadRoomsFromFile("textadventurerooms.txt");
//showAllRooms(rooms); // for debugging
// Okay, so let's play the game!
int currentRoom = 0;
String ans;
while ( currentRoom >= 0 )
{
Room cur = rooms[currentRoom];
System.out.print( cur.description );
System.out.print("> ");
ans = keyboard.nextLine();
// See if what they typed matches any of our exit names
boolean found = false;
for ( int i=0; i<cur.numExits; i++ )
{
if ( cur.exits[i].equals(ans) )
{
found = true;
// if so, change our next room to that exit's room number
currentRoom = cur.destinations[i];
}
}
if ( ! found )
System.out.println("Sorry, I don't understand.");
}
}
public static Room[] loadRoomsFromFile( String filename )
{
Scanner file = null;
try
{
file = new Scanner(new java.io.File(filename));
}
catch ( java.io.IOException e )
{
System.err.println("Sorry, I can't read from the file '" +filename + "'.");
System.exit(1);
}
int numRooms = file.nextInt();
Room[] rooms = new Room[numRooms];
// initialize rooms from file
int roomNum = 0;
while ( file.hasNext() )
{
Room r = getRoom(file);
if ( r.roomNumber != roomNum )
{
System.err.println("Reading room # " + r.roomNumber + ", but" + roomNum + " was expected.");
System.exit(2);
}
rooms[roomNum] = r;
roomNum++;
}
file.close();
return rooms;
}
public static void showAllRooms( Room[] rooms )
{
for ( Room r : rooms )
{
String exitString = "";
for ( int i=0; i<r.numExits; i++ )
exitString += "\t" + r.exits[i] + " (" + r.destinations[i] +")";
System.out.println( r.roomNumber + ") " + r.roomName + "\n" +exitString );
}
}
public static Room getRoom( Scanner f )
{
// any rooms left in the file?
if ( ! f.hasNextInt() )
return null;
Room r = new Room();
String line;
// read in the room # for errorchecking later
r.roomNumber = f.nextInt();
f.nextLine(); // skip "\n" after room #
r.roomName = f.nextLine();
// read in the room's description r.description = "";
while ( true )
{
line = f.nextLine();
if ( line.equals("%%") )
break;
r.description += line + "\n";
}
// finally, we'll read in the exits
int i = 0;
while ( true )
{
line = f.nextLine();
if ( line.equals("%%") )
break;
String[] parts = line.split(":");
r.exits[i] = parts[0];
r.destinations[i] = Integer.parseInt(parts[1]);
i++;
}
r.numExits = i;
// should be done; return the Room
return r;
}
}
line 39
Room[] rooms = loadRoomsFromFile("textadventurerooms.txt");
line 90
Room r = getRoom(file);
line 143
line = f.nextLine();
I did not attach the text file itself but I can if it is needed to find the error.

I'm guessing that your text file does not have as many lines are your program expects (you are trying to call nextLine() after already reaching EOF. Double check that your text file matches what you want. Not having the text file it is tough to give more detail. Based on where it is make sure that you are breaking out of that while loop. You can also check to see if there is another line by calling hasNextLine().

Add a line "%%" to your room definition file. Your parser requires that.

Related

Problem with Abstract ArrayList and counting elements

I want to get a little help with a school assignment. I have a method that isn't acting the way I thought it would. I'm pretty sure the problem is in nlpClassify(), but I'm not entirely sure. Currently, clpClassify() will only print out 0s for the variables. Any suggestions are welcome.
public class TweetHandler implements TweetHandlerInterface {
private Scanner inFile = null;
private String tweet = null;
private String[] temp = null;
private int counter = 0;
List<AbstractTweet> tweetList = new ArrayList<AbstractTweet>();
List<AbstractTweet> dataList = new ArrayList<AbstractTweet>();
List<String[]> dataBaseList = new ArrayList<String[]>();
#Override
public List<AbstractTweet> loadTweetsFromText(String filePath) {
MainApp main = null;
try {
inFile = new Scanner ( new FileReader(filePath));
}
catch( FileNotFoundException er ){
System.err.println(er);
main.printMenu();
}
String line = null;
//String[] data = null;
//int counter = 0;
while ( inFile.hasNextLine() ) {
line = inFile.nextLine();
parseTweetLine(line);
counter++;
}
System.out.println("Reading tweets from file..."
+ "\n" + counter + " tweets read.");
inFile.close();
return tweetList;
}
#Override
public AbstractTweet parseTweetLine(String tweetLine) {
temp = tweetLine.split("\",\"");
tweet = temp[5];
if( temp.length > 6 ){
for( int i = 0; i < temp.length; i++ ){
tweet += " " + temp[i];
}
}
temp[0] = temp[0].replaceAll("\"","");
tweet = tweet.replaceAll("\\p{Punct}", "");
temp[5] = tweet;
int target = Integer.parseInt(temp[0]);
int id = Integer.parseInt(temp[1]);
SimpleDateFormat format = new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy");
Date date = new Date();
try{
date = format.parse(temp[2]);
}
catch( ParseException e ){
System.err.println("Error with date parsing. " + e);
}
String flag = temp[3];
String user = temp[4];
String text = temp[5];
Tweet tweets = new Tweet(target,id,date,flag,user,text);
return tweets;
}
/**
* calls classifyTweet
*/
public void nlpClassify(){ //prints out accuracy
System.out.println("Classifying tweets...");
counter = 0;
int correct = 0,
wrong = 0;
float accuracy = 0.0f;
AbstractTweet tweets;
for( int i = 0; i < tweetList.size(); i++ ){
tweets = tweetList.get(i);
tweets.setPredictedPolarity(classifyTweet(tweets));
int target = tweets.getTarget();
int polarity = tweets.getPredictedPolarity();
System.out.println("Target: " + target );
System.out.println("Prediction: " + polarity );
for( int j = 0; j < 75; j++ ){
System.out.print("=");
}
System.out.println();
if( target == polarity ){
correct++;
}
else{
wrong++;
}
counter++;
accuracy = ( correct / counter ) * 100.0f;
}
System.out.println( "Classified " + counter + " tweets." );
System.out.println( "Correct tweets: " + correct );
System.out.println( "Wrong tweets: " + wrong );
System.out.println( "Accuracy: " + accuracy );
}
#Override
public int classifyTweet(AbstractTweet tweet) {
int calcPolarity = SentimentAnalyzer.getParagraphSentiment( tweet.getText() );
tweet.setPredictedPolarity(calcPolarity);
return calcPolarity;
}
#Override
public void addTweetsToDB(List<AbstractTweet> tweets) {
System.out.println("Adding files to database... ");
int i = 0;
while( i < tweets.size()){
dataList.add(tweets.get(i));
i++;
}
}
#Override
public void deleteTweet(int id) {
int i = 0,
temp = 0;
Tweet obj = null;
while( i < dataList.size() ){
temp = obj.getId();
if( id == temp ){
dataList.remove(i);
--counter;
}
++i;
}
}
#Override
public void saveSerialDB() {
try{
FileOutputStream fileOut = new FileOutputStream("DB.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(dataList);
out.close();
fileOut.close();
}
catch( IOException e ){
e.printStackTrace();
}
}
#Override
public void loadSerialDB() {
try{
FileInputStream fileIn = new FileInputStream("DB.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
dataList = (List<AbstractTweet>)in.readObject();
in.close();
fileIn.close();
}
catch( Exception e ){
e.printStackTrace();
}
}
#Override
public List<AbstractTweet> searchByUser(String user) {
int i = 0;
String temp = null;
Tweet obj = null;
while( i < dataList.size() ){
temp = obj.getUser();
if( user.equals(temp) )
dataList.add(obj);
++i;
}
return dataList;
}
Ignore searchByUser(String user), I know it's wrong and haven't gotten around to fixing it. If you have suggestions for it, that's cool too.
Here is the interface.
public interface TweetHandlerInterface {
/**
* Loads tweets from a CSV text file.
* #param filePath The path to the CSV file.
* #return A list of tweets as objects.
*/
List<AbstractTweet> loadTweetsFromText(String filePath);
/**
* Parses a single line from the CSV file and returns a tweet as an object.
* #param tweetLine A string containing the contents of a single line in the CSV file.
* #return A tweet as an object.
*/
AbstractTweet parseTweetLine(String tweetLine);
/**
* Classifies a tweet as negative, neutral, or positive by using the text of the tweet.
* #param tweet A tweet object.
* #return 0 = negative, 2 = neutral, 4 = positive.
*/
int classifyTweet(AbstractTweet tweet);
/**
* Adds a list of new tweets to the existing database.
* #param tweets A list of tweet objects.
*/
void addTweetsToDB(List<AbstractTweet> tweets);
/**
* It deletes ad tweet from the database, given its id.
* #param id The id value of the tweet.
*/
void deleteTweet(int id);
/**
* Saves the database in the working directory as a serialized object.
*/
void saveSerialDB();
/**
* Loads tweet database.
*/
void loadSerialDB();
/**
* Searches the tweet database by user name. It returns a list of all tweets
* matching the given user name.
* #param user The user name to search for.
* #return A list of tweet objects.
*/
List<AbstractTweet> searchByUser(String user);
/**
* Searches the tweet database for tweets posted on a given date.
* #param date The date to search for.
* #return A list of tweet objects.
*/
List<AbstractTweet> searchByDate(Date date);
/**
* Searches the tweet database for tweets matching a given flag.
* #param flag The flag to search for.
* #return A list of tweet objects.
*/
List<AbstractTweet> searchByFlag(String flag);
/**
* Searches the tweet database for tweets matching a given substring.
* #param substring The substring to search for.
* #return A list of tweet objects.
*/
List<AbstractTweet> searchBySubstring(String substring);
}
Here is my Main().
public class MainApp {
public static void main (String[] args){
TweetHandler handler = new TweetHandler();
MainApp obj = new MainApp();
Tweet tweetObj = null;
String choice;
do{
obj.printMenu();
System.out.print("Enter a choice from above: ");
Scanner inputConsole = new Scanner( System.in );
choice = inputConsole.next();
String filePath = null;
switch( choice ){
case "0":
System.exit(0);
break;
case "1":
Scanner file = new Scanner ( System.in );
System.out.print("Enter the input file path: ");
filePath = file.nextLine();
handler.loadTweetsFromText(filePath);
break;
case "2":
handler.classifyTweet(handler.parseTweetLine(filePath));
handler.nlpClassify();
break;
case "3":
System.out.println("Enter ID of the tweet you wish to change: ");
break;
case "4":
System.out.println("Adding tweets to database...");
handler.addTweetsToDB(handler.loadTweetsFromText(filePath));
break;
case "5":
Scanner removeChoice = new Scanner( System.in );
System.out.println("Enter ID of tweet you wish to delete: ");
int remove = removeChoice.nextInt();
handler.deleteTweet(remove);
break;
case "6":
Scanner searching = new Scanner( System.in );
System.out.println("Search by: 1 User, 2 Date, 3 Flag, 4 Substring.");
int search = searching.nextInt();
switch(search){
case 1:
case 2:
case 3:
case 4:
}
break;
}
} while ( !"0".equals(choice) );
}
void printMenu(){
System.out.println("0. Exit program.\n"
+ "1. Load new tweet text file.\n"
+ "2. Classify tweets using NLP library and report accuracy.\n"
+ "3. Manually change tweet class label.\n"
+ "4. Add new tweets to database.\n"
+ "5. Delete tweet from database (given its id).\n"
+ "6. Search tweets by user, date, flag, or a matching substring.\n");
}
}
You loop for with tweetList.size(). You can print out tweetList.size() to see the value. I guess it's 0. I didn't see any tweetList.add(obj) in your code. So tweetList is empty all the time.

how to link a main class to a jframe form in java using netbeans

Good day!
I have created a code using Netbeans and it executes the processes just fine.
Now, i want my input to given and output to be displayed through a user interface. I have then created a 2 Jframes, 1 to collect the user's input and the other to display the results after execution by the code.
But, i am unable to link the interface to the main class(called NgramBetaE) as i am not aware of how i can do so.
I highly welcome suggestions.
The main class in its entirety is;
package ngrambetae;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
/**
*
* #author 201102144
*/
public class NgramBetaE {
static LinkedList<String> allWords = new LinkedList<String>();
static LinkedList<String> distinctWords = new LinkedList<String>();
static String[] hashmapWord = null;
static int wordCount;
public static HashMap<String,HashMap<String, Integer>> hashmap = new HashMap<>();
public static HashMap<String,HashMap<String, Integer>> bigramMap = new HashMap<>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//prompt user input
Scanner input = new Scanner(System.in);
//read words from collected corpus; a number of .txt files
File directory = new File("Corpus");
File[] listOfFiles = directory.listFiles();//To read from all listed iles in the "directory"
int lineNumber = 0;
String line;
String files;
String delimiters = "[()?!:;,.\\s]+";
//reading from a list of text files
for (File file : listOfFiles) {
if (file.isFile()) {
files = file.getName();
try {
if (files.endsWith(".txt") || files.endsWith(".TXT")) { //ensures a file being read is a text file
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
line = line.toLowerCase();
hashmapWord = line.split(delimiters);
//CALCULATING UNIGRAMS
for(int s = 0; s < hashmapWord.length; s++){
String read = hashmapWord[s];
allWords.add(read);
//count the total number of words in all the text files combined
//TEST
wordCount = 0;
for (int i = 0; i < allWords.size(); i++){
wordCount ++;
}
}
//CALCULATING BIGRAM FREQUENCIES
for(int s = 0; s < hashmapWord.length -1; s++){
String read = hashmapWord[s];
final String read1 = hashmapWord[s + 1];
HashMap<String, Integer> counter = bigramMap.get(read);
if (null == counter) {
counter = new HashMap<String, Integer>();
bigramMap.put(read, counter);
}
Integer count = counter.get(read1);
counter.put(read1, count == null ? 1 : count + 1);
}
//CALCULATING TRIGRAM FREQUENCIES
for(int s = 0; s < hashmapWord.length - 2; s++){
String read = hashmapWord[s];
String read1 = hashmapWord[s + 1];
final String read2 = hashmapWord[s + 2];
String readTrigrams = read + " " + read1;
HashMap<String, Integer> counter = hashmap.get(readTrigrams);
if (null == counter) {
counter = new HashMap<String, Integer>();
hashmap.put(readTrigrams, counter);
}
Integer count = counter.get(read2);
counter.put(read2, count == null ? 1 : count + 1);
}
}
br.close();
}
} catch (NullPointerException | IOException e) {
e.printStackTrace();
System.out.println("Unable to read files: " + e);
}
}
}
//COMPUTING THE TOTAL NUMBER OF WORDS FROM ALL THE TEXT FILES COMBINED
System.out.println("THE TOTAL NUMBER OF WORDS IN COLLECTED CORPUS IS : \t" + wordCount + "\n");
for(int i = 0, size = allWords.size(); i < size; i++){
String distinctWord = allWords.get(i);
//adding a word into the 'distinctWords' list if it doesn't already occur
if(!distinctWords.contains(distinctWord)){
distinctWords.add(distinctWord);
}
}
//PRINTING THE DISTINCT WORDS
System.out.println("THE DISTINCT WORDS IN TOTAL ARE :\t " + distinctWords.size() + "\n");
System.out.println("PRINTING CONTENTS OF THE BIGRAMS HASHMAP... ");
System.out.println(bigramMap);
System.out.println("================================================================================================================================================================================================================================================================================================================\n");
System.out.println("PRINTING CONTENTS OF THE TRIGRAMS HASHMAP... ");
System.out.println(hashmap);
System.out.println("================================================================================================================================================================================================================================================================================================================\n");
//QUITTING APPLICATION
String userInput = null;
while(true) {
System.out.println("\n**********************************************************************************************************************************************************************************************************************************");
System.out.println("\n\n\t\tPLEASE ENTER A WORD OR PHRASE YOU WOULD LIKE A PREDICTION OF THE NEXT WORD FROM:");
System.out.println("\t\t\t\t(OR TYPE IN 'Q' OR 'q' TO QUIT)");
userInput = input.nextLine();
if (userInput.equalsIgnoreCase("Q")) break;
//FORMAT USER INPUT
String[] users = userInput.toLowerCase().split("[?!,.\\s]+");
if (users.length < 2) {
userInput = users[0];
//System.out.println("\nENTRY '" + userInput + "' IS TOO SHORT TO PREDICT NEXT WORD. PLEASE ENTER 2 OR MORE WORDS");
//CALCULATING BIGRAM PROBABILITY
int sum = 0;
try {
for(String s : bigramMap.get(userInput).keySet()) {
sum += bigramMap.get(userInput).get(s);
}
String stringHolder = null;
double numHolder = 0.0;
for(String s : bigramMap.get(userInput).keySet()) {
//System.out.println("TWO");
double x = Math.round(bigramMap.get(userInput).put(s, bigramMap.get(userInput).get(s))/ (double)sum *100 );
if(s != null){
if(numHolder < x ){
stringHolder = s;
numHolder = x;
}
}
}
System.out.println("\nNEXT WORD PREDICTED IS '" + stringHolder + "'");
System.out.println("ITS PROBABILITY OF OCCURRENCE IS " + numHolder + "%");
} catch (Exception NullPointerException) {
System.out.println("\nSORRY. MATCH NOT FOUND.");
}
} else {
userInput = users[users.length - 2] + " " + users[users.length - 1];
// System.out.println("FROM USER WE GET....");
// System.out.println(bigrams.get(userInput).keySet());
/* CALCULATING TRIGRAM PROBABILITY*/
int sum = 0;
try {
for(String s : hashmap.get(userInput).keySet()) {
sum += hashmap.get(userInput).get(s);
}
String stringHolder = null;
double numHolder = 0.0;
for(String s : hashmap.get(userInput).keySet()) {
//System.out.println("TWO");
double x = Math.round(hashmap.get(userInput).put(s, hashmap.get(userInput).get(s))/ (double)sum *100 );
if(s != null){
if(numHolder < x ){
stringHolder = s;
numHolder = x;
}
}
}
System.out.println("\nNEXT WORD PREDICTED IS '" + stringHolder + "'");
System.out.println("ITS PROBABILITY OF OCCURRENCE IS " + numHolder + "%");
} catch (Exception NullPointerException) {
System.out.println("\nSORRY. MATCH NOT FOUND.");
}
}
}
input.close();
}
}
My first Jframe which i would like to appear upon running the project has got a single textbox and a single button;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String usersInput = jTextField1.getText();
Interface1 s = new Interface1();
s.setVisible(true);
dispose();
}
i would like for the user to enter data in the textbox and when they click on the button 'predict next word' then the output from the code execution is displayed on the second jframe which has got 3 labels and relative text areas.
NOTE; i couldn't paste the screenshots but if you run the NgramBetaE class you will get an idea of how the interfaces will be as i tried to explain them.
Thank you
Don't even try to link your GUI code to your NgramBetaE code as you've more work to do since the NgramBetaE is little more than one huge static main method that gets user input from the console with a Scanner and outputs to the console via printlns. Melding these two is like trying to put a square peg into a round hole.
Instead re-write the whole thing with an eye towards object-oriented coding, including creation of an OOP-compliant model class with instance fields and methods, and a single GUI that gets the input and displays it, that holds an instance of the model class and that calls instance methods on this instance.
Consider creating non-GUI classes and methods for --
Reading in data from your text files
Analyzing and hashing the data held in the text files including calculating word frequencies etc...
Returning needed data after analysis in whatever data form it may be needed.
A method for allowing input of a String/phrase for testing, with return its predicted probability
Then create GUI code for:
Getting selected text file from the user. A JFileChooser and supporting code works well here.
Button to start analysis
JTextField to allow entering of phrase
JTextArea or perhaps JTable to display results of analysis
Note that you should avoid having more than one JFrame in your GUI. For more on this, please have a look at The Use of Multiple JFrames, Good/Bad Practice?

Java program to count lines, words, and chars from a text given file

I am practicing to write a program that gets a text file from user and provides data such as characters, words, and lines in the text.
I have searched and looked over the same topic but cannot find a way to make my code run.
public class Document{
private Scanner sc;
// Sets users input to a file name
public Document(String documentName) throws FileNotFoundException {
File inputFile = new File(documentName);
try {
sc = new Scanner(inputFile);
} catch (IOException exception) {
System.out.println("File does not exists");
}
}
public int getChar() {
int Char= 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
Char += line.length() + 1;
}
return Char;
}
// Gets the number of words in a text
public int getWords() {
int Words = 0;
while (sc.hasNext()) {
String line = sc.next();
Words += new StringTokenizer(line, " ,").countTokens();
}
return Words;
}
public int getLines() {
int Lines= 0;
while (sc.hasNextLine()) {
Lines++;
}
return Lines;
}
}
Main method:
public class Main {
public static void main(String[] args) throws FileNotFoundException {
DocStats doc = new DocStats("someText.txt");
// outputs 1451, should be 1450
System.out.println("Number of characters: "
+ doc.getChar());
// outputs 0, should be 257
System.out.println("Number of words: " + doc.getWords());
// outputs 0, should be 49
System.out.println("Number of lines: " + doc.getLines());
}
}
I know exactly why I get 1451 instead of 1451. The reason is because I do not have '\n' at the end of the last sentence but my method adds
numChars += line.length() + 1;
However, I cannot find a solution to why I get 0 for words and lines.
*My texts includes elements as: ? , - '
After all, could anyone help me to make this work?
**So far, I the problem that concerns me is how I can get a number of characters, if the last sentence does not have '\n' element. Is there a chance I could fix that with an if statement?
-Thank you!
After doc.getChar() you have reached the end of file. So there's nothing more to read in this file!
You should reset your scanner in your getChar/Words/Lines methods, such as:
public int getChar() {
sc = new Scanner(inputFile);
...
// solving your problem with the last '\n'
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (sc.hasNextLine())
Char += line.length() + 1;
else
Char += line.length();
}
return char;
}
Please note that a line ending is not always \n! It might also be \r\n (especially under windows)!
public int getWords() {
sc = new Scanner(inputFile);
...
public int getLines() {
sc = new Scanner(inputFile);
...
I would use one sweep to calculate all 3, with different counters. just a loop over each char, check if its a new word etc, increase counts , use Charater.isWhiteSpace *
import java.io.*;
/**Cound lines, characters and words Assumes all non white space are words so even () is a word*/
public class ChrCounts{
String data;
int chrCnt;
int lineCnt;
int wordCnt;
public static void main(String args[]){
ChrCounts c = new ChrCounts();
try{
InputStream data = null;
if(args == null || args.length < 1){
data = new ByteArrayInputStream("quick brown foxes\n\r new toy\'s a fun game.\nblah blah.la la ga-ma".getBytes("utf-8"));
}else{
data = new BufferedInputStream( new FileInputStream(args[0]));
}
c.process(data);
c.print();
}catch(Exception e){
System.out.println("ee " + e);
e.printStackTrace();
}
}
public void print(){
System.out.println("line cnt " + lineCnt + "\nword cnt " + wordCnt + "\n chrs " + chrCnt);
}
public void process(InputStream data) throws Exception{
int chrCnt = 0;
int lineCnt = 0;
int wordCnt = 0;
boolean inWord = false;
boolean inNewline = false;
//char prev = ' ';
while(data.available() > 0){
int j = data.read();
if(j < 0)break;
chrCnt++;
final char c = (char)j;
//prev = c;
if(c == '\n' || c == '\r'){
chrCnt--;//some editors do not count line seperators as new lines
inWord = false;
if(!inNewline){
inNewline = true;
lineCnt++;
}else{
//chrCnt--;//some editors dont count adjaccent line seps as characters
}
}else{
inNewline = false;
if(Character.isWhitespace(c)){
inWord = false;
}else{
if(!inWord){
inWord = true;
wordCnt++;
}
}
}
}
//we had some data and last char was not in new line, count last line
if(chrCnt > 0 && !inNewline){
lineCnt++;
}
this.chrCnt = chrCnt;
this.lineCnt = lineCnt;
this.wordCnt = wordCnt;
}
}

Exception in thread "main" java.lang.NullPointerException when trying to update file

I'm in a beginner CS class and I'm trying to update info in a file. The info in the array does get replaced temporarily; however, I am unable to save the changes to the file. And, even after it's replaced, I get the "null" error.
Here is my code, I have omitted the lines and methods that are unrelated:
public static void readData(){
// Variables
int choice2, location;
// Read file
File dataFile = new File("C:/Users/shirley/Documents/cddata.txt");
FileReader in;
BufferedReader readFile;
// Arrays
String[] code = new String[100];
String[] type = new String[100];
String[] artist = new String[100];
String[] song = new String[100];
Double[] price = new Double[100];
Double[] vSales = new Double[100];
// Split Variables
String tempCode, tempType, tempArtist, tempSong, tempPrice, tempVsales;
// Split
String text;
int c = 0;
try{
in = new FileReader(dataFile);
readFile = new BufferedReader(in);
while ((text = readFile.readLine()) != null){
// Split line into temp variables
tempCode = text.substring(0,5);
tempType = text.substring(5,15);
tempArtist = text.substring(16,30);
tempSong = text.substring(30,46);
tempPrice = text.substring(46,52);
tempVsales = text.substring(52);
// Place text in correct arrays
code[c] = tempCode;
type[c] = tempType;
artist[c] = tempArtist;
song[c] = tempSong;
price[c] = Double.parseDouble(tempPrice);
vSales[c] = Double.parseDouble(tempVsales);
c += 1; // increase counter
}
// Output to user
Scanner kb = new Scanner(System.in);
System.out.print("\nSelect another number: ");
choice2 = kb.nextInt();
// Reads data
if (choice2 == 5){
reqStatsSort(code,type,artist,song,price,vSales,c);
location = reqStatistics(code,type,artist,song,price,vSales,c);
if (location == -1){
System.out.println("Sorry, code not found.");
}
else{
System.out.print("Enter new volume sales: ");
vSales[location] = kb.nextDouble();
}
displayBestSellerArray(type,artist,song,vSales,c);
readFile.close();
in.close();
changeVolume(code,type,artist,song,price,vSales,c); // Method to rewrite file
readData();
}
}catch(FileNotFoundException e){
System.out.println("File does not exist or could not be found.");
System.err.println("FileNotFoundException: " + e.getMessage());
}catch(IOException e){
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
///////////////// REQ STATS SORT METHOD ////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
public static void reqStatsSort(String[] sortCode, String[] sortType, String[] sortArtist,
String[] sortSong, Double[] sortPrice, Double[] sortVSales, int c){
// Variables
String tempCode, tempArtist, tempType, tempSong;
double tempVsales, tempPrice;
for(int j = 0; j < (c - 1); j++){
for (int k = j + 1; k < c; k++){
if ((sortCode[k]).compareToIgnoreCase(sortCode[j]) < 0){
// Switch CODE
tempCode = sortCode[k];
sortCode[k] = sortCode[j];
sortCode[j] = tempCode;
// Switch TYPE
tempType = sortType[k];
sortType[k] = sortType[j];
sortType[j] = tempType;
// Switch ARTIST
tempArtist = sortArtist[k];
sortArtist[k] = sortArtist[j];
sortArtist[j] = tempArtist;
// Switch SONG
tempSong = sortSong[k];
sortSong[k] = sortSong[j];
sortSong[j] = tempSong;
// Switch VOLUME
tempVsales = sortVSales[k];
sortVSales[k] = sortVSales[j];
sortVSales[j] = tempVsales;
// Switch PRICE
tempPrice = sortPrice[k];
sortPrice[k] = sortPrice[j];
sortPrice[j] = tempPrice;
}
}
}
}
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/////////////// REQUEST STATISTICS METHOD //////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
public static int reqStatistics(String[] statsCode, String[] statsType,
String[] statsArtist, String[] statsSong, Double[] statsPrice,
Double[] statsVSales, int c){
// Variables
String cdCode;
// Obtain input from user
Scanner kb = new Scanner(System.in);
System.out.print("Enter a CD code: ");
cdCode = kb.nextLine();
// Binary search
int position;
int lowerbound = 0;
int upperbound = c - 1;
// Find middle position
position = (lowerbound + upperbound) / 2;
while((statsCode[position].compareToIgnoreCase(cdCode) != 0) && (lowerbound <= upperbound)){
if((statsCode[position].compareToIgnoreCase(cdCode) > 0)){
upperbound = position - 1;
}
else {
lowerbound = position + 1;
}
position = (lowerbound + upperbound) / 2;
}
if (lowerbound <= upperbound){
return(position);
}
else {
return (-1);
}
}
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/////////////// BEST SELLER ARRAY METHOD //////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
public static void displayBestSellerArray (String[] displaySortedType,
String[] displaySortedArtist, String[] displaySortedSong,
Double[] displaySortedVSales, int c){
// Output to user
System.out.println();
System.out.println("MUSIC ARTIST HIT SONG VOLUME");
System.out.println("TYPE SALES");
System.out.println("--------------------------------------------------------------------");
for (int i = 0; i < c; i++){
System.out.print(displaySortedType[i] + " " + displaySortedArtist[i] + " "
+ displaySortedSong[i] + " ");
System.out.format("%6.0f",displaySortedVSales[i]);
System.out.println();
}
}
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////// CHANGE VOLUME METHOD ////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
public static void changeVolume(String[] writeCode, String[] writeType,
String[] writeArtist, String[] writeSong, Double[] writePrice,
Double[] writeVSales, int c){
File textFile = new File("C:/Users/shirley/Documents/cddata.txt");
FileWriter out;
BufferedWriter writeFile;
// Variables
String entireRecord, tempVSales;
int decLoc;
try{
out = new FileWriter(textFile);
writeFile = new BufferedWriter(out);
// Output to user
for (int i = 1; i <= c; i++){
// Convert volume sales to String
tempVSales = Double.toString(writeVSales[i]);
// Get rid of decimals
decLoc = (tempVSales.indexOf("."));
tempVSales = tempVSales.substring(0,decLoc);
// Create record line
entireRecord = writeCode[i] + " " + writeType[i] + " " + writeArtist[i]
+ " " + writeSong[i] + " " + writePrice[i] + " " + tempVSales;
// Write record to file
writeFile.write(entireRecord);
if (i != c){
writeFile.newLine();
}
}
writeFile.close();
out.close();
System.out.println("Data written to file.");
}
catch(IOException e){
System.out.println("Problem writing to file.");
System.out.println("IOException: " + e.getMessage());
}
}
The last method, changeVolume(), is what isn't working. The error I get is
Exception in thread "main" java.lang.NullPointerException
at culminating3.Culminating3.changeVolume(Culminating3.java:508)
at culminating3.Culminating3.readData(Culminating3.java:185)
at culminating3.Culminating3.readData(Culminating3.java:167)
at culminating3.Culminating3.main(Culminating3.java:47)
Java Result: 1
Line 508 is:
tempVSales = Double.toString(writeVSales[i]);
in the changeVolume method().
So my program asks the user for a CD code to change the volume of sales, and sorts the arrays to perform a binary search if the inputted code exists. If it does, my program replaces the old volume of sales (which it does), and saves it with the changeVolume() method (which it doesn't do and gives me the error).
Please keep in mind I'm a newbie. It looks fine to me but I can't figure out why it's not working. I apologize for any messes in the code. writeVSales[] shouldn't be null because I assigned input in the readData() method?
Problem is here:
// Convert volume sales to String
tempVSales = Double.toString(writeVSales[i]);
// Get rid of decimals
decLoc = (tempVSales.indexOf("."));
tempVSales = tempVSales.substring(0,decLoc);
I suggest you to take some sample values and work on this first.
You can use StringTokenizer to perform this.
When you input the information into the writeVSales array you start at 0 (good) and increment c everytime a new item is added, whether or not there is a new item to add or not (again this is fine).
int c = 0;
try{
in = new FileReader(dataFile);
readFile = new BufferedReader(in);
while ((text = readFile.readLine()) != null){
// Split line into temp variables
tempCode = text.substring(0,5);
tempType = text.substring(5,15);
tempArtist = text.substring(16,30);
tempSong = text.substring(30,46);
tempPrice = text.substring(46,52);
tempVsales = text.substring(52);
// Place text in correct arrays
code[c] = tempCode;
type[c] = tempType;
artist[c] = tempArtist;
song[c] = tempSong;
price[c] = Double.parseDouble(tempPrice);
vSales[c] = Double.parseDouble(tempVsales);
c += 1; // increase counter
}
Later in changeVolume() your for loop starts at 1 and goes to c. So you are missing the first element and trying to add an element from an index that is null, hence the `NullPointerexception.
// Output to user
for (int i = 1; i <= c; i++){
//code
}
Change the for loop to start and 0 and go to i < c (i.e. c - 1):
for (int i = 0; i < c; i++){
// Convert volume sales to String
tempVSales = Double.toString(writeVSales[i]);
// Get rid of decimals
decLoc = (tempVSales.indexOf("."));
tempVSales = tempVSales.substring(0,decLoc);
// Create record line
entireRecord = writeCode[i] + " " + writeType[i] + " " + writeArtist[i]
+ " " + writeSong[i] + " " + writePrice[i] + " " + tempVSales;
// Write record to file
writeFile.write(entireRecord);
if (i != c){
writeFile.newLine();
}
}

End of file detected on input -- Help please [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I tried submitting this and an error pops up saying ** END OF FILE detected on input -- EXIT **.
I cant figure out what this means, just to be clear I am trying to set up a system so that data is input on a loop unless the value is 0. Thanks.
This is my code:
class Main
{
public static void main( String args[] )
{
int SN = 1;
while ( SN != 0)
{
System.out.print("#SN : " );
SN = BIO.getInt();
System.out.print("#CW : " );
int CW = BIO.getInt();
System.out.print("#EX : " );
int EX = BIO.getInt();
double Mark = CW + EX;
System.out.printf("SN= " + SN + "EX= " + EX + "CW= " + CW + "Mark= " + "%6.1f", (double) Mark / 2 );
}
}
}
This is the BIO code:
class BIO
{
private static final int EOF = -1;
private static final int NONE = -2;
private static int nextChar = NONE;
private static boolean EOFdetected = false;
public static String getLineBASE()
{
String line = ""; // Line read
int ch; // Read ch
try
{
ch = System.in.read(); // No next char
if ( ch == EOF )
{
System.out.println("**** END OF FILE " +
"detected on input -- EXIT ****" );
System.exit(-1);
}
while( ch != '\n' ) // Read loop
{
if ( ch == EOF )
{
EOFdetected = true;
return line; // exit
}
line = line + (char) ch; // form line
ch = System.in.read(); // next ch
}
return line; // return line
}
catch( IOException exp ) // Problem
{
System.exit(-1); // Exit **
}
return ""; // Blank line
}
public static String getLine()
{
String line = getLineBASE(); // Read line
//System.out.println( line );
return line;
}
public static String getString()
{
String line = getLine(); // Read line
return line.trim();
}
public static double getDouble()
{
String res = getLine(); // Read line
double value = 0.0; //
try
{
value = Double.parseDouble( res.trim() ); // Convert
}
catch ( NumberFormatException ex ) // Problem
{ // ignore
}
return value; // return
}
public static int getInt()
{
String res = getLine(); // Read line
int value = 0; //
try
{
value = Integer.parseInt( res.trim() ); // Convert
}
catch ( NumberFormatException ex ) // Problem
{ // ignore
}
return value; // return
}
}
try
{
ch = System.in.read(); //reads from keyboard.
if ( ch == EOF )
{
System.out.println("**** END OF FILE " +
"detected on input -- EXIT ****" );
System.exit(-1);
}
}
This snippet reads in input from the keyboard. If you want to read stuff from a file (Which I assume you are, since there is an EOF) look up the Scanner class. If this is not what you wanted, my apologies, I am only making assumptions.

Categories