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.
Related
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.
when I attempt to run this program it will accept the inputs but will only print out 0.0 0.0 0.0 for all prints. I need it to print the imputed numbers and then print the average to 2 decimal accuracy. Why is it only printing 0s and not the numbers put in
import java.util.Scanner;
import java.util.Arrays;
public class pcCalculate
{
double[] pcPrice = new double [10];
public static void main(String[] args)
{
Quiz input = new Quiz();
Quiz display = new Quiz();
Quiz avgCalc = new Quiz();
input.arrayInput();
display.displayPCPrices();
avgCalc.avgPCCalc();
}
public void displayPCPrices()
{
System.out.println(Arrays.toString(pcPrice));
}
public double avgPCCalc()
{
int sum = 0;
for (int i=0; i < pcPrice.length; i++)
{
sum = (int) (sum + pcPrice[i]);
}
double average = sum / (double)pcPrice.length;
return average;
}
public void arrayInput()
{
Scanner price = new Scanner(System.in);
System.out.println("Enter Prices");
pcPrice[0] = price.nextDouble();
pcPrice[1] = price.nextDouble();
pcPrice[2] = price.nextDouble();
pcPrice[3] = price.nextDouble();
pcPrice[4] = price.nextDouble();
pcPrice[5] = price.nextDouble();
pcPrice[6] = price.nextDouble();
pcPrice[7] = price.nextDouble();
pcPrice[8] = price.nextDouble();
pcPrice[9] = price.nextDouble();
}
}
Arrays are better in loops, in this case, I would to something like this:
import java.util.Scanner;
import java.util.Arrays;
public class pcCalculate {
double[] pcPrice = new double [10];
public static void main(String[] args){
Scanner price = new Scanner(System.in);
for(int i=0; i< pcPrice.length; i++){
System.out.print("Set Price " + (i + 1) + ":");
pcPrice[i] = price.nextDouble();
}
displayPCPrices();
System.out.println("The average is :" + avgPCCalc());
}
public void displayPCPrices()
{
System.out.println("The prices are: " + "\n");
for(int i = 0; i< pcPrice.length; i++){
System.out.print(pcPrice[i] + " ");
}
}
public double avgPCCalc()
{
double sum = 0;
for (int i=0; i < pcPrice.length; i++)
{
sum += pcPrice[i];
}
double average = sum / 10;
return average;
}
}
Call your displayPCPrices method from your main and pass in pcPrice as a parameter:
import java.util.Scanner;
import java.util.Arrays;
public class pcCalculate
{
public static void main(String[] args)
{
double[] pcPrice = new double [10];
Scanner price = new Scanner(System.in);
System.out.println("Enter Prices");
pcPrice[0] = price.nextDouble();
pcPrice[1] = price.nextDouble();
pcPrice[2] = price.nextDouble();
pcPrice[3] = price.nextDouble();
pcPrice[4] = price.nextDouble();
pcPrice[5] = price.nextDouble();
pcPrice[6] = price.nextDouble();
pcPrice[7] = price.nextDouble();
pcPrice[8] = price.nextDouble();
pcPrice[9] = price.nextDouble();
displayPCPrices(pcPrice);
}
public void displayPCPrices(Array pcPrice)
{
System.out.println(Arrays.toString(pcPrice));
}
public double avgPCCalc()
{
int sum = 0;
for (int i=0; i < pcPrice.length; i++)
{
sum = (int) (sum + pcPrice[i]);
}
double average = sum / (double)pcPrice.length;
return average;
}
}
EDIT: And just so you're aware, main(String[] args) is where your program will always start, from there you call other methods and do your work. Nothing else will be calling your main method.
EDIT2: If you'd like to have a conversation about your coding practices shoot me a message, I see you've changed your question and you're missing some basic concepts that would help you easily solve this issue.
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 have an assignment, I was wondering how I could go about using 2D arrays with another class, I have a class called Die that looks like this:
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Now in a main method i have to do the following
I have all the other parts done, I just cant seem to figure out this part.
My current code(Not started this part) is below
import java.util.Arrays;
import java.util.Scanner;
class ASgn8
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();
String[] playerNames = new String[playerCount];
int again = 1;
for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
playerNames[i] = scan.nextLine();
}
int randomNum = (int)(Math.random() * (30-10)) +10;
}
}
Do any of you java geniuses have any advice for me to begin?
Thanks!
Here is your main method, you just need to update your main method with this one,
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();
HashMap<String, ArrayList<Die>> hashMap = new HashMap<String, ArrayList<Die>>();
int again = 1;
for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
hashMap.put(scan.nextLine(),new ArrayList<Die>());
}
for(String key : hashMap.keySet()){
System.out.println(key + "'s turn....");
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
hashMap.get(key).add(d);
System.out.println("Want More (Yes/No) ???");
String choice = scan.next();
while(choice != null && choice.equalsIgnoreCase("YES")){
if(hashMap.get(key).size()>4){System.out.println("Sorry, Maximum 5-Try you can...!!!");break;}
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ;
hashMap.get(key).add(dd);
System.out.println("Want More (Yes/No) ???");
choice = scan.next();
}
}
for(String key : hashMap.keySet()){
System.out.println(key + " - " + hashMap.get(key));
}
}
EDITED
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt(); // get number of participant player...
scan.nextLine();
Die[] tempDie = new Die[5]; // temporary purpose
Die[][] finalDie = new Die[5][]; // final array in which all rolled dies stores...
String [] playerName = new String[playerCount]; // stores player name
int totalRollDie = 0; // keep track number of user hash rolled dies...
for(int i = 0; i < playerCount; i++) // get all player name from command prompt...
{
System.out.print("What is your name: ");
String plyrName = scan.nextLine();
playerName[i] = plyrName;
}
for(int i = 0; i < playerCount; i++){
System.out.println(playerName[i] + "'s turn....");
totalRollDie = 0;
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
tempDie[totalRollDie] = d;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
String choice = scan.next();
while(choice != null && choice.equalsIgnoreCase("YES")){
if(totalRollDie < 5){ // if user want one more time to roll die then first check whether alread user has rolled 5-time or not.
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ; // rolled and print whatever value get..
tempDie[totalRollDie] = dd;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
choice = scan.next();
}
}
finalDie[i] = new Die[totalRollDie];
for(int var = 0 ; var < totalRollDie ; var++){
finalDie[i][var] = tempDie[var]; // store Die object into finalDie array which can random number for all user..
}
}
for(int i = 0 ;i < playerCount ; i++){ // finally print whatever user's roll value with all try...
System.out.println(" --------- " + playerName[i] + " ------------ ");
for(Die de : finalDie[i]){
System.out.println(de);
}
}
tempDie = null;
}
When the program runs, it asks you to enter a product name and price, and then whenever you press -1 it will be stopped and display a list of the entered product and price. However, the problem is I wrote a selection sort algorithm to sort the list by PRICE in ascending order. The output is not what I expected. Have a look at "//Selection Sort" in this code
import java.util.Scanner;
public class ProductPrices {
private static Scanner keyboard = new Scanner(System.in);
private static Scanner key = new Scanner(System.in);
final static int arrayLength = 1000; //maximum array size
static float[] productPrice = new float[arrayLength]; //stores the prices of products
static String[] productName = new String[arrayLength]; //stores the names of products
public static void main(String[] args) {
System.out.println("SHOPPING. Press -1 to quit anytime.\n");
for(int i=0; i<arrayLength; i++) {
System.out.print("Product: ");
productName[i] = keyboard.nextLine();
if(productName[i].equals("-1"))
break;
System.out.print("Price: $");
productPrice[i] = key.nextFloat();
if(productPrice[i] < 0)
break;
}
System.out.println("\nList of the SHOPPING!\n---------------------");
for(int i=0; i<productPrice.length; i++) {
if(productName[i] == null || productName[i].equals("-1") || productPrice[i] < 0)
continue; // null arrays will not be displayed.
else {
// Selection sort
if(productPrice[i] > productPrice[i+1]) {
float temp = productPrice[i];
productPrice[i] = productPrice[i+1];
productPrice[i+1] = temp;
}
System.out.printf("Item: %s %.2f\n", productName[i], productPrice[i]);
}
}
}
}
For example
:::Input:::
Product: apple
Price: $2.35
Product: pie
Price: $1.36
Product: cereal
Price: $7.4
Product: -1
:::Output:::
Item: apple 1.36
Item: pie 2.35
Item: cereal 0.00
That is incorrect, it should be
Item: pie 1.36
Item: apple 2.35
Item: cereal 7.40
Basically you have implemented selection sort incorrectly. Here is the code to fix it, including a counter to count how many products have been entered (makes the implementation clearer). Also as the other post says, you do not swap the names in your example, only the prices. I think the following should work:
public static void main(String[] args) {
System.out.println("SHOPPING. Press -1 to quit anytime.\n");
int prodCount = 0;
for(int i=0; i<arrayLength; i++) {
System.out.print("Product: ");
productName[i] = keyboard.nextLine();
if(productName[i].equals("-1"))
break;
System.out.print("Price: $");
productPrice[i] = key.nextFloat();
if(productPrice[i] < 0)
break;
prodCount++;
}
System.out.println("\nList of the SHOPPING!\n---------------------");
for (int j = 0; j < prodCount-1; j++) {
int iMin = j;
for (int i = j+1; i < prodCount; i++) {
if (productPrice[i] < productPrice[iMin]) {
iMin = i;
}
}
if ( iMin != j ) {
float temp = productPrice[j];
productPrice[j] = productPrice[iMin];
productPrice[iMin] = temp;
String tempn = productName[j];
productName[j] = productName[iMin];
productName[iMin] = tempn;
}
}
for(int i=0; i<prodCount; i++) {
System.out.printf("Item: %s %.2f\n", productName[i], productPrice[i]);
}
}