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
Related
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;
}
import java.io.*;
import java.util.*;
public class Exercise3_2
{
public static void main(String[] args) throws FileNotFoundException
{
String firstName;
String lastName;
double score1, score2, score3, score4, score5;
double avg;
Scanner inFile = new Scanner(new FileReader("test.txt"));
PrintWriter outFile = new PrintWriter ("testavg.out");
firstName = inFile.next();
lastName = inFile.next();
outFile.println("Student name : " + firstName + " " + lastName);
score1 = inFile.nextDouble();
score2 = inFile.nextDouble();
score3 = inFile.nextDouble();
score4 = inFile.nextDouble();
outFile.println("Test scores: " + score1 + " ," + score2 + " ," + score3
+ " ," + score4);
avg = (score1 + score2 + score3 + score4) / 4;
outFile.printf("Average test scores: %5.2f %n, avg");
inFile.close();
outFile.close();
}
}
Whenever I run this this is what I get :
Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
......WHY!!!!
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)
Here is my code:
import java.util.*;
import java.text.*;
public class zadanko4
{
int ile;
public static final int vat8 = 8;
public static final int vat23 = 23;
public static final int vat5 = 5;
//deklaracje zmiennych tablicowych
static double[] price;
static String[] name;
static int[] quantity;
static int[] vat;
//tworzenie tablic
price = new double[ile];
name = new String[ile];
quantity = new int[ile];
vat = new int[ile];
public static void printSellerData(String tekst)
{
System.out.print(tekst);
}
public static void printBuyerData(String company, String taxNo, String phone, String email)
{
System.out.print(company + taxNo + phone + email);
}
public static void printInvoiceDate(Date data)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(dateFormat.format(data));
}
public static void printInvoiceHeader(String naglowek)
{
System.out.print(naglowek);
}
public static void printInvoiceProduct(String name, int quantity, double price, int vat)
{
System.out.printf(name + quantity + price + vat);
}
public static void readProductsData()
{
//uzytkownik wprowadza liczbe produktow
System.out.println("podaj liczbe produktow");
Scanner scanner = new Scanner(System. in );
ile = scanner.nextInt();
}
public static void main(String[] args)
{
int i;
String line;
for (i = 0; i < ile; i++)
{
System.out.print("Podaj cene produktu nr " + (i + 1) + ": ");
price[i] = scanner.nextDouble();
System.out.print("Podaj nazwe produktu nr " + (i + 1) + ": ");
name[i] = scanner.next();
System.out.print("Podaj ilosc produktu nr " + (i + 1) + ": ");
quantity[i] = scanner.nextInt();
System.out.print("Podaj vat produktu nr " + (i + 1) + ": ");
vat[i] = scanner.nextInt();
System.out.printf("Dane sprzedajacego\n");
printSellerData("Company: MaxDom Ltd, Kochanowskiego 17, 31-782 Krakow, Poland\n");
printSellerData("Tax no: 677-000-21-39\n");
printSellerData("Phone: +48123454943\n");
printSellerData("Email: office#maxdom.pl\n\n");
System.out.printf("Dane kupujacego\n");
printBuyerData("Softpol Ltd, Mickiewicza 5, 31-009 Krakow, Poland\n", "342-909-33-12\n", "+48505392100\n", "office#softpol.eu\n");
// printInvoiceNumber(+numer+);
Date data = new Date();
printInvoiceDate(data);
printInvoiceHeader("|No.|Product desciptrion |Quantity |Unit price |Total |VAT rate |VAT |Gross|");
printInvoiceHeader("|______________________________________________________________________________________________________|");
//printInvoiceProduct("name[i]", ilosc[prod], cena[prod], vat[prod]");
printInvoiceProduct("|" + (i + 1) + " |" + name[i] + " |" + quantity[i] + " |" + price[i] + " |" + (quantity[i] * price[i]) + " |" + (vat[i] / 100.0) + " |" + (quantity[i] * price[i] * (vat[i] / 100.0)) + " |" + (quantity[i] * price[i]) * (1 + (vat[i] / 100.0)));
}
}
}
and my problems:
I have 4 errors like: error: <identifier> expected. It is connected
with arrays but i have no idea what is wrong.
By the last line: printInvoiceProduct.... I want to display 1 product which user entered, but nothing displays.
Why is that?
Create new memory addresses for arrays as you refer them. Like;
static double[] price = new double[ile];
This is also not enough because these static arrays trying to make a static reference to a non-static variable, "ile". So if you want your arrays to be static, just make "ile" static also.
printInvoiceProduct method is declared to pass 4 arguments to it but you've called it by only one String object.
Even if you solve compilation errors you will face again problems.
For example you are creating an array with size zero This will fail. So instead of creating your array objects above; create in the main function after knowing size of array.
So get rid of ile variable. Take input in the main and then instantiate all the array.
Even I don't see a need of class level arrays all can be method local.
On top of that I don't think this is correct platform to solve such problem. Consider putting your problem on
https://codereview.stackexchange.com/
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);
}
}