i've been puzzling over this for about 5 hours now, I just can't get the errors to stop. am I doing something fundamentally wrong, or misunderstanding something? I'm hoping this is fairly simple to some people, as i'm just learning. the point of this program is to calculate taxes and dealership fees on cars using methods and arrays.
package taxesandfeescar;
import java.util.Scanner;
import java.util.Arrays;
/**
*
* #author K
*/
public class Taxesandfeescar {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many vehicle prices would you like to store?");
int pricesNumber = input.nextInt();
int Prices[] = new int[pricesNumber];
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
System.out.println("Please enter the price, Without taxes or fees, of car #" + imsg);
Prices[i] = input.nextInt();
}
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
System.out.println("The final price, after taxes and fees of car #" + imsg + " is " + pricesTaxFees[i]);
Prices[i] = input.nextInt();
int pricesTaxFees[i] = applyTaxesAndFees[i];
}
}
public static double[] applyTaxesAndFees(int Prices, int pricesNumber){
int pricesTaxFees[pricesNumber];
for(int i = 0; i < pricesNumber; i++) {
pricesTaxFees[i] = Prices[i] / 13 * 100 + 1500;
}
return pricesTaxFees[];
}
}
You have several errors in your code. For example: you dont have to read twice the price of the car. You cannot print the message with the final price before calculating the final price. When you have defined like that applyTaxesAndFees(int Prices, int pricesNumber) you cannot call it like thatapplyTaxesAndFees[i], it is totaly wrong. You shoul call this method like applyTaxesAndFees(Price, priceNumber).
Anyway, check the code above and find and learn from your mistakes like we all do. Have fun with java.
This will work for you.
import java.util.Scanner;
import java.util.Arrays;
/**
*
* #author K
*/
public class Taxesandfeescar {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many vehicle prices would you like to store?");
int pricesNumber = input.nextInt();
int Prices[] = new int[pricesNumber];
int pricesTaxFees[] = new int[pricesNumber];
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
System.out.println("Please enter the price, Without taxes or fees, of car #" + imsg);
Prices[i] = input.nextInt();
}
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
pricesTaxFees[i] = applyTaxesAndFees(Prices[i]);
System.out.println("The final price, after taxes and fees of car #" + imsg + " is " + pricesTaxFees[i]);
}
}
public static int applyTaxesAndFees(int Price){
int pricesTaxFees = 0;
pricesTaxFees = Price / 13 * 100 + 1500;
return pricesTaxFees;
}
}
Here is something working:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many vehicle prices would you like to store?");
int numberOfVehicles = input.nextInt();
double[] vehiclePrices = new double[numberOfVehicles];
for (int i = 0; i < numberOfVehicles; i++) {
int vehicleNumber = i + 1;
System.out.println("Please enter the price, Without taxes or fees, of car #" + vehicleNumber);
vehiclePrices[i] = input.nextInt();
}
for (int i = 0; i < numberOfVehicles; i++) {
int vehicleNumber = i + 1;
vehiclePrices[i] = applyTaxesAndFees(vehiclePrices[i]);
System.out.println("The final price, after taxes and fees of car #" + vehicleNumber + " is " + vehiclePrices[i]);
}
}
public static double applyTaxesAndFees(double pricesBeforeTaxes) {
double priceAfterTaxes = pricesBeforeTaxes + ((pricesBeforeTaxes * 13) / 100) + 1500;
return priceAfterTaxes;
}
my advice would be to check the changes line by line and see the differences. I'm learning as well, but would recommend you to read more about how methods and arrays works. Also - naming conventions are important.
Related
When I try to print my array in the main...I'm getting NULL and 0.0.
Can anyone give me some advice as to why this may be happening?
Since I was getting all Nulls and 0.0's I pulled the for loop into my dataCalculations method and it printed the name and the sales amount perfectly.
Is my use of the .length feature incorrect?
Any advice/help would be greatly appreciated.
Thanks,
/*
* Anthony Vincenzo Laginess
* CIT 130 HMW 08 Arrays
* 10/19/16
* Time Spent:
*/
package cit130mhmw08_laginess;
import java.util.Scanner;
public class CIT130MHMW08_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("------------------------------------------");
System.out.println("Please enter the total number of dealers: ");
System.out.println("------------------------------------------");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
String[] dealerNames = new String[numDealers];
double[] dealerSales = new double[numDealers];
double[] commissionRate = new double[dealerSales.length];
double[] dealershipSalesTotal = new double[dealerSales.length];
double[] dealerSalesAvgTotal = new double[dealerSales.length];
double[] totalCommission = new double[commissionRate.length];
System.out.println("--------------------------------------------------------");
System.out.printf("Please enter the required data for each of your dealers: %n");
System.out.println("--------------------------------------------------------");
dataCalculation(numDealers);
System.out.println("----------------");
System.out.println("Dealer Totals: ");
System.out.println("----------------");
displayTotals(numDealers, dealerNames, dealerSales, commissionRate);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: %n");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
double[] dealerSales = new double[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
double sales = input.nextDouble();
dealerSales[i] = sales;
}
}//data calculations
//METHOD 3
public static double[] commission(double[] dealerSales)
{
//Create array
double[] commissionRate = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
commissionRate[i] = dealerSales[i];
if(commissionRate[i] > 0 && commissionRate[i] < 5000)
commissionRate[i] = commissionRate[i] * 0.08;
else if(commissionRate[i] > 5000 && commissionRate[i] < 15000)
commissionRate[i] = commissionRate[i] * 0.15;
else if(commissionRate[i] > 15000)
commissionRate[i] = commissionRate[i] * 0.20;
}
return commissionRate;
}//commission method
public static double[] dealershipSales(double[] dealerSales)
{
//Create array
double[] dealershipSalesTotal = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
dealershipSalesTotal[i] += dealerSales[i];
}
return dealershipSalesTotal;
}//dealership sales
public static double[] dealerSalesAvg(double[] dealerSales)
{
double[] dealerSalesAvgTotal = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
dealerSalesAvgTotal[i] += dealerSales[i] / dealerSales.length;
}
return dealerSalesAvgTotal;
}//dealership sales averages
public static double[] dealershipTotalCommission(double[] commissionRate)
{
double[] totalCommission = new double[commissionRate.length];
for(int i = 0; i < commissionRate.length; i++)
{
totalCommission[i] += commissionRate[i];
}
return totalCommission;
}//total commission for the dealership
public static void displayTotals(int numDealers, String[] dealerNames, double[] dealerSales, double[] commissionRate)
{
for(int i = 0; i < numDealers; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
System.out.println(" " + commissionRate[i]);
}
}//display totals
}//class
You are not returning anything from dataCalculation(), so the calculations are lost when the method call is done. Just as dealerNames, dealerSales and commissionRate are passed as arguments to displayTotals(), they should probably be passed to dataCalculation() first rather than being declared again, at least the first two. You should call commission() to get the last, the method doesn’t seem to be called ever.
I'm trying to teach myself Java and I'm having a hell of a time! :)
I just started the other day and I've hit a bit of a road block.
I'm trying to learn arrays, but my methods are also kinda jacked up.
I know when I invoke my method in my main that it isn't right. I thought I was supposed to give the method that I was invoking the arguments that it needs to carry out its processes?
I'm just trying to call my last method and display the data from that method.
package test_arraymethods;
import java.util.Scanner;
public class TEST_arraymethods
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("------------------------------------------");
System.out.println("Please enter the total number of dealers: ");
System.out.println("------------------------------------------");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
System.out.println("--------------------------------------------------------");
System.out.printf("Please enter the required data for each of your dealers: %n");
System.out.println("--------------------------------------------------------");
dataCalculation(numDealers);
//displayTotals(numberOfDealers, dealerNames, dealerSales, commissionRate);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: %n");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
double[] dealerSales = new double[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
double sales = input.nextDouble();
dealerSales[i] = sales;
}
}//data calculations
//METHOD 3
public static double[] commission(double[] dealerSales)
{
//Create array
double[] commissionRate = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
commissionRate[i] = dealerSales[i];
if(commissionRate[i] > 0 && commissionRate[i] < 5000)
commissionRate[i] = commissionRate[i] * 0.08;
else if(commissionRate[i] > 5000 && commissionRate[i] < 15000)
commissionRate[i] = commissionRate[i] * 0.15;
else if(commissionRate[i] > 15000)
commissionRate[i] = commissionRate[i] * 0.20;
}
return commissionRate;
}//commission method
public static double[] dealershipSales(double[] dealerSales)
{
//Create array
double[] dealershipSalesTotal = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
dealershipSalesTotal[i] += dealerSales[i];
}
return dealershipSalesTotal;
}//dealership sales
public static double[] dealerSalesAvg(double[] dealerSales)
{
double[] dealerSalesAvgTotal = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
dealerSalesAvgTotal[i] += dealerSales[i] / dealerSales.length;
}
return dealerSalesAvgTotal;
}//dealership sales averages
public static double[] dealershipTotalCommission(double[] commissionRate)
{
double[] totalCommission = new double[commissionRate.length];
for(int i = 0; i < commissionRate.length; i++)
{
totalCommission[i] += commissionRate[i];
}
return totalCommission;
}//total commission for the dealership
public static void displayTotals(double[] numberOfDealers, double[] dealerNames, double[] dealerSales, double[] commissionRate)
{
for(int i = 0; i < numberOfDealers.length; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
System.out.println(" " + commissionRate[i]);
}
// pass all of your values to this method and then display them
//display the dealer name and amount of sales
//and the amount of commission for all dealers in a tabular format.
}//display totals */
}//class
The reason that you can't get this to work:
displayTotals(numberOfDealers, dealerNames, dealerSales, commissionRate);
is that it is referring to variables that are not in scope. Those variables are all local variables within methods whose calls have finished. If you want the variables to be accessible in another method, they must be declared as (static, in this case) fields.
Can someone help me figure out how to make this program display the longest streak. I'm rolling two dice, and recording the percent each dice sum. Now I need something that will tell me what dice sum came up in the longest streak for example "The longest run was a run of 8 7's that began at roll 1479966."
import java.util.Scanner;
import java.text.DecimalFormat;
public class RollThoseDice {
/* Author: Name
* Assignment: Third Program
*/
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int timesRolled, randomOutSum;
DecimalFormat df = new DecimalFormat ("#.###");
System.out.println("Name: "
+ "\nAssignment: Third Program"
+"\nExtra Credit: Percentage is displayed in three decimal places");
int[] d = new int[13];
for (int i = 2; i < 13; i++) d[i] = 0;
int N=0;
boolean againA = true;
while(againA) {
try{
System.out.print("\nHow Many Rolls? ");
N =kbd.nextInt();
againA = false;
} catch(Exception e) {
System.out.println("Invalid Input");
kbd.next();
}
}
for (int k = 0; k < N; k++) {
int diceOut1 = (int) (Math.random()*6+1);
int diceOut2 = (int) (Math.random()*6+1);
int diceSum = diceOut1 + diceOut2;
d[diceSum]++;
}
for (int i = 2; i < 13; i++)
System.out.println("Total " + i + " happened "
+ df.format((double) (d[(int) i] / (double) N) * 100)
+ "% of the time.");
}
}
The longest run was a run of 8 7's that began at roll 1479966.
So, what are the parameters in that output?
Looks like roll, run length or roll count, and roll number.
Hmm, what can keep multiple variables, so we can treat them as one thing?
I know, we'll create a model class.
public class RollStreak {
private final NumberFormat NF = NumberFormat.getInstance();
private int roll;
private int rollCount;
private long rollNumber;
public RollStreak(int roll, long rollNumber, int rollCount) {
this.roll = roll;
this.rollNumber = rollNumber;
this.rollCount = rollCount;
}
public int getRoll() {
return roll;
}
public int getRollCount() {
return rollCount;
}
public long getRollNumber() {
return rollNumber;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("The computer rolled a ");
builder.append(roll);
builder.append(" ");
builder.append(rollCount);
builder.append(" times in a row starting at roll number ");
builder.append(NF.format(rollNumber));
builder.append(".");
return builder.toString();
}
}
A model class allows you to treat a group of fields as one object.
I don't want to give away the whole answer. You still have to determine how to create these model class instances and get the longest streaks. Hint: There can be more than one longest streak.
import java.util.Scanner;
class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
int students;
int rank[];
public void save() {
Scanner sc = new Scanner(System.in);
System.out.println("Type in number of students");
students = sc.nextInt();
name = new String[students];
korean = new int[students];
math = new int[students];
english = new int[students];
sum = new int[students];
average = new double[students];
rank = new int[students];
for (int i = 0; i < students; i++) {
System.out.println("Type name");
name[i] = sc.next();
System.out.println("Type Korean score");
korean[i] = sc.nextInt();
System.out.println("Type math score");
math[i] = sc.nextInt();
System.out.println("Type English score");
english[i] = sc.nextInt();
sum[i] = korean[i] + math[i] + english[i];
average[i] = sum[i] / 3.0;
}
}
int stu() {
return students;
}
int[] sum() {
return sum;
}
}
class DataOutput {
DataInput data = new DataInput();
int sNum;
int[] rrank, sum;
DataOutput(int students, int[] sum) {
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
void ranker() {
int cnt = 1;
for (int i = 0; i < sNum; i++) {
for (int j = 0; j < sNum; j++) {
if (sum[i] < sum[j]) {
cnt++;
}
}
rrank[i] = cnt;
cnt = 1;
}
}
}
public class Score {
public static void main(String[] args) {
DataInput data = new DataInput();
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
data.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean math English \t sum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < data.stu(); i++) {
System.out.println(data.name[i] + "\t\t" + data.korean[i] + " "
+ data.math[i] + " " + data.english[i] + "\t"
+ data.sum[i] + " " + data.average[i] + " "
+ out.rrank[i]); // this is where i get an Exception
}
}
}
So, this is my program for getting ranks of students. But somehow when I run the code, I keep getting "OutOfBoundaryException". I checked my code, and realized that when I instantiate a new instance of DataOutput, it creates all new data. So I tried to fix this by setting a constructor. However I still can't solve this matter. I know that I can put the ranker method into DataInput class, and problem will be easily solved however I really want to keep DataOutput class.
Thank you for your time.
PS: Exception is thrown on line 98, out.rrank[i]
Your students field isn't set until the save() method is called. The value of sNum in main is then 0.
Change the order in main to:
DataInput data = new DataInput();
data.save();// <--
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
out.ranker();
the problem was that you initialize the rank[] before creating students, As soultion I suggest you to initialize after collection students/scores
public void init(int students, int[] sum){
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
And update main()
DataOutput out = new DataOutput();
data.save();
int sNum = data.stu();
int[] sum = data.sum();
out.init(sNum, sum);
out.ranker();
package ooptutorial;
public class ShoppingTest {
//name of file must be same as name of method
public static void main(String[] args) {
Shopping firstClient = new Shopping();
int[] pricelist = {299,399,499};
for (int i = 0; i < pricelist.length; i++){
firstClient.Basket(pricelist[i]);
}
System.out.println("The Total Price of your Item is : "
+ firstClient.r);
System.out.println("The Total Price with VAT : "
+ firstClient.TotalPrice());
firstClient.DailyIncome(firstClient.TotalPrice());
Shopping secondClient = new Shopping();
int[] pricelist2 = {599,159,459};
for(int i = 0; pricelist2.length; i++){
secondClient.Basket(pricelist2[i]);
}
System.out.println("The Total Price of your Item is : "
+ secondClient.r);
System.out.println("The Total Price with VAT : "
+ secondClient.TotalPrice());
secondClent.DailyIncome(secondClient.TotalPrice());
System.out.println("The Daily Income : "
+ secondClient._dailyIncome);
}
}
[ed: artificial break added]
class Shopping{
int r = 0;
final int VAT_VALUE = 17;
static int DailyIncome = 0;
int Basket(int ItemPrice){
r = ItemPrice;
return r;
}
int TotalPrice(){
return ((r * VAT_VALUE) / 100) + r;
}
public static int DailyIncome(int income){
_dailyIncome += income;
return _dailyIncome;
}
}
You have an error on this line:
for(int i = 0; pricelist2.length; i++){
Because pricelist2.length is an int, not a boolean as required by Java syntax. Perhaps you meant:
for(int i = 0; i < pricelist2.length; i++){