Scanner sam = new Scanner(System.in);
public class balance {
public double[] returnarray1() {
System.out.print("Enter account balances seperated by coma:");
String[] temp = sam.nextLine().split(",");
double[] bal = new double[temp.length];
for(int i=0; i<temp.length; i++) {
bal[i] = Double.parseDouble(temp[i]);
}
return bal;
}
}
public class interest {
public double[] returnarray2() {
balance bl = new balance();
double[] temp = bl.returnarray1();
double[] inter = new double[temp.length];
for(int i=0;i>temp.length;i++) {
inter[i] = temp[i] * 0.02/12;
}
return inter;
}
}
public static void main(String[] args) {
samiksood ss = new samiksood();
balance bl = ss.new balance();
interest it = ss.new interest();
double[] balance = bl.returnarray1();
double[] interest = it.returnarray2();
for(int i =0; i<balance.length;i++) {
System.out.print("Account "+ i +1);
System.out.print(balance[i]);
System.out.println(interest[i]);
}
}
when i run it it asks me for output twice which should not happen why is my class repeating?
this program is supposed to seperate a single output into multiple different ones and be placed into a array which is then converted to double the balance is then returned. similarly interest is calculated by preforming calculations on each balance array and returned.they are called into the main method and each array is supposed to be printed.
You both call returnarray1 in your main and inside returnarray2 so that's why returnarray1 is executed twice.
Assuming you want to use the result of the first time in the second time you can change
public double[] returnarray2() {
balance bl = new balance();
double[] temp = bl.returnarray1();
double[] inter = new double[temp.length];
for (int i = 0; i > temp.length; i++) {
inter[i] = temp[i] * 0.02 / 12;
}
return inter;
}
to
public double[] returnarray2(double[] temp) {
balance bl = new balance();
double[] inter = new double[temp.length];
for (int i = 0; i > temp.length; i++) {
inter[i] = temp[i] * 0.02 / 12;
}
return inter;
}
and
double[] interest = it.returnarray2();
to
double[] interest = it.returnarray2(balance);
I believe there is also a small bug at this line
for (int i = 0; i > temp.length; i++) {
because it needs to be
for (int i = 0; i < temp.length; i++) {
There's a lot more room for improvement, because a lot of your code is not according to conventions, but it should work at least.
Related
class Account {
int accountNumber;
int balance;
Account(int accountNumber, int balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
Account() {
int accountNumber = 0;
int balance = 0;
}
}
public class HW2 {
public static void main(String[] args) {
Account[] oneH = new Account[100];
accountNumberGenerator(oneH);
balanceGenerator(oneH);
for(int i = 0; i < oneH.length; i++){
System.out.println(oneH[i].accountNumber + " " + oneH[i].balance);
}
}
public static void accountNumberGenerator(Account[] arr){
Account one = new Account();
for(int i = 0; i < arr.length; i++){
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
public static void balanceGenerator(Account[] arr){
int min = 100;
int max = 100000;
for(int i = 0; i < arr.length; i++){
Random rand = new Random();
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
arr[i].balance = random_int;
}
}
}
I'm making an object array but it's not working.
Whenever I print each values of the Account array it just shows the 100 and random number that generated last for all values.
I'm not sure what is the problem.
public static void accountNumberGenerator(Account[] arr){
Account one = new Account();
for(int i = 0; i < arr.length; i++){
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
In this method you are only creating one single instance of Account and assigning it to every element of the array.
You need to create a brand new object each iteration of your loop.
public static void accountNumberGenerator(Account[] arr){
for(int i = 0; i < arr.length; i++){
Account one = new Account();
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
Here's a simple way to create 100 accounts.
public class Main {
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
Account[] oneH = new Account[100];
for(int i=0; i<oneH.length; i++)
oneH[i] = new Account(i, r.nextInt(99900)+100);
for(int i = 0; i < oneH.length; i++)
System.out.printf("%3d%7d\n", oneH[i].accountNumber, oneH[i].balance);
}
}
Place code to print elements from arr_param
Place code to sort elements in arr_param in ascending order of fahrenheit temperature
Place code to print out elements from arr_param with temperatures > 90 deg. F
There is a private class to do the conversions from F to C to K.
public class Temperature {
public Temperature(double p_fahren) {
fahrenTemp = p_fahren;
}
public void setFahrenheit(double p_fahren) {
fahrenTemp = p_fahren;
}
public double getFahrenheit() {
return fahrenTemp;
}
public double getCelsius() {
double celsius_temp;
celsius_temp = (5.0 / 9.0) * (fahrenTemp - 32.0);
return celsius_temp;
}
public double getKelvin() {
double kelvin_temp = ((5.0 / 9.0) * (fahrenTemp - 32.0)) + 273.0;
return kelvin_temp;
}
public String toString() {
String ret_val = "";
ret_val = String.format("%.1f F, %.1f C, %.1f K",fahrenTemp, getCelsius(), getKelvin());
return ret_val;
}
}
We are not allowed to use the Arrays Util
public class Asn5_Test_Temperature
{
public static void main(String args[])
{
Temperature arr_temps [] =
{
new Temperature(90), new Temperature(75), new Temperature(65), new Temperature(95),
new Temperature(89), new Temperature(67), new Temperature(77), new Temperature(71),
new Temperature(55), new Temperature(65), new Temperature(64), new Temperature(74),
new Temperature(91), new Temperature(86), new Temperature(78), new Temperature(73),
new Temperature(68), new Temperature(94), new Temperature(91), new Temperature(62)
};
print_array("After population", arr_temps);
sort_array(arr_temps);
print_array("After sort", arr_temps);
print_days_above_90(arr_temps);
}
public static void print_array(String message, Temperature arr_param[])
{
System.out.println("----" + message + "---");
for(Temperature oneElem : arr_param)
System.out.print(oneElem + "\t");
System.out.println();
}
public static void sort_array(Temperature arr_param[])
{
int min;
int temp = 0;
for(int i = 0; i < arr_param.length; i++)
{
min = i;
for(int j = i + 1; j < arr_param.length; j++)
{
if(arr_param[j] < arr_param[min])
{
min = j;
}
}
temp = arr_param[i];
arr_param[i] = arr_param[min];
arr_param[min] = temp;
}
for(int i = 0; i < arr_param.length; i++)
{
System.out.print(arr_param[i] + " ");
}
}
public static void print_days_above_90(Temperature arr_param[])
{
System.out.println("----Days over 90 F---");
for(int i = 0; i > 90; i++)
{
System.out.print(arr_param[i] + " ");
}
}
}
The program is supposed to print out the array, then in ascending order, then only the ones that are above 90 degrees F
I am having issue getting the sort code to work and getting it to sort the temperatures over 90 degrees F. I get three errors in my code: error: bad operand types for binary operator '<' and error: incompatible types: Temperature cannot be converted to int and error: incompatible types: int cannot be converted to Temperature
For this section call the getFahrenheit method to compare:
if(arr_param[j].getFahrenheit() < arr_param[min].getFahrenheit())
{
min = j;
}
For this section.. use the toString method. The purpose of the toString method is to convert your object data to a readable String.
for(int i = 0; i < arr_param.length; i++)
{
System.out.print(arr_param[i].toString() + " ");
}
I hope this helps and let me know if you have any questions.
I'm trying to get the average score from objects but can't think of a good way to do it.
I have 10 objects and they all have their own score associated with it.
I created setter and getter class where it would get the average, but the problem I run into is that I would create something like this so that even if I do put object's score into this method the holder will go back to 0.
public double getAverage() {
return average;
}
public void setAverage(double studentScore) {
double holder = 0;
average = holder + studentScore;
holder = average;
this.average = studentScore;
}
I was also thinking of just creating setter and getter methods for every single score, but that takes up lots of space and I figured there has to be a better way to do it.
Here is a snippet of the code I'm using in the main method
public static void main(String[] args) {
final String STUDENT_INFO = "HW1_Students.txt";
List<GradeInfo> list = new ArrayList<GradeInfo>();
Scanner inputFile = null;
GradeInfo person1 = new GradeInfo();
GradeInfo person2 = new GradeInfo();
GradeInfo person3 = new GradeInfo();
GradeInfo person4 = new GradeInfo();
GradeInfo person5 = new GradeInfo();
GradeInfo person6 = new GradeInfo();
GradeInfo person7 = new GradeInfo();
GradeInfo person8 = new GradeInfo();
GradeInfo person9 = new GradeInfo();
GradeInfo person10 = new GradeInfo();
list.add(person1);
list.add(person2);
list.add(person3);
list.add(person4);
list.add(person5);
list.add(person6);
list.add(person7);
list.add(person8);
list.add(person9);
list.add(person10);
try {
inputFile = new Scanner(new File(STUDENT_INFO));
}
catch (FileNotFoundException ex) {
System.out.println("\n *** Exception occured while opening "
+ ex.getMessage() + " ***");
System.exit(-1);
}
readData(inputFile, STUDENT_INFO, person1, person2, person3, person4,
person5, person6, person7, person8, person9, person10);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
Any advice would be greatly appreciated, thanks.
public void setAverage(ArrayList<GradeInfo> grades) {
double average = 0;
for(int i = 0; i < grades.size(); i++){
average += grades.get(i);
}
average = average / grades.size();
this.average = average;
}
I hope this is what you meant to do....... This method will take your Arraylist, and set the correct average score in your wired "setter and getter class".
I dont really understand what you are trying to do here:
public void setAverage(double studentScore) {
double holder = 0;
average = holder + studentScore;
holder = average;
this.average = studentScore;
}
But its logical that holder will be reset to 0 because you initialize it and set it to 0 in the beginnig of your function, or do i misunderstand this?
Just create holder outside of your setter.
And if you just want to have the average of a bunch of values just add all the values together and divide the result by the number/quantity of your values.
For example:
public double getAverage(List <GradeInfo> l){
int totalAmount;
for(i = 0; i < l.size(); i++){
totalAmount += l.get(i);
}
double average = totalAmount / l.size();
return average;
}
This is probably not applicable to your program insofar as you probably have at least one positive value going into your calculation. But I could see a professor taking off points for it if he is testing all possible cases.
If you do follow the advice of Sand, be sure to check that the size of the arraylist is greater than zero before you use the size in the average calculation. You cannot divide by zero in Java. Instead, do this:
public double getAverage(List <GradeInfo> l){
int totalAmount;
for(i = 0; i < l.size(); i++){
totalAmount += l.get(i);
}
if (l.size() > 0) {
double average = totalAmount / l.size();
return average;
else {
double average = 0;
}
return average;
}
I'm new to Java. I'm getting an "illegal start of expression error". I've been searching for answers and cant find out, if I'm using the brackets incorrectly or not but I've tried it without the brackets and with them and cant seem to get past this 1 error. I could use some assistance.
Thank you :)
public class LIANGLAB1
{
public static void main(String[] argv){
gasStation A = new gasStation(3.39, 3.49);
gasStation B = new gasStation(3.19, 3.39);
A.sellregular(10); A.sellregular(10);
B.sellregular(11); B.sellregular(12);
if (A.moreprofit(B)) System.out.println("station A is more profitable");
else System.out.println("station B is more profitable");
gasStation G[] = new gasStation[10];
for(int i=0;i<10;i++) G[i] = new gasStation(3.19,3.39);
{gasStation highest =G[0];}
for (int i=1;i<10;i++)
{if (G[i].moreprofit(highest)) highest = G[i];
{System.out.println("highest total sales is" +highest.sales+ );}
//ERROR IS HERE
}
}
}
class gasStation
{
double regularprice;
double superprice;
double sales;
public gasStation(double r, double s)
{regularprice = r; superprice = s; sales = 0;}
public void sellregular(double gallons)
{sales += regularprice * gallons;}
public void sellsuper(double gallons)
{sales += superprice * gallons;}
public void gouge()
{superprice *= 2; regularprice *=2;}
public boolean moreprofit(gasStation other)
{return sales > other.sales;}
}
Learn the Java coding standards. You aren't following them. It makes your code hard to read.
Good names matter. Put more thought into naming classes, methods, and variables. Your aim should be easy understanding and readability.
This code compiles and runs fine.
public class LIANGLAB1 {
public static void main(String[] argv) {
GasStation gasStationA = new GasStation(3.39, 3.49);
GasStation gastStationB = new GasStation(3.19, 3.39);
gasStationA.sellRegular(10);
gasStationA.sellRegular(10);
gastStationB.sellRegular(11);
gastStationB.sellRegular(12);
if (gasStationA.hasMoreProfit(gastStationB)) System.out.println("station A is more profitable");
else System.out.println("station B is more profitable");
GasStation arrayOfGasStations[] = new GasStation[10];
for (int i = 0; i < 10; i++) {
arrayOfGasStations[i] = new GasStation(3.19, 3.39);
}
GasStation highest = arrayOfGasStations[0];
for (int i = 1; i < 10; i++) {
if (arrayOfGasStations[i].hasMoreProfit(highest)) {
highest = arrayOfGasStations[i];
}
}
System.out.println("highest total sales is" + highest.sales);
}
}
class GasStation {
double regularprice;
double superprice;
double sales;
public GasStation(double r, double s) {
regularprice = r;
superprice = s;
sales = 0;
}
public void sellRegular(double gallons) {
sales += regularprice * gallons;
}
public void sellSuper(double gallons) {
sales += superprice * gallons;
}
public void gouge() {
superprice *= 2;
regularprice *= 2;
}
public boolean hasMoreProfit(GasStation other) {
return sales > other.sales;
}
}
Change this
for(int i=0;i<10;i++) G[i] = new gasStation(3.19,3.39);
{gasStation highest =G[0];}
to this
for(int i=0;i<10;i++){
G[i] = new gasStation(3.19,3.39);
gasStation highest =G[0];
}
And to improve code readability, you should really consider sticking to one statement per line.
EDIT:
for (int i=1;i<10;i++)
{if (G[i].moreprofit(highest)) highest = G[i];
{System.out.println("highest total sales is" +highest.sales+ );}//ERROR IS HERE
}
}
change it to:
for (int i=1;i<10;i++){
if (G[i].moreprofit(highest))
highest = G[i];
}
System.out.println("highest total sales is" +highest.sales);
There is no reason to open curly braces for single println statements.
Can you give me a hint on what I'm doing wrong with my average in the average method? I'm trying to call the method in the read scores.I'm trying to get the average of the scores I have in my input.txt file.
import java.io.*;
import java.util.*;
public class FindGrade {
public static final int NUM_SCORE_TYPES = 5;
public static void main(String[] args) {
Scanner scan = null;
int[] quizArray = null;
int[] labArray = null;
int[] attendance = null;
int[] midterms = null;
int quizgrade =0;
int labgrade=0;
int attendance_1=0;
int midterms_1 =0;
String name;
try {
scan = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
// each iteration is for single exam type (ie: Quizzes is the 1st one)
for (int i = 0; i < NUM_SCORE_TYPES; i++) {
name = scan.next();
int numScores = scan.nextInt();
int maxGrade = scan.nextInt();
if (name.equals("Quizzes")) {
quizArray = new int[numScores];
readScores(quizArray, numScores, scan);
}
else if (name.equals("Labs")) {
labArray = new int[numScores];
readScores(labArray, numScores, scan);
}
else if (name.equals("Lab_attendance")) {
attendance = new int[numScores];
readScores(attendance, numScores, scan);
}
else if (name.equals("Midterms")) {
midterms = new int[numScores];
readScores(midterms, numScores, scan);
}
}
}
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
}
public static void average(double [] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}
In any case, you can't directly call it with the arrays that you are creating there. Because the arrays are of type int, but the average-method requires a double array. When you change this, you can call the method like this...
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
average(scoreArray, numScores); // <----- Call it here
}
public static void average(int[] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}