Methods and arrays - java

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/

Related

Why is the compiler saying "cannot find symbol" to the getter methods? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
When I try to compile the code, it keeps saying "cannot find symbol" every single time I try to call a getter method. I'd love any and all suggestions as to how to fix the problem.
Here is the code with the main method
import java.util.Scanner;
public class Assignment10
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("\nThis program displays some attributes and behaviors of two different dogs.");
//Create two Dogs objects
Dogs firstDog = new Dogs();
Dogs secondDog = new Dogs();
//Naming scheme for first dog
System.out.print("\nWhat would you like to name the first dog? ");
firstDog.setName(in.nextLine());
//Naming scheme for second dog
System.out.print("What would you like to name the second dog? ");
secondDog.setName(in.nextLine());
//Scheme for getting the breed of first dog
System.out.print("\nWhat is the breed of the first dog? ");
firstDog.setBreed(in.nextLine());
//Scheme for getting the breed of first dog
System.out.print("What is the breed of the second dog? ");
secondDog.setBreed(in.nextLine());
//Scheme to get age of first dog
System.out.println("\nWhere is the first dog in their lifespan? ");
System.out.print("Enter 1 for puppy, 2 for adolescent, 3 for adult, 4 for senior: ");
firstDog.setAge(in.nextInt());
//Scheme to get age of second dog
System.out.println("Where is the first dog in their lifespan? ");
secondDog.setAge(in.nextInt());
//Scheme to get weight of first dog
System.out.println("\nWhere is the first dog in the weight range?");
System.out.print("Enter 1 for low, 2 for medium, 3 for high: ");
firstDog.setWeight(in.nextInt());
//Scheme to get weight of second dog
System.out.println("Where is the second dog in the weight range?: ");
secondDog.setWeight(in.nextInt());
System.out.println("\nThank you for your input.");
System.out.println("The following describes the first dog:\n");
//Displaying the attributes and behaviors of the first dog
System.out.println( firstDog.getName + " is a " + firstDog.getAge + " month old " + firstDog.getWeight + " pound " + firstDog.getGender + " " + firstDog.getBreed + " who " + firstDog.getFleas + "fleas.");
System.out.print("When their owner tossed over a doggie treat, " + firstDog.getName + " jumped in the air and went ");
firstDog.eating();
System.out.println();
System.out.print("When " + firstDog.getName + " ran back to their owner after fetching the ball, the " + firstDog.getBreed + " dropped the ball and elatedly went ");
firstDog.barking();
System.out.println();
if ( firstDog.getFleas().equals("has") )
{
System.out.print("After rolling around in the mud, " + firstDog.getName + " always goes ");
firstDog.scratchingFleas();
}
//Displaying the attributes and behaviors of the second dog
System.out.println( secondDog.getName + " is a " + secondDog.getAge + " month old " + secondDog.getWeight + " pound " + secondDog.getGender + " " + secondDog.getBreed + " who " + secondDog.getFleas + "fleas.");
System.out.print( secondDog.getName + " loudly goes ");
secondDog.eating();
System.out.println(" whenever they eat.");
System.out.print( secondDog.getName + " goes ");
secondDog.barking();
System.out.println(" each and every time there's a squirrel in the backyard.");
if ( secondDog.getFleas().equals("has") )
{
System.out.print("The owners brought the " + secondDog.getBreed + " to the vet because " + secondDog.getName + " kept going ");
secondDog.scratchingFleas();
System.out.print(" as if there were fleas.");
}
}
}
and here is the code with the class that defines the objects
public class Dogs
{
private StringBuffer z = new StringBuffer("");
private StringBuffer name;
private StringBuffer breed;
private String gender;
private int age;
private double weight;
private String fleas;
private int i = (int)(Math.random() * 20);
private int j = (int)(Math.random() * 20);
private int k = (int)(Math.random() * 50);
private int l = (int)(Math.random() * 50);
public Dogs()
{
name = z;
breed = z;
gender = (i <= j) ? "female" : "male";
age = 0;
weight = 0;
fleas = (k <= l) ? "has " : "does not have ";
}
public void setName(String s) {
name = name.append(s);
}
public void setBreed(String s) {
breed = breed.append(s);
}
public void setAge(int i)
{
if (i == 1)
age = (int)(1 + Math.random() * 7);
if (i == 2)
age = (int)(8 + Math.random() * 10);
if (i == 3)
age = (int)(18 + Math.random() * 66);
if (i == 4)
age = (int)(84 + Math.random() * 49);
}
public void setWeight(int i)
{
if (i == 1)
weight = 10 + Math.random() * 30;
if (i == 2)
weight = 40 + Math.random() * 60;
if (i == 3)
weight = 100 + Math.random() * 50;
}
public String getName() {
return name.toString();
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
public String getGender() {
return gender;
}
public String getBreed() {
return breed.toString();
}
public String getFleas() {
return fleas;
}
public void eating() {
System.out.print("chomp chomp chomp!");
}
public void barking() {
System.out.print("woof woof woof!");
}
public void scratchingFleas() {
System.out.print("scrhh scrhh scrhh");
}
}
I really appreciate everyone who helps!!!!
You are not calling the getters. You do dog.getNamewhen you should be doing dog.getName();

Why are object values not being stored?

***After bottle3 is .set() to 0, all of the values seem to be set to zero. Even took the bottle3.set(0); bit of the driver and it the other bottle objects still seem to lose the value that they are supposed to be set to.
import java.util.Scanner;
test driver for the Bottle class
public class BottleDriver extends Bottle
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
int x;
Bottle bottle1 = new Bottle();
Bottle bottle2 = new Bottle();
Bottle bottle3 = new Bottle();
Bottle bottle4 = new Bottle();
Bottle bottle5 = new Bottle();
System.out.println("please enter a number for bottle1:");
bottle1.read();
System.out.println("Bottle1 is this value " + bottle1.marbles + ".");
System.out.println("Please enter a number for bottle2:");
bottle2.read();
System.out.println("Bottle2 is this value " + bottle2.marbles + ".");
bottle3.set(0);
System.out.println("Bottle3 is set to " + bottle3.marbles + ".");
bottle3 = bottle3.add(bottle1);
System.out.println(bottle3.marbles);
bottle3 = bottle3.add(bottle2);
bottle3 = bottle3.divide(2);
System.out.println("The 2 bottle average is: " + bottle3 + ".");
System.out.print("Subtracting bottle1 from bottle2 is: " );
bottle3 = bottle2.subtract(bottle1);
System.out.println( bottle3);
bottle3 = bottle2.divide(bottle1);
System.out.println("Dividing bottle2 with bottle1 is: " + bottle3 + ".");
if (bottle1.equals(bottle2))
{
System.out.println("Bottle1 and bottle2 are equal.");
}
else
{
System.out.println("Bottle1 and bottle2 are not equal.");
}
System.out.println("Bottle4 is now given the value of 10 with the set()method.");
bottle4.set(10);
System.out.println("The value of bottle4 is " + bottle4 + ".");
System.out.println("Bottle4 is now multiplied with bottle1. The value is placed in bottle5.");
bottle5 = bottle1.multiply(bottle4);
System.out.println("The value of bottle5 is " + bottle5 + ".");
System.out.println("Enter an integer to add to the value bottle1 has.");
System.out.println("The sum will be put in bottle3.");
x = scan.nextInt();
bottle3 = bottle1.add(x);
System.out.println("Adding your number " + x +
" to bottle1 gives a new Bottle with " + bottle3 + " in it.");
System.out.print("Adding the number " + bottle2 + " which is the number" +
" in bottle2 to the\nnumber in ");
bottle2 = bottle1.add(bottle2);
System.out.println("bottle1 which is " + bottle1 +" gives " + bottle2 + ".");
}
}
//***Bottle Class
import java.util.Scanner;
public class Bottle
{
public static final int MAX = 75;
public static final int MIN = 0;
public static int marbles;
Bottle()
{
marbles = 0;
}
public int get()
{
return this.marbles;
}
public void read() {
Scanner keyboard = new Scanner(System.in);
marbles = keyboard.nextInt();
set(marbles);
}
public void set(int marbles)
{
if(marbles > MAX || marbles < MIN)
{
System.out.println("Below or exceeded capacity of the bottle.");
System.exit(0);
}
else
{
this.marbles = marbles;
}
}
public Bottle add(Bottle bottle)
{
Bottle newBottle = new Bottle();
newBottle.set(newBottle.marbles + bottle.marbles);
return newBottle;
}
public int subtract(int bottle)
{
}
public int multiply(int bottle)
{
}
public int divide(int bottle)
{
}
}
The issue is that marbles is a static field. Static fields are shared between all instances of the class, to help save on memory. Remove the static annotation and it should fix your issue.
public static int marbles;

