I was having some trouble with a program where I am suppose to allow a user to enter any amount of numbers into a program until they do not want to anymore. The program then should calculate the average and maximum of the numbers inputed. Where did I go wrong?
import java.util.Scanner;
public class DataSet
{
//Instance Variables
private double newValue;
private double sum;
private int count;
Scanner scan = new Scanner(System.in);
//Constructors
public DataSet()
{
double newValue = 0;
double sum = 0;
int count = 0;
}
public void run()
{
}
public double getaddValueToSet()
{
System.out.println("Please enter a number");
newValue = scan.nextDouble();
count += 1;
return newValue;
}
public double getSum()
{
sum += newValue;
return sum;
}
public double getAverage()
{
double average;
average = sum/count;
return average;
}
public double getMaximum()
{
double max=newValue;
if(newValue >= max)
{
max = newValue;
}
return max;
}
public String toString()
{
String str;
str = "Average: " + getAverage() + "\n" +
"Maximum: " + getMaximum();
return str;
}
}
import java.util.Scanner;
public class DataSetRunner
{
public static void main(String [] args)
{
String answer = "yes";
Scanner scan = new Scanner(System.in);
{
System.out.println("Do you want to enter another number?");
answer = scan.next();
}
while(answer.equals("yes"))
{
DataSet d1 = new DataSet();
double sum, number;
d1.run();
number = d1.getaddValueToSet();
sum = d1.getSum();
answer = scan.nextLine();
System.out.println(d1);
}
}
}
DataSet d1 = new DataSet();
do {
System.out.println("Do you want to enter another number?");
answer = scan.next();
if (answer.equalsIgnoreCase("YES")) {
double sum, number;
d1.run();
number = d1.getaddValueToSet();
sum = d1.getSum();
answer = scan.nextLine();
System.out.println(d1);
} else {
break;
}
} while (true);
Related
I am trying to populate my array with user input; however, I cannot get it to properly work. I am trying to get an int for the user for the number of products they want to enter. Then I want to populate the array with more user input of actual products (Strings) based on the number of products they said they wanted to enter. This is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class Practice {
public static void main(String[] args) {
bannerPrinter();
getNum();
int num = 0;
ArrayList<String> products = productBuilder(num);
boolean productGuess = getOrder(products);
if (productGuess) {
double price = getPrice();
double tax = getTax(price);
double total = getTotal(tax, price);
printTotal(total);
}
else {
System.out.print("Product not found.");
}
}
public static void bannerPrinter() {
System.out.println();
System.out.println("******************************************");
System.out.println("****** Welcome to my eCommerce app! ******");
System.out.println("******************************************");
System.out.println();
}
public static int getNum() {
Scanner scnr = new Scanner(System.in);
int num = 0;
System.out.print("Enter the number of products: ");
num = scnr.nextInt();
return num;
}
public static ArrayList<String> productBuilder(int num) {
Scanner scnr = new Scanner(System.in);
String arrayNames = "";
ArrayList<String> products = new ArrayList();
for (int i = 0; i <= num; i++) {
System.out.print("Enter the products: ");
products.add(arrayNames);
}
return products;
}
public static boolean getOrder(ArrayList<String> products) {
Scanner scnr = new Scanner(System.in);
String guess = "";
boolean productName = products.contains(guess);
System.out.print("Enter a product: ");
guess = scnr.nextLine();
if(productName) {
System.out.println();
System.out.print("This product has been found.");
System.out.println();
}
else {
System.out.println();
}
return productName;
}
public static double getPrice() {
double price = 0.0;
price = (int)(Math.random() * 100);
return price;
}
public static double getTax(double price) {
double tax = 0.0;
tax = price * 0.10;
return tax;
}
public static double getTotal(double price, double tax) {
double saleTotal = 0.0;
saleTotal = price + tax;
return saleTotal;
}
public static void printTotal(double saleTotal) {
System.out.println("You total is $" + saleTotal + "0");
}
}
I may not fully understand what you attempt to do but I did see some interesting lines... see my comments
public static ArrayList<String> productBuilder(int num) {
Scanner scnr = new Scanner(System.in);
String arrayNames = "";
ArrayList<String> products = new ArrayList();
for (int i = 0; i <= num; i++) {
System.out.print("Enter the products: ");
// I assume here scnr is supposed to read something
// and assign it to arrayNames?
products.add(arrayNames);
}
return products;
}
public static boolean getOrder(ArrayList<String> products) {
Scanner scnr = new Scanner(System.in);
String guess = "";
// I assume this line is supposed to be after
// guess = scnr.nextLine()?
boolean productName = products.contains(guess); // very confusing line
System.out.print("Enter a product: ");
guess = scnr.nextLine();
if(productName) {
System.out.println();
System.out.print("This product has been found.");
System.out.println();
}
else {
System.out.println();
}
return productName;
}
package homeWork;
public class ShoppingBag {
private int items;
private float totalRetailCost;
private float taxRate;
public ShoppingBag(float taxRate){
this.taxRate = taxRate;
items = 0;
totalRetailCost = 0.0f;
}
// Transformer
public void place(int numItems, float theCost){
items = items += numItems;
totalRetailCost += (numItems * theCost);
}
public int getItems(){
return items;
}
public float getRetailCost(){
return totalRetailCost;
}
public float getTotalCost(){
return totalRetailCost + (1 + taxRate);
}
public String toString(){
String result = "The bag contains " + items + " items";
result += "The retail cost of items is" + totalRetailCost;
result += "The total cost = " + getTotalCost();
return result;
}
}
package homeWork;
import java.util.*;
public class MainClass {
public static void main(String[] args){
Scanner conIn = new Scanner(System.in);
ShoppingBag sb = new ShoppingBag(0.06f);
int count = 0;
float cost = 0.0f;
System.out.print("Enter count (0 to stop):");
count = conIn.nextInt();
while(count != 0){
System.out.print("Enter cost: ");
cost = conIn.nextFloat();
sb.place(count, cost);
System.out.print("Enter count (0 to stop):");
count = conIn.nextInt();
}
}
}
I have tried all that I have found on here to return result after completion of input. Ive done what my book has shown me to do but I am not getting a result. Just a nudge in the right direction would be helpful.
You are no printing the object anywhere. Print the object
System.out.print(sb);
This question already has answers here:
Why does this Java division print out zero? [duplicate]
(5 answers)
Closed 7 years ago.
I am having problem with my getGPA() method it will only return a 0.00 value. I need for the function to calculate the GPA by dividing totalgradepoints by numberofclasses. I've tried everything and have no idea what the problem is. I am a complete beginner and trying to learn as I go this is for a class assignment so this is what we were instructed by our professor. I appreciate any advice on this thank you everyone.
import java.util.Scanner;
import java.text.DecimalFormat;
public class StudentGPAInfo {
static DecimalFormat f = new DecimalFormat ("0.00");
private double gpa;
private int totalgradepoints;
private int numberofclasses;
private String studentname;
public StudentGPAInfo() {
gpa = 0;
totalgradepoints = 0;
numberofclasses = 0;
studentname = null;
}
public void setName(String studentID){
studentname = studentID;
}
public void addClass(int classes, String gradepoint){
numberofclasses = numberofclasses += classes;
if (gradepoint.equalsIgnoreCase("A")) {
totalgradepoints += 4;
} else if (gradepoint.equalsIgnoreCase("B")) {
totalgradepoints += 3;
} else if (gradepoint.equalsIgnoreCase("C")) {
totalgradepoints += 2;
} else if (gradepoint.equalsIgnoreCase("D")) {
totalgradepoints += 1;
} else if (!gradepoint.equalsIgnoreCase("F")) {
System.err.println("Invalid input: " + gradepoint);
}
}
public String getName(){
return studentname;
}
public double getGPA(){
gpa = totalgradepoints / numberofclasses;
return gpa;
}
public void displayStudent(){
System.out.println("Student Name: " + studentname);
System.out.println("Total Grade Points: " + totalgradepoints);
System.out.println("Number of Class Credits: " + numberofclasses);
System.out.println(studentname + " Your GPA Average is: " + f.format(gpa));
}
}
public class GPAtest {
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String sName;
String grade;
int sClass;
String aClass;
StudentGPAInfo student = new StudentGPAInfo();
System.out.print("Please Enter Student Name: ");
sName = input.nextLine();
student.setName(sName);
do {
System.out.print("Please Enter Class credits: ");
sClass = Integer.parseInt(input.nextLine());
System.out.print("Please Enter Letter Grade: ");
grade = input.nextLine();
System.out.print("Another Class? ");
aClass = input.nextLine();
student.addClass(sClass, grade);
}
while (aClass.equalsIgnoreCase("y"));
student.displayStudent();
}
}
Please read how integer division works. if the numerator is less than the denominator, the result is zero. Make the numerator a double by casting.
Change this:
gpa = totalgradepoints / numberofclasses;
to this:
gpa = (double) totalgradepoints / numberofclasses;
New Class
public class NewClass {
private String accountNumber;
private String accountName;
private double balance;
public NewClass(String nameIn, String numberIn) {
accountNumber = numberIn;
accountName = nameIn;
balance = 0;
}
public String getAccountName() {
return accountName;
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public void deposit(double amountIn) {
balance = balance + amountIn;
}
public boolean withdraw(double amountIn) {
if (amountIn < 0 && balance < 0) {
return false;
} else {
balance = balance - amountIn;
return true;
}
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
}
Main Class
public static void main(String[] args) {
String accountName = "";
String accountNum = "";
Scanner sc = new Scanner(System.in);
boolean IsAccount = false;
NewClass[] accountList = new NewClass[3];
accountList[0] = new NewClass(accountName, accountNum);
accountList[1] = new NewClass(accountName, accountNum);
accountList[2] = new NewClass(accountName, accountNum);
int i = 0;
int count = 3;
while (i < count) {
double amount;
System.out.print("Enter the account name: ");
accountName = sc.next();
accountList[i].setAccountName(accountName);
System.out.println("Enter the account number: ");
accountNum = sc.next();
accountList[i].setAccountNumber(accountNum);
System.out.print("Enter amount to deposit: ");
amount = sc.nextDouble();
accountList[i].deposit(amount);
System.out.print("Enter amount to withdraw: ");
amount = sc.nextDouble();
accountList[i].withdraw(amount);
i++;
}
while (i < count) {
System.out.println(accountList[i].getAccountNumber());
System.out.println(accountList[i].getAccountName());
System.out.println(accountList[i].getBalance());
}
}
I am new to java programming and am having trouble with my bank account program. The output is to show three accounts each containing a name, account number and balance. This i cant get to show. Any help would be greatly appreciated. Thank You.
It looks like you don't reset i back to 0 before the loop that's supposed to print the output, which means that i==count due to the previous loop, so the loop that prints the output is never entered.
Here's what you have to fix:
int i = 0; // add this
while (i < count){
System.out.println(accountList[i].getAccountNumber());
System.out.println(accountList[i].getAccountName());
System.out.println(accountList[i].getBalance());
i++; // add this too
}
Of course you can make your code more elegant with the enhanced for loop :
for (NewClass account : accountList) {
System.out.println(account.getAccountNumber());
System.out.println(account.getAccountName());
System.out.println(account.getBalance());
}
I'm attempting to call a method in order to calculate average (calcavgnow).. I'm trying to have it calculate the average of all the numbers in the array and return the average to the caller. I'm hoping it can deal with any size array. I tried attempting below.. can anyone help me figure out what I am doing wrong?
import javax.swing.JOptionPane;
public class sdasfs {
public static void main(String[] args) {
double total = 0;
double SelectNumber = 0;
int a = 0;
double calcavgnow = 0;
do {
try {
String UserInput = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
SelectNumber = Integer.parseInt(UserInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
} while (SelectNumber < 1);
double Numbers[] = new double[(int) SelectNumber];
for (a = 0; a < Numbers.length; a++) {
String EnterNumber = JOptionPane.showInputDialog("Please enter a number.");
Numbers[a] = Double.parseDouble(EnterNumber);
total += Numbers[a];
calcavgnow = total / SelectNumber;
}
JOptionPane.showMessageDialog(null, getTotal(numbers) + " divided by " + Numbers.length + " is " + getAvg(Numbers));
}
//Create method in order to calculate calcavgnow
public static double getAvg(int numbers[]){
return (double)getTotal(numbers)/numbers.length;
}
public static int getTotal(int numbers[]){
int total = 0;
for(int i:numbers)
total +=i;
return total;
}
}// end class
Have a separate method to calculate average. Don't do everything inside the same method. Learn to modularize your code. So others can easily get adopt to your code.
public static double getAvg(double numbers[]){
return getTotal(numbers)/numbers.length;
}
public static double getTotal(double numbers[]){
double total = 0;
for(double i:numbers)
total +=i;
return total;
}
import javax.swing.JOptionPane;
public class AvgCalculator {
public static void main(String[] args) {
double total = 0;
double SelectNumber = 0;
int a = 0;
double calcavgnow = 0;
do {
try {
String UserInput = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
SelectNumber = Integer.parseInt(UserInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
} while (SelectNumber < 1);
double Numbers[] = new double[(int) SelectNumber];
for (a = 0; a < Numbers.length; a++) {
String EnterNumber = JOptionPane.showInputDialog("Please enter a number.");
Numbers[a] = Double.parseDouble(EnterNumber);
total += Numbers[a];
}
calcavgnow = total / SelectNumber;
JOptionPane.showMessageDialog(null, "The average entered is " + calcavgnow);
}
}