So I would like to start out by telling you that I am learning Java on my own and you guys are the nearest thing I have to teachers. So thank you so much for putting up with my simple and obvious question. I am just trying to learn. Once again I am getting an error that for the life of me I cannot figure out.
Here is the error:
Exception in thread "main" java.lang.NullPointerException
at Advisor_score.All_user.Score1(All_user.java:13)
at Advisor_score.All_user.main(All_user.java:28)
Here is my code for the ratings class:
package Advisor_score;
public class Rating {
double [] Ratings;
double sum=0;
double raw_advisor;
double advisor_score;
public Rating (double [] x){
Ratings = x;
}
public double Score(){
for(int i=2;i<Ratings.length;i++){
sum+=Ratings[i];
}
raw_advisor=((sum-(3*(Ratings.length-2)))/4);
advisor_score= 2.5+(2.5*(1-Math.pow(Math.E, -.5*raw_advisor)));
return advisor_score;
}
Here is my code for the other class:
package Advisor_score;
public class All_user{
double [] ADVISOR_SCORE;
Rating [] All_users;
double score;
public All_user(Rating...args){
All_users=args;
}
public double [] Score1(){
for (int j = 0;j<All_users.length;j++){
score=All_users[j].Score();
ADVISOR_SCORE[j]=score;
}
return ADVISOR_SCORE;
}
public void print(){
for(int i = 0;i<ADVISOR_SCORE.length;i++){
System.out.println(ADVISOR_SCORE[i]);
}
}
public static void main(String[] args){
double p1_1[] = {101,1,5,5,5};
double p2_1[] = {101,1,1,2,3};
Rating d = new Rating(p1_1);
Rating e = new Rating(p2_1);
All_user all=new All_user(d, e);
all.Score1();
all.print();
}
}
Again, I cannot thank you guys enough at StackOverflow. Your help has been invaluable!!
You have not initialized the ADVISOR_SCORE and All_users arrays, but you do try to assign values and use them. When you declare
double[] ADVISOR_SCORE; // this is null until assigned
At some point, it needs to be assigned
ADVISOR_SCORE = new double[size];
this variable:
double [] ADVISOR_SCORE;
hasn't been initialized... and therefore it's null.
ADVISOR_SCORE has not been initialised
Jeff Storey provided the best explanation, here are two semi-related tips I had to learn when learning Java:
1) Once you initialize that array
ADVISOR_SCORE = new double[size];
You cannot modify the array's length unless you re-initialize it. Students often will try to add another value onto the end of an array or otherwise "grow" it somehow. If this is something you need, checkout Vector and ArrayList.
2) Java coding conventions are to capitalize class names...
public class Rating {
...but leave the first letter of method names in lower case.
public double [] getFirstScore() {
It'll help readability when others start working on your code.
Happy coding!
Related
Hope you guys can help me (I know this is alot im sorry)
below is my Customer class
import java.util.*;
public class Customer{
//fields
int id;
String firstName;
String lastName;
double lastYear;
ArrayList<Order> orderList = new ArrayList<>();
//4 arg constructor
public Customer(String fN,String lN,int i){
id=i;
fN=firstName;
lN=lastName;
this.orderList=orderList;
}
//toString method
public String toString(){
return "Customer Information:"+"First Name: "+ firstName +" Last Name: "+ lastName+ "ID code"+ id;
}
//AveragePayment method
public void AveragePayment(){
double total=0;
for(Order currentObj : orderList){
total=total+currentObj.getTotalCost();
}
double avgCost = total / orderList.size();
}
}
this is my Order.java class
public class Order{
//fields
double salesTaxRate;
double price;
double shippingCost;
double total;
double salesTax;
//1 arg constructor
public Order(double set1){
salesTaxRate=set1;
price=0;
shippingCost=0;
total=0;
salesTax=0;
}
//setPrice method
public void setPrice(double p){
price=p;
salesTax=salesTaxRate*price;
double subTotal=(price+salesTaxRate);
if(subTotal<50){
shippingCost=0.8*subTotal;
}
else{
shippingCost=0;
}
}
//getTotalCost method
public double getTotalCost(){
return total;
}
//setTotalCost
public void setTotal(double total){
this.total=total;
}
}
finally the tester
import java.text.NumberFormat;
public class Tester
{
public static void main(String[] args)
{
double avgPurchase;
Order[] lastYear = new Order[4];
// I bought most stuff in Pennsylvania but..
lastYear[0] = new Order(0.06);
lastYear[1] = new Order(0.06);
// I did send one thing to my mom in New York City and had to pay their sales tax...
lastYear[2] = new Order(0.09);
lastYear[3] = new Order(0.06);
lastYear[0].setPrice(57.93);
lastYear[1].setPrice(257.93);
lastYear[2].setPrice(100.30);
lastYear[3].setPrice(15.67);
Customer me = new Customer("Christian" , "Turner" , 12321, lastYear);
// okay! ready to go !
System.out.println( me );
avgPurchase = me.AveragePayment();
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println( "has spent an average of " + fmt.format(avgPurchase) + " per purchase.");
}
}
im getting an error in my tester that says
Customer cannot be applied to given types;
`Customer me = new Customer("Christian" , "Turner" , 12321, lastYear)`;
and also
Tester.java:32: error: incompatible types: void cannot be converted to double
avgPurchase = me.AveragePayment()
As you can see im specifically instructed to modify my Customer class's constructor to allow the user to initalize the array. I believed i did just that however the tester is unable to populate the array. I believe i need an extra argument to specifically initalize the array however I'm confused on how to do so. Also I believe my AveragePayment method in my customer class is wrong because the data type is unable to convert from double to void, but i dont know how to go about fixing this. As this is an assignment i am unable to modify the tester in anyway Any help would be appreciated! I know its gotta be some little error im missing in the AveragePayment method, but the constructor error im literally clueless on how to solve it
Since this is a homework assignment I don't want to give you the answer, however most of this code is close to correct and you are not that far from solving the assignment. I am going to try and break down some areas that are likely giving you issues.
To start, look at my comment about the two errors you are getting, hopefully that will help, if not you are welcome to respond and I can try and provide more clarity.
Order List uses the wrong type
Customer.java should use Order[] instead of ArrayList<Order>. Since you cannot modify Tester.java, it is a good idea to match type you are given. Look at how Order[] lastYear is initialized in tester.java
Constructor Issues
There is an additional issue with the constructor besides the incorrect number of arguments you mentioned in your question. Take a close look at how you are doing the assignments inside this constructor. Think about which variable needs to change, put that one on the left and side so it gets assigned a new value
//4 arg constructor
public Customer(String fN,String lN,int i){
id=i;
fN=firstName;
lN=lastName;
this.orderList=orderList;
}
setPrice method
Take a look at your setPrice() method in Order.java. What should the outcome of this method be. You are doing math correctly, but this method will not provide the outcome you are hoping for.
//setPrice method
public void setPrice(double p){
price=p;
salesTax=salesTaxRate*price;
double subTotal=(price+salesTaxRate);
if(subTotal<50){
shippingCost=0.8*subTotal;
}
else{
shippingCost=0;
}
}
Im new with programming and have been trying to solve this problem for a while, been looking at similar questions but im not understanding whats wrong with my code.
So the assignment is to write a method that takes an array that has three doubles in it. Then return the average of the three doubles. Then write a main that should call and then type the method.
Thanks!
Main
public class Tenta131031upg1main {
public static void main (String[]args){
double []arr ={3.15, 4.41, 7.64};
Tenta131031upg1.genomsnitt(double arr[]);
System.out.println(Tenta131031upg1.genomsnitt(arr));
}
}
Class
public class Tenta131031upg1 {
static int i =0;
static double sammanlagd=0;
static double genomsnitt=0;
public static double genomsnitt(double[]arr){
while(i<arr[].length()){
sammanlagd = sammanlagd + arr[i];
i++;
}
genomsnitt = sammanlagd/arr[].length();
return genomsnitt;
}
}
PS. they are two different classes with 1 main and 1 class they are not in the same file!
The error:
Syntax error on token "double", new expected
Variable must provide either dimension expressions or an array initializer
arr cannot be resolved to a type
at Tenta131031upg1main.main(Tenta131031upg1main.java:7)
Please correct the two lines in the first file like this:
double[] arr ={3.15, 4.41, 7.64};
Tenta131031upg1.genomsnitt(arr);
You were creating a new, empty array in the second line.
Try this:
Main
public class Tenta131031upg1main {
public static void main (String[]args){
double[] arr ={3.15, 4.41, 7.64};
System.out.println(Tenta131031upg1.genomsnitt(arr));
}
}
Class
public class Tenta131031upg1 {
static int i =0;
static double sammanlagd=0;
static double genomsnitt=0;
public static double genomsnitt(double[] arr){
while(i<arr.length){
sammanlagd = sammanlagd + arr[i];
i++;
}
genomsnitt = sammanlagd/arr.length;
return genomsnitt;
}
}
Changes are:
change in method call
arr.length instead of arr[].length()
Hi and thanks for at least visiting.
I promise I've checked every question that's seemed relevant to what I need to do. I've tried every solution on the site and most on Google.
What I'm attempting to do is create a personality quiz that matches you to a certain trait. The desired program result is that the highest matched trait will display first. After the person tests, calculations are done to see what percentage a person is of each trait and that percentage is stored in doubles.
So I'm trying to order or sort an arraylist of objects based on this double. I've tried various strategies, but I'll give you the current two:
With Comparable
public static class results implements Comparable<results>
{
private double rPercent; //I've tried public and just leaving it double
public results(double percent)
{
this.rPercent = percent;
Percent*=100;
System.out.printf("You are %.2f," percent);
System.out.println();
}
public double getPercent()
{
return rPercent;
}
public int CompareTo(results Percent)
{
double p1 = (results Percent).getX();
double p2 = this.X - p1;
return (int)p2;
}
}
public static void main(String[] args) throws Exception
{
ArrayList<results> sortList = new ArrayList<results>();
sortList.add(new results(prcTrait1));
sortList.add(new results(prcTrait2));
sortList.add(new results(prcTrait3));
Collections.sort(sortList);
results beginResults = sortList.get(0);
results beginResults = sortList.get(1);
results beginResults = sortList.get(2);
//It prints out the traits in their original order. Always.
}
That's one solution I saw.
Then this is another thing I'm trying:
With Comparater
public class personalityQuiz
{
public double newPercent;
//. . .
public static class results
{
personalityQuiz v = new personalityQuiz();
//v for variable
//That and I wanted it to be short because I would be using it alot.
public results(double percent)
{
v.newPercent = percent;
percent*=100;
System.out.printf("You are %.2f", percent);
System.out.println();
}
}
public double getPercent
{
double xPercent = newPercent;
return xPercent;
}
public static void main(String[] args) throws Exception
{
ArrayList<results> sortList = new ArrayList<results>();
sortList.add(new results(prcTrait1));
sortList.add(new results(prcTrait2));
sortList.add(new results(prcTrait3));
Collections.sort(sortList, new Comparator<results>()
{
public int compare(results p1, results p2)
{
personalityQuiz v = new personalityQuiz();
double newP1 = p1.v.getPercent();
double newP2 = p2.v.getPercent();
if(newP1 < newP2)
{
return 1;
}
else if(newP2 < newP1)
{
return -1;
}
else
{
return 0;
}
});
results beginResults = sortList.get(0);
results beginResults = sortList.get(1);
results beginResults = sortList.get(2);
//still prints them in their original order
}
}
I apologize for the probable various mistakes in execution there.
I'm somewhat self-learning Java right now and what I know was basically self-taught as well.
Anyway, any help would be amazing.
And I'll try to be around to respond to any comments or answers quickly ^^~
In your first example, I think you missed a few things (and results should be Results, also CompareTo should be compareTo) -
public static class Results implements Comparable<Results>
{
private double rPercent; //I've tried public and just leaving it double
public Results(double percent)
{
this.rPercent = percent;
percent*=100;
System.out.printf("You are %.2f%n", percent);
}
public double getPercent()
{
return rPercent;
}
#Override
public int compareTo(Results result)
{
return new Double(getPercent()).compareTo(result.getPercent());
}
}
In your compare method, try Double.compare(double x, double y).
EDIT: Elliott Frisch expanded on that
I'm going to be honest and say some of your code was hard to follow, it would be beneficial for you to learn the 'standards' of the Java programming language, such as classes always starting with a capitol letter etc..
In your first example, the reason they were always coming out in the same order is probably because of a rounding error. When you're converting a double to a integer, it was most probably less than 1 (but greater than 0) in magnitude. Hence it was being rounded down (or up) to 0. Meaning that the collections API was not sorting them as there were being seen as 'equal'.
Your second example I was not able to follow, sorry.
-Thomas
Okay I have tried to write a simple Java code in BlueJ, that finds and prints the product of all the entries in data such as if data is {1,2,3,4} then the result will be 24.
And my code is below:
public class Product {
public static int[] product(int[] a) {
int [] s = new int[a.length];
for (int i =0; i< a.length; i++)
s[i] = a[i]*a[i];
return s; //the definition of your method...
}
public static void main(String[] args) {
//calling the method to seek if compiles
int[] results = Product.product(new int[] { 1,2,3,4 });
//printing the results
System.out.println(java.util.Arrays.toString(results));
}
}
The above code is giving me the square of each number, which is not what I want to have, somehow I have modify the code that the result will be 24 but I couldn't figure it out, anyone knows how to do it?
First of all, if you are first writing Java it is important to know that variable, function and class names are quite important. Please note that having Product.product() is not a good idea, since the function name is almost the same as the class name. Anyway, regarding your code. Your code is indeed returning the square of your input, what you would want is the following:
public class Product {
public static int getProduct(int[] input) {
int total = 1;
for (int v : input) {
total *= v;
}
return total;
}
}
This will return an integer value with the product of your input array. This also uses a for-each loop instead of a regular for-loop for readability. Also you don't need the index in this case. Good luck with it!
First, your product method needs to return an int rather than an int [].
You need to maintain the product as a variable. You can set it to 1 initially, and then multiply it by each element of the a array in turn; then you just return this value.
public class ClassName {
public static void main(String[] args) {
//code: depending on user input runs Methodname1();
}
public static void MethodName1 {
double kgs;
double totalIn;
//code: do/while try/catch etc.
double ImpToMetBmi;
double InchToMtrH;
InchToMtrH = totalIn*2.54/100;
ImpToMetBmi = (kgs/(InchToMtrH*InchToMtrH);
System.out.printf("\nYour BMI is: %.3f\n" ,ImpToMetBmi);
}
}
Really sorry for the long and badly written code. I think all code/layout must be seen to figure out the problem.
Errors I'm getting:
Exception...Uncompilable source code - variable totalIn might not have been initialized
Exception...Uncompilable source code - variable kgs might not have been initialized
This formula worked before I inserted do/while try/catch statements for exception handling.
I have spent hours reading about declaring and initilizing variables, local and class variables. I've tried a few different ways but nothing I try fixes the problem.
I'm confused as to what is causing this and how to fix it. I'd like to figure this out and understand the solution.
Where do I initialize 'totalIn' and 'kgs'? and What to I initialize them as?
These varialbles are populated by values inputted by the user through Scanner if that makes any difference.
Please help!
Here is an example that explains the cause you are getting and why you are getting that -
double test;
if( isTrue){
test = 2.0d;`enter code here`
}
// This will give you a error stating that test might have not initialized
double calculate = test * 5.0;
Reason is clear if condition in if block is true then the test value will be initialized with 2.0 other wise it will be uninitialized.
A quick fix to this might be initializing test to some value (may be 0).
Coming to you point, to initialize those variables you can do following things -
static double kgs;
static double totalIn;
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
kgs= sc.nextDouble;
totalIn = sc.nextDouble();
}
or pass them as method parameter like below -
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
double kgs = sc.nextDouble;
double totalIn = sc.nextDouble();
}
public void yourMethod(double kgs, double totalIn){
// do whatever you want with above passed variables
}
Declaration of MethodName1 method is wrong. You missed argument section. Change it to public static void MethodName1().
public class ClassName {
public static void main(String[] args) {
//code: depending on user input runs Methodname1();
}
public static void MethodName1(double KGS, double TOTAL) {
double kgs = KGS;
double totalIn = TOTAL;
//code: do/while try/catch etc.
double ImperialToMetricBmi;
double InchesToMtrHeight;
InchesToMtrHeight = totalIn*2.54/100;
ImperialToMetricBmi = (kgs/(InchesToMtrHeight*InchesToMtrHeight));
System.out.printf("\nYour BMI is: %.3f\n" ,ImperialToMetricBmi);
}
}
You could basically initialize both kgs and totalIn right where you have declared them but it would be better if the method takes those value as arguments(As of this point both the value never get initialized). Also then you would need to call the static method with both those arguments like
double value1 = 123.1;
double value2 = 24
MethodName1(value1, value2)
Further reading the question I realised that you might be trying to initialize the value inside a conditional statement or a loop .
Understanding in simple terms what happens when the condition does to run the statement is not satisfied ?
The answer is that the value never gets initialized which is the case happening here.