How do I make this if statement?

Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}

How can I print out in columns in java

This is where I am printing out and I need it to print in columns.aLeaderboard is an array list with a custom class.it contains several different ints
System.out.println("Position Team Games Played Home Wins Home Draws Home Losses Home Goals For Home Goals Against Away Wins Away Draws Away Losses Away Goals For Away Goals Against Goal Difference Total Points");
for(int counter = 0;counter<teamName.size();counter++)
{
System.out.print((counter + 1) + " " + teamName.get(counter) + " " + (aLeaderboard.get(counter)).getGamesPlayed() + " " + (aLeaderboard.get(counter)).getHomeWins() + " " + (aLeaderboard.get(counter)).getHomeDraws() + " ");
System.out.print((aLeaderboard.get(counter)).getHomeLosses() + " " + (aLeaderboard.get(counter)).getAwayWins() + " " + (aLeaderboard.get(counter)).getAwayWins() + " " + (aLeaderboard.get(counter)).getAwayDraws() + " ");
System.out.print((aLeaderboard.get(counter)).getHomeGoalsFor() + " " + (aLeaderboard.get(counter)).getHomeGoalsAgainst() + " " + (aLeaderboard.get(counter)).getAwayLosses() + " " + (aLeaderboard.get(counter)).getGamesPlayed() + " ");
System.out.print((aLeaderboard.get(counter)).getAwayGoalsFor() + " " + (aLeaderboard.get(counter)).getAwayGoalsAgainst() + " " + (aLeaderboard.get(counter)).getGoalsDifference() + " " + (aLeaderboard.get(counter)).getTotalPoints());
System.out.println();
}
I would use System.out.printf(...) and use a template String to help be sure that all columns line up. Then you could print things out easily in a for loop.
For example:
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class Foo4 {
public static void main(String[] args) {
List<Bar4> bar4List = new ArrayList<>();
bar4List.add(new Bar4("Donald", 3, "A", 22.42));
bar4List.add(new Bar4("Duck", 100, "B", Math.PI));
bar4List.add(new Bar4("Herman", 20, "C", Math.sqrt(20)));
String titleTemplate = "%-10s %6s %6s %9s%n";
String template = "%-10s %6d %6s %9s%n";
System.out.printf(titleTemplate, "Name", "Value", "Grade", "Cost");
for (Bar4 bar4 : bar4List) {
System.out.printf(template, bar4.getName(),
bar4.getValue(), bar4.getGrade(), bar4.getCostString());
}
}
}
class Bar4 {
private String name;
private int value;
private String grade;
private double cost;
private NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
public Bar4(String name, int value, String grade, double cost) {
this.name = name;
this.value = value;
this.grade = grade;
this.cost = cost;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public String getGrade() {
return grade;
}
public double getCost() {
return cost;
}
public String getCostString() {
return currencyFormat.format(cost);
}
}
Which would return:
Name Value Grade Cost
Donald 3 A $22.42
Duck 100 B $3.14
Herman 20 C $4.47
For more details on the user of the String format specifiers (i.e., the %6d and %6s above), please look at the Formatter API.

Code compiles and runs in Netbeans but not java command line

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

Categories

Resources