I'm a college student and this code is for a project in my intro to Java course. I've worked with it over and over again, searched for answers both on stackoverflow and others websites, but I still can't figure out what the problem is. The program is meant to store Clients by prompting for a First and Last name, and a email address. The client will be given a Client ID, and they can use that to either book a storage unit, or display a booked storage unit. When I run the program I get this exception:
Exception in thread "main" java.lang.NullPointerException
at Webstore3.WebStorage.Sub_Menu(WebStorage.java:153)
at Webstore3.WebStorage.main(WebStorage.java:85)
I've seen the questions and answers on stackoverflow regarding NullPointerExceptions, and I've done test code to make sure there is something in both input and customer[i].Client_ID, but I've yet to realize what the problem is. I know that the code isn't perfect, but any and all help in getting past this first error would be greatly appreciated.
package Webstore3;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
import java.lang.StringBuilder;
public class WebStorage
{
static int c = 0;
static int b = 0;
static int s = 0;
static WebStorage temp_w = new WebStorage();
static Customer temp_c;
static Booking temp_b;
static Storage temp_s;
static int i = 0;
static int j = 0;
static int k = 0;
static int Confirm;
static int Choose;
static String input = new String("");
static int temp = 0;
static String temp_string = "";
static String temp_string2 = "";
static Random r = new Random();
static Customer[] customer = new Customer[100];
static Booking[] booking = new Booking[14];
static Storage[] storage = new Storage[14];
//static ArrayList<Customer> customer2 = new ArrayList<Customer>();
//static ArrayList<Customer> booking2 = new ArrayList<Customer>();
//static ArrayList<Customer> storage2 = new ArrayList<Customer>();
static int w = 0;
static int l = 0;
public static void main(String[] args)
{
Confirm = JOptionPane.showConfirmDialog(null, "Would you like to Access ~WebStorage~?");
if(Confirm == 0)
{
while(temp != 3)
{
temp = MainMenu();
if(temp == 1)
{
temp_c = new Customer();
temp_c.First_Name();
temp_c.Last_Name();
temp_c.Email();
temp_string = temp_c.Account_Created();
customer[c] = temp_c;
if(Confirm == 0 )
{
c++;
input = JOptionPane.showInputDialog("What would you like to do now?" + "\n" + "\n" + "Book Unit - (1)" + "\n" + "Main Menu - (2)");
Choose = Integer.parseInt(input);
if(Choose == 1)
{
input = JOptionPane.showInputDialog("Enter unit width: ");
w = Integer.parseInt(input);
input = JOptionPane.showInputDialog("Enter unit length: ");
l = Integer.parseInt(input);
temp_s = new Storage();
temp_string2 = temp_s.Storage(w, l);
storage[s] = temp_s;
if(temp_string2 != "")
{
temp_b = new Booking();
temp_b.Storage_ID = temp_string2;
temp_b.Client_ID = temp_string;
booking[b] = temp_b;
b++;
}
}
}
}
if(temp == 2)
{
Sub_Menu();
}
if(temp == 3)
{
JOptionPane.showMessageDialog(null, "Goodbye");
System.exit(0);
}
}
}
if(Confirm == 1)
{
System.out.println("Goodbye");
System.exit(0);
}
}
public static int MainMenu()
{
input = JOptionPane.showInputDialog("Please enter the number correspoding to your desired action: " + "\n" + "\n" + "Create an Account - (1)" + "\n" + "Booking - (2)" + "\n" + "Quit Program - (3)" +"\n");
temp = Integer.parseInt(input);
return temp;
}
public static void Sub_Menu()
{
input = JOptionPane.showInputDialog("Please enter the number correspoding to your desired action: " + "\n" + "\n" + "Book Storage - (1)" + "\n" + "Search Booking - (2)" + "\n" + "Display all Booking - (3)" +"\n" + "Main Menu - (4)");
Choose = Integer.parseInt(input);
if(Choose == 1)
{
input = JOptionPane.showInputDialog("Enter your Client ID: ");
temp_string = input;
for(i = 0; i < customer.length; i++)
{
if(input == customer[i].Client_ID)
{
input = JOptionPane.showInputDialog("Enter unit width: ");
w = Integer.parseInt(input);
input = JOptionPane.showInputDialog("Enter unit length: ");
l = Integer.parseInt(input);
temp_s = new Storage();
temp_string2 = temp_s.Storage(w, l);
storage[s] = temp_s;
if(temp_string2 != "")
{
temp_b = new Booking();
temp_b.Storage_ID = temp_string2;
temp_b.Client_ID = temp_string;
booking[b] = temp_b;
b++;
}
}
}
JOptionPane.showMessageDialog(null, "Client ID not found!" + "\n" + "\n" + "Press ok, to return to the main menu and create an account");
}
if(Choose == 2)
{
input = JOptionPane.showInputDialog("Enter your Client ID: ");
for(i = 0; i < customer.length; i++)
{
if(input == customer[i].Client_ID)
{
input = JOptionPane.showInputDialog("Enter your Storage ID: ");
for(i = 0; i < storage.length; i++)
{
if(input == storage[i].Storage_ID)
{
JOptionPane.showMessageDialog(null, "size: " + storage[i].sb2 + "\n" + "Rental: " + storage[i].price_h + "\n" + "Storage ID: " + storage[i].sb + "\n" + "\n" + "Press ok, to return to the Main menu");
}
}
}
}
}
if(Choose == 3)
{
input = JOptionPane.showInputDialog("Enter you Client ID: ");
for(i = 0; i < customer.length; i++)
{
if(input == customer[i].Client_ID)
{
for(j = 0; j < booking.length; j++)
{
if(input == booking[j].Client_ID)
{
for(k = 0; k < storage.length; k++)
{
if(booking[j].Storage_ID == storage[k].Storage_ID)
{
JOptionPane.showMessageDialog(null, "First Name: " + customer[i].Client_FirstName + "\n" + "Last Name: " + customer[i].Client_LastName + "\n"+ "Email: " + customer[i].Client_Email + "\n" + "size: " + storage[k].sb2 + "\n" + "Rental: " + storage[k].price_h + "\n" + "Storage ID: " + storage[k].sb + "\n" + "\n");
}
}
}
}
}
}
}
if(Choose == 4)
{
}
}
}
class Customer extends WebStorage
{
static String input = new String("");
static boolean error;
static int Confirm = 0;
static int Valid_Email = 0;
static int Valid_ID = 0;
String Client_FirstName = "";
String Client_LastName = "";
String Client_Number = "";
String Client_Email = "";
static int[] temp_array = new int[9];
static int[] Client_ID_Array = new int[9];
String Client_ID = "";
StringBuilder sb;
Customer()
{
Client_FirstName = new String("");
Client_LastName = new String("");
Client_Number = new String("");
Client_Email = new String("");
Client_ID = new String("");
sb = new StringBuilder("");
}
Customer(String Client_FirstName, String Client_LastName, String Client_Number, String Client_Email, String Client_ID, StringBuilder sb)
{
this.Client_FirstName = Client_FirstName;
this.Client_LastName = Client_LastName;
this.Client_Number = Client_Number;
this.Client_Email = Client_Email;
this.Client_ID = Client_ID;
this.sb = sb;
}
public void First_Name()
{
input = JOptionPane.showInputDialog("Enter your Information to create an account: " + "\n" + "\n" + "First Name: ");
for(int i = 0; i < input.length(); i++)
{
error = Character.isLetter(input.charAt(i));
if(error == false)
{
input = JOptionPane.showInputDialog("Your name may only contain letters" + "\n" + "\n" + "First Name: ");
error = Character.isLetter(input.charAt(i));
i = -1;
}
}
Client_FirstName = input;
}
public void Last_Name ()
{
input = JOptionPane.showInputDialog("Enter your Information to create an account: " + "\n" + "\n" + "Last Name: ");
for(int i = 0; i < input.length(); i++)
{
error = Character.isLetter(input.charAt(i));
if(error == false)
{
input = JOptionPane.showInputDialog("Your name may only contain letters" + "\n" + "\n" + "Last Name: ");
error = Character.isLetter(input.charAt(i));
i = -1;
}
}
Client_LastName = input;
}
public void Email ()
{
input = JOptionPane.showInputDialog("Enter your Information to create an account: " + "\n" + "\n" + "Email: (Must contain a #, and end with .com, .net, .org, or .edu) ");
while(Valid_Email < 2)
{
Valid_Email = 0;
error = input.contains("#");
if(error == true)
{
Valid_Email++;
}
error = input.contains(".com");
if(error == true)
{
Valid_Email++;
}
error = input.contains(".net");
if(error == true)
{
Valid_Email++;
}
error = input.contains(".org");
if(error == true)
{
Valid_Email++;
}
error = input.contains(".edu");
if(error == true)
{
Valid_Email++;
}
if(Valid_Email < 2)
{
input = JOptionPane.showInputDialog("Invalid email entered! " + "\n" + "\n" + "Email: (Must contain a #, and end with .com, .net, .org, or .edu) ");
}
}
Client_Email = input;
}
public String Account_Created()
{
Confirm = JOptionPane.showConfirmDialog(null, "Account Created!" + "\n" + "Is everything correct?" + "\n" + "First Name: " + Client_FirstName + "\n" + "Last Name: " + Client_LastName + "\n"+ "Email: " + Client_Email);
if(Confirm == 0)
{
do{
for(i = 0; i < temp_array.length; i++)
{
temp_array[i] = r.nextInt(9);
}
for(i = 0; i < customer.length; i++)
{
for(int j = 0; j < Client_ID_Array.length; j++)
{
if(temp_array[j] == customer[i].Client_ID_Array[j])
{
Valid_ID++;
}
}
}
}while(Valid_ID == 9);
Client_ID_Array = temp_array;
for(i = 0; i < Client_ID_Array.length; i++)
{
sb.append(Client_ID_Array[i]);
}
Client_ID = sb.toString();
JOptionPane.showMessageDialog(null, "Your Client ID#: " + Client_ID );
}
return Client_ID;
}
}
class Booking extends WebStorage
{
String Client_ID;
String Storage_ID;
static int i = 0;
String temp_string = "";
String input = "";
static int Choose = 0;
static int Choose2 = 0;
static int w = 0;
static int l = 0;
Booking()
{
Client_ID = "";
Storage_ID = "";
temp_string = "";
input = "";
}
Booking(String Client_ID, String Storage_ID, String temp_string, String input)
{
this.Client_ID = Client_ID;
this.Storage_ID = Storage_ID;
this.temp_string = temp_string;
this.input = input;
}
}
class Storage extends WebStorage
{
static int Confirm = 0;
static int[] width = { 5, 5, 10, 10, 10, 10, 10};
static int[] length = { 5, 10, 10, 15, 20, 25, 30};
static int[] unit = { 3, 3, 2, 2, 2, 1, 1};
static int[] price = {16, 33, 41, 73, 163, 245, 277};
static int price_h = 0;
static int total_units = 1;
String Storage_ID = "";
StringBuilder sb;
StringBuilder sb2;
static char by = 'x';
Storage()
{
Storage_ID = "";
sb = new StringBuilder();
sb2 = new StringBuilder();
}
Storage(String Storage_ID, StringBuilder sb, StringBuilder sb2)
{
this.Storage_ID = Storage_ID;
this.sb = sb;
this.sb2 = sb2;
}
public String Storage(int w, int l)
{
for(int i = 0; i < width.length; i++)
{
if(w == width[i] && l == length[i] && unit[i] > 0)
{
if(total_units < 10)
{
sb.append(0);
sb.append(total_units);
}
if(total_units > 9)
{
sb.append(total_units);
}
if(width[i] < 10)
{
sb.append(0);
sb.append(w);
if(length[i] < 10)
{
sb.append(0);
sb.append(l);
}
if(length[i] > 9)
{
sb.append(l);
}
}
if(width[i] > 9)
{
sb.append(w);
if(length[i] < 10)
{
sb.append(0);
sb.append(l);
}
if(length[i] > 9)
{
sb.append(l);
}
}
unit[i] = unit[i] - 1;
total_units = total_units + 1;
sb2.append(w);
sb2.append(by);
sb2.append(l);
price_h = price[i];
JOptionPane.showMessageDialog(null, "Storage Booked!" + "\n" + "\n" + "size: " + sb2 + "\n" + "Rental: " + price_h + "\n" + "Storage ID: " + sb );
Storage_ID = sb.toString();
WebStorage.s++;
}
if((w != width[i] && l !=length[i]) && unit[i] <= 0)
{
JOptionPane.showMessageDialog(null, "No storage units of that size are available");
}
if(total_units == 14)
{
JOptionPane.showMessageDialog(null, "All storage units are occupied!");
}
}
return Storage_ID;
}
Have a look at those points.
You declare an array of Customer with a size of 100.
static Customer[] customer = new Customer[100];
later in the code you loop over all array entries
for(i = 0; i < customer.length; i++)
But you do not check if at index i is already a reference to a Customer is stored. If not you get a NUllPointerException.
if(input == customer[i].Client_ID)
Related
public static void stats(){
System.out.println("\nName : " +characterName+ " " +characterClass);
System.out.println("Level : " + Level); //Output the value of Level
do {
int []statValues = new int[]{Str, Dex, Con, Int, Wis, Cha};
String[] stats = new String[]{"Str", "Dex", "Con", "Int", "Wis", "Cha"};
int amount;
for (int i = 0; i<statValues.length;i++) {
statValues[i] = rollDice();
amount = statValues[i];
System.out.print(stats[i]+ " : " +statValues[i]);
if (amount == 10 || amount == 11) {
Bonus = 0;
System.out.print(" [ " + Bonus + "]\n");
}
//Bonus value for integers less than 10
else if (amount < 10) {
Bonus = 0;
bonusCounter = amount;
while (bonusCounter < 10) {
if (bonusCounter % 2 == 1) {
Bonus = Bonus + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[-" + Bonus + "]\n");
}
//Bonus value for integers greater than 10
else {
Bonus = 0;
bonusCounter = 11;
while (bonusCounter <= amount) {
if (bonusCounter % 2 == 0) {
Bonus = Bonus + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[+" + Bonus + "]\n");
}
}
System.out.println("Type \"yes\" to re-roll or press any key to terminate the program");
reRoll = sc.next();
}
while (reRoll.equals("yes"));
}
}
This is just a part of a code. Here i need to calculate the bonus for the Con stat using the variable conBonus. Because in the main method i need to calculate the hitpoints and for that the bonus value used is the bonus in conBonus.
Below is the class where the main method is given.
public class Game {
public static void main(String[] args) {
Character.level();
Character.Class();
Character.stats();
int hitPoints;
hitPoints = Character.Level*((int)((Math.random()*Character.hitDice)+1)+Character.conBonus);
System.out.println("HP : [" +hitPoints+ "]");
}
Will passing the bonus amounts to an array work. If so how can i pass it?
Here is how to store Bonus for each category:
First, change Bonus from an int to an array:
static int[] Bonus;
And in main, create a size of 6:
Bonus = new int[6];
Now to calculate hitPoints, use the array (notice that "Con" is array value 2, or the third element of the array: { "Str", "Dex", "Con", "Int", "Wis", "Cha" }
hitPoints = Character.Level * ((int) ((Math.random() * Character.hitDice) + 1) + Character.Bonus[2]);
Here is the new stats method, which uses the new Bonus array:
public static void stats() {
do {
System.out.println("\nName : " + characterName + " " + characterClass);
System.out.println("Level : " + Level); // Output the value of Level
int []statValues = new int[]{Str, Dex, Con, Int, Wis, Cha};
String[] stats = new String[] { "Str", "Dex", "Con", "Int", "Wis", "Cha" };
int amount;
for (int i = 0; i < statValues.length; i++) {
statValues[i] = rollDice();
amount = statValues[i];
System.out.print(stats[i] + " : " + statValues[i]);
if (amount == 10 || amount == 11) {
Bonus[i] = 0;
System.out.print(" [ " + Bonus[i] + "]\n");
}
// Bonus value for integers less than 10
else if (amount < 10) {
Bonus[i] = 0;
bonusCounter = amount;
while (bonusCounter < 10) {
if (bonusCounter % 2 == 1) {
Bonus[i] = Bonus[i] + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[-" + Bonus[i] + "]\n");
}
// Bonus value for integers greater than 10
else {
Bonus[i] = 0;
bonusCounter = 11;
while (bonusCounter <= amount) {
if (bonusCounter % 2 == 0) {
Bonus[i] = Bonus[i] + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[+" + Bonus[i] + "]\n");
}
}
System.out.println("Type \"yes\" to re-roll or press any key to terminate the program");
reRoll = sc.next();
} while (reRoll.equals("yes"));
}
Hi guys this is my first post in this website and I'm still new to Java. This my code that i am working on.
public static void main(String[] args) throws Exception {
// debug
if ($DEBUG) System.out.println("starting\n");
//read data from text file into arrays w,p
String[] wArr = new String[50];
String[] pArr = new String[50];
String fileName = "homs.txt";
readFile(fileName, wArr, pArr);
//main control loop
while (true) {
//use input dialog to get 2 words from user
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
String[] words = input.split("\\s+");
String w1 = words[0];
String w2 = words[1];
//check each word if in dictionary
int w1ix = chkFound(wArr, w1);
boolean isFound = (w1ix >= 0);
System.out.println(w1 + " is found: " + isFound);
int w2ix = chkFound(wArr, w2);
boolean isFound2 = (w2ix >= 0);
System.out.println(w2 + " is found: " + isFound2);
if (w1ix >=0 && w2ix >=0 ) msg = "both words " + w1 + " and " + w2 +
"\n\tare in dictionary";
else { msg = "one or more words not in dictionary: ";
if (w1ix <0) msg += w1 + " ";
if (w2ix <0) msg += w2 + " ";
System.out.println(msg);
//check if homonyms
boolean isHom = chkHom(pArr, w1, w2);
//output result
String line = msg +
"\nWord 1: " + w1 +
"\nWord 2: " + w2 +
"\nWord 1 in dictionary: " + isFound +
"\nWord 2 in dictionary: " + isFound2 +
"\nHomonyms: " + isHom;
JOptionPane.showMessageDialog(null, line);
//ask user to continue Y/N?
int cont = JOptionPane.showConfirmDialog(null, "Continue?");
if (cont > 0)
break;//exit loop or continue
}
//end main
}
}
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
My problem for this code is that when i run it it keeps looping
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
I think the reason for this problem is this part of the code. I have not come up with a solution for this though.
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
https://docs.oracle.com/javase/7/docs/api/constant-values.html#javax.swing.JOptionPane.OK_OPTION
public static final int OK_OPTION 0
your break doesn't work
if (cont > 0)
break;//exit loop or continue
change it to:
final int cont = JOptionPane.showConfirmDialog(null, "Continue?","Continue?", JOptionPane.YES_NO_OPTION);
if(cont == JOptionPane.NO_OPTION){
break;
}
I am trying to do a Yahtzee program. I start with trying to get the card pairs to work out before I continue with rest.
public class PlayEngine {
public PlayEngine(){}
public int evaluate(int[] dicePoints){
double dice1 = Math.random()*6+1;
int diceint1 = (int) dice1;
double dice2 = Math.random()*6+1;
int diceint2 = (int) dice2;
double dice3 = Math.random()*6+1;
int diceint3 = (int) dice3;
double dice4 = Math.random()*6+1;
int diceint4 = (int) dice4;
double dice5 = Math.random()*6+1;
int diceint5 = (int) dice5;
/* int[] dicePoints = {dice1, dice2, dice3, dice4, dice5}; */
int par = 0;
if(dice1==dice2 || dice1==dice3 || dice1==dice4 || dice1==dice5 || dice2==dice3 || dice2==dice4 || dice2==dice5 || dice3==dice4 || dice3==dice5 || dice4==dice5)
{
par = 1;
return par;
} else {
return par;
}
} //dicePoints
} //PlayEngine
When I run this, I get no errors. I only get up the "No main methods..", and that is how it should be.
When I try to run the program we got from school to test if the score:
import javax.swing.*;
import java.util.*;
public class TestScore {
public static void main(String[] args) {
int[] dicePoints = new int[5];
int[] playPoints = new int[15];
PlayEngine player = new PlayEngine ();
String[] kategori = {"Ettor ",
"Tvåor ",
"Treor ",
"Fyror ",
"Femmor ",
"Sexor ",
"Par ",
"Två Par ",
"Triss ",
"Fyrtal ",
"Liten stege ",
"Stor stege ",
"Kåk ",
"Chans ",
"Yatzy "};
String indata, utdata;
while(true) {
indata = JOptionPane.showInputDialog("Ange tärningarnas värden: ");
if (indata == null) // Avsluta genom att trycka Cancel
break;
StringTokenizer ordSeparator = new StringTokenizer(indata, " ,\t");
if (ordSeparator.countTokens() == 5) {
int index = 0;
while(ordSeparator.hasMoreTokens() && index < 5) {
String ettOrd = ordSeparator.nextToken();
dicePoints[index] = Integer.parseInt(ettOrd);;
index = index + 1;
}
playPoints = player.evaluate(dicePoints);
utdata = "Tärningarnas värden: ";
for (int i = 0; i < dicePoints.length; i = i + 1)
utdata = utdata + dicePoints[i] + " ";
utdata = utdata + "\n";
for (int i = 0; i <playPoints.length; i = i + 1) {
utdata = utdata + kategori[i] + playPoints[i] + "\n";
}
JOptionPane.showMessageDialog(null, utdata);
}
else
JOptionPane.showMessageDialog(null, "Du har angivt felaktigt antal värden!!!");
}
}//main
} //TestScore
I get this error:
TestScore.java:36: error: incompatible types: int cannot be converted to int[]
playPoints = player.evaluate(dicePoints);
^
How come? What is wrong?
Updated code:
import javax.swing.*;
import java.util.*;
public class TestScore {
public static void main(String[] args) {
int[] dicePoints = new int[5];
int playPoints;
PlayEngine player = new PlayEngine ();
String[] kategori = {"Ettor ",
"Tvåor ",
"Treor ",
"Fyror ",
"Femmor ",
"Sexor ",
"Par ",
"Två Par ",
"Triss ",
"Fyrtal ",
"Liten stege ",
"Stor stege ",
"Kåk ",
"Chans ",
"Yatzy "};
String indata, utdata;
while(true) {
indata = JOptionPane.showInputDialog("Ange tärningarnas värden: ");
if (indata == null) // Avsluta genom att trycka Cancel
break;
StringTokenizer ordSeparator = new StringTokenizer(indata, " ,\t");
if (ordSeparator.countTokens() == 5) {
int index = 0;
while(ordSeparator.hasMoreTokens() && index < 5) {
String ettOrd = ordSeparator.nextToken();
dicePoints[index] = Integer.parseInt(ettOrd);;
index = index + 1;
}
playPoints = player.evaluate(dicePoints);
utdata = "Tärningarnas värden: ";
for (int i = 0; i < dicePoints.length; i = i + 1)
utdata = utdata + dicePoints[i] + " ";
utdata = utdata + "\n";
for (int i = 0; i <playPoints.length; i = i + 1) {
utdata = utdata + kategori[i] + player.evaluate(dicePoints) + "\n";
}
JOptionPane.showMessageDialog(null, utdata);
}
else
JOptionPane.showMessageDialog(null, "Du har angivt felaktigt antal värden!!!");
}
}//main
} //TestScore
evaluate method return int (defined as public int evaluate(int[] dicePoints){) and not int[]. You are trying to save value returned from evaluate method as an array here:
playPoints = player.evaluate(dicePoints);
as you defined playPoints variable as int[] playPoints = new int[15];
Change it to int playPoints;
Ok, so I really didn't know how to say it right for the title so this should shed some light on the situation.
I'm making a palindrome program in Java. In every which way you look at it, it works just fine. It reads in a file using Scanner, searches through the entire file and outputs if that line in the text file is a palindrome. If you have any special characters or caps it deletes them and turns everything to lowercase.
My issue is that after the check is done on each line, I want to show some extra information next to the result.
Each line should show how many words are in the line, how many characters and if its a palindrome or not.
Anyway here is the code, hopefully someone can help me figure this out. Thanks.
import java.io.File;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
//Global Variables
Scanner cScan = null;
Scanner wScan = null;
Scanner pScan = null;
int charCount = 0, numLines = 0, numChars = 0, wordCount = 0;
//Take in User Input
Scanner iScan = new Scanner(System.in); //Start input Scanner
String fileName = null;
System.out.print("Please Enter a File Name: ");
fileName = iScan.nextLine();
iScan.close(); //Close input Scanner
//Read File Specified by User
File palin = new File(fileName);
try {
//Checks for Number of Characters
cScan = new Scanner(palin);
while(cScan.hasNextLine()) {
String line = cScan.nextLine();
numChars += line.length();
numLines++;
}
//Checks for Number of Words
wScan = new Scanner(palin);
while (wScan.hasNext()) {
wScan.next();
wordCount++;
}
//Format Lines
pScan = new Scanner(palin);
while (pScan.hasNext()) {
String line = pScan.nextLine();
String reString = line.replaceAll("[^\\p{L}\\p{Nd}]", "");
String lString = reString.toLowerCase();
boolean pali = false;
String tP = "Yes", fP = "No";
int n = lString.length();
for (int i = 0; i < (n / 2) + 1; ++i) {
if (lString.charAt(i) != lString.charAt(n - i - 1)) {
pali = false;
break;
}
else if (lString.charAt(i) == lString.charAt(n - i - 1)) {
pali = true;
break;
}
}
if (pali == true)
System.out.println(line + " w: " + wordCount + ", " + " c: " + charCount + ", " + tP);
else
System.out.println(line + " w: " + wordCount + ", " + " c: " + charCount + ", " + fP);
}
}
catch(Exception e) {
System.out.println("File Could Not be Found");
}
//charCount = (numLines + numChars) - 1; //Minus 1 to Compensate for EOL at EOF
//System.out.println(charCount);
//System.out.println(wordCount);
//System.out.println(spRemover);
}
}
I cleaned up your code a little bit.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Palindrome {
int charCount = 0;
int totalWordCount = 0;
public static String isPalindrome(String str) {
if(str.equals(new StringBuffer().append(str).reverse().toString())) {
return "a";
}
else {
return "not a";
}
}
public static int getNumberOfWords(String str) {
return str.isEmpty() ? 0 : str.split("\\s+").length;
}
public void process(File file) {
try {
Scanner sc = new Scanner(file);
int i = 0;
while(sc.hasNextLine()) {
i++;
String line = sc.nextLine();
int wordCount = getNumberOfWords(line);
System.out.println("Line " + i + "is " + isPalindrome(line) + " palindrome. It has " + wordCount + " words and " + line.length() + " characters.");
charCount = charCount + line.length();
totalWordCount = totalWordCount + wordCount;
}
sc.close();
System.out.println("There are " + i + " lines in the file with a total of " + totalWordCount + " words and " + charCount + " characters.");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner iScan = new Scanner(System.in);
String fileName = null;
System.out.print("Please Enter a File Name: ");
fileName = iScan.nextLine();
iScan.close();
File file = new File(fileName);
Palindrome pal = new Palindrome();
pal.process(file);
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class IteratingFileWithInformation {
int charCount = 0 ;
int totalWordCount = 0;
private static String checkPalindrome(String line) {
return line.equals(new StringBuffer().append(line).reverse().toString()) ? "a" : "not a" ;
}
private static int getNumberOfWords(String words) {
return words.isEmpty() ? 0 : words.split("\\s+").length;
}
private void checkFileAndProcess(BufferedReader file) {
Scanner input = new Scanner(file);
int i = 0;
while(input.hasNextLine()) {
i++;
String line = input.nextLine();
int wordCount = getNumberOfWords(line);
System.out.println("Line: " + i + " is " + checkPalindrome(line) + " Palindrome. It has " + wordCount + " words and " + line.length() +
" characters. ");
charCount += line.length();
totalWordCount += wordCount;
}
input.close();
System.out.println("There are " + i + " lines in the file with a total of " + totalWordCount + " words and " + charCount + " characters.");
}
public static void main(String[] args) throws FileNotFoundException {
Scanner givefileName = new Scanner(System.in);
String fileName = null;
System.out.println("Enter the file name :");
fileName = givefileName.nextLine();
givefileName.close();
FileReader file = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(file);
IteratingFileWithInformation fileWithInformation = new IteratingFileWithInformation();
fileWithInformation.checkFileAndProcess(bufferedReader);
}
}
but when I run the program using the command line. I get a run time error of "java.lang.NoClassDefFoundError". All I did was copy the code from Netbeans and paste it on a notepad file and then tried running it by command prompt. I am not sure what I am/ did wrong. Any feedback is greatly appreciated it! Here is my code BTW
package reader;
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class Reader{
public static final Scanner in = new Scanner( System.in);
static final int adult = 0; // The index representation numbers for the total and count arrays;
static final int child = 1;
static final int adultMale = 2;
static final int adultFemale = 3;
static final int childMale = 4;
static final int childFemale = 5;
static final int people = 6;
static final int family = 7;
public static void main(String[] arg){
if(arg.length > 2){ die("Too many arguments");}
else {System.out.println("Good");}
String inFileName;
if(arg.length > 0){ inFileName = arg[0];}
else {
inFileName = "population.txt";}
Scanner fin = openFile(inFileName);
int[] count = new int[8]; // adults,children,male adult, female adult, male child , female child, people, family
int[] total = new int[8]; //adults,children,male adult, female adult, male child , female child, people, family
for( ; fin.hasNextLine(); ){
String line = fin.nextLine();
String error = check(line);
if(error != null){die(error);}
else{ gather(line, count, total);}
}//loop
for(int i = 0; i< count.length; i++){ System.out.print(count[i] + " ");}
System.out.println();
for(int i = 0; i< total.length; i++){ System.out.print(total[i] + " ");}
System.out.println();
System.out.println((float)count[family]/count[people]);
fin.close();
String outFileName;
if( arg.length > 1){ outFileName = arg[1];}
else{outFileName = "output.txt";}
PrintStream fout = outFile(outFileName);
showCensus(fout,count,total);
}//main
public static void die(String message){
System.err.println("Error: " + message);
System.exit(1);
}//die
public static Scanner openFile(String fileName){
Scanner inputFile = null;
try{
inputFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException e){ die("File not found: " + fileName);
}
return inputFile;
}// OpenFIle
public static PrintStream outFile(String fileName){
Scanner temp = null;
try{
temp = new Scanner(new File(fileName));
} catch(FileNotFoundException ei){
PrintStream result = null;
try{
result = new PrintStream( new File(fileName));
}catch(FileNotFoundException eo){die("Can't open " + fileName);}
return result;
}
die("The file " + fileName + " already exists!");
return null;
}
public static String check(String line){
int change = 0;
String sex;
int age;
Scanner sin = new Scanner(line);
if(!sin.hasNext()){return null;}
if(sin.next().equalsIgnoreCase("Comment")){return null;}
Scanner sin2 = new Scanner(line);
while(sin2.hasNext()){
change++;
if(change % 2 == 0){}
else{
sex = sin2.next();
if(!sex.equals("M")&& !sex.equals("F")){return "Gender must be 'M' or 'F', not " + sex;}
if(!sin2.hasNext()){return "No data after " + sex ;}
if(!sin2.hasNextInt()){return "age must be a number not " + sin2.next();}
age = sin2.nextInt();
//System.out.print(sex + " " + age + " ");
}
}
System.out.println();
return null;
}
public static void gather(String line, int[] count, int[] total){
int change = 0;
Scanner sin = new Scanner(line);
if(!sin.hasNext()){return ;}
if(sin.next().equalsIgnoreCase("Comment")){return;}
Scanner sin2 = new Scanner(line);
while(sin2.hasNext()){
change++;
if(change % 2 == 0){}
else{
String sex = sin2.next();
int age = sin2.nextInt();
if(sex.equals("M") && age > 17){
count[adultMale]++;
count[adult]++;
count[people]++;
total[adultMale]+= age;
total[adult]+= age;
total[people]+= age;}
else if(sex.equals("M") && age <= 17){
count[child]++;
count[people]++;
count[childMale]++;
total[child]+= age;
total[people]+= age;
total[childMale]+= age;}
else if(sex.equals("F") && age > 17 ){
count[adult]++;
count[adultFemale]++;
count[people]++;
total[adult]+= age;
total[adultFemale]+= age;
total[people]+= age;}
else if(sex.equals("F") && age <= 17){
count[childFemale]++;
count[child]++;
count[people]++;
total[childFemale]+= age;
total[child]+= age;
total[people]+= age;}
}
}// while
count[family]++;
}
public static void showCensus(PrintStream out, int[] count, int[] total){
out.println("The Family Statistics 2013 Report");
out.println();
out.println("People: " + count[people] + " Average Age: " + (float)total[people]/count[people]);
out.println(" Adults: " + count[adult] + " Average Age: " + (float)total[adult]/count[adult]);
out.println(" Males: " + count[adultMale] + " Average Age: " + (float)total[adultMale]/count[adultMale]);
out.println(" Females: " + count[adultFemale] + " Average Age: " + (float)total[adultFemale]/count[adultFemale]);
out.println(" Children: " + count[child] + " Average Age: " + (float)total[child]/count[child]);
out.println(" Males: " + count[childMale] + " Average Age: " + (float)total[childMale]/count[childMale]);
out.println(" Female: " + count[childFemale] + " Average Age: " + (float)total[childFemale]/count[childFemale]);
out.println("Families: " + count[family] + " Average Family Size " + (float)count[family]/count[people]);
}
}//Reader
Your class Reader is defined in the reader package. You need to give the JVM the proper class path. Create a folder called reader and place your class there. Then use the -classpath flag when call java.
c:\>javac reader\Reader.java
c:\>java -classpath . reader.Reader