Can't return the answer - java

The answer should be returned but it does not display for some reason. I have printed within for loop and seen that it's correct answer.
public class Salary
{
public static void main (String[]args)
{
double [] salary = {20000.00};
double riseRate = 1.07;
calculateSalary(salary, riseRate);
}
public static double [] calculateSalary(double [] salary, double riseRate)
{
for (int i=0; i<salary.length; i++)
{
salary [i] = salary [i] * riseRate;
}
return salary;
}
}

That's because you're not printing out the answer. Add a print statement in main.

System.out.println(calculateSalary(salary, riseRate)[0]);

You are returning an array. The salary is in the the first position of you array. If you want to see the salary you would need to use
return salary[0];
in your method.
or
System.out.println(calculateSalary(salary,riseRate)[0]);
in the main.
What you're trying to print right now is the actual array, not a value.
I am not sure why you are doing it like this, though.
Why not just use a double instead of double[]?

Related

error with returning a value from a method in java

hello in the code below I am sorting (sort method) a small array to find the largest number. I then print the answer in the (display method).
But to extend my knowledge I want to mass the max value back to them main in a return statement and then print from there....simply to learn how to return a value.
package christmas;
public class maxvalue
{
public static void main(String[] args)
{
int[] data={10,90,30};
sort(data);
System.out.println("\nmax number is :");
display(data);
System.out.println(data);
}
static int display(int num[])
{
System.out.print(num[0] + " ");
return num[0];
}
static void sort(int num[])
{
int i, j, temp;
for(i=0; i<num.length-i;i++)
{
for(j=0; j<num.length-i-1;j++)
{
if(num[j]<num[j+1])
{
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
}
}
the output is:
max number is :
90 [I#4617c264
90 is the max value as printed by the display value. But after this I have a return of the max value and then I try and print the return. But instead of an integer it looks like a memory location is being printed.
Any ideas please - I am student but this is not homework - simply trying to catch up. I appreciate that there are more elegant ways to calculate the max value in an array but what I am trying to learn is the passing of arguments to and from a method.
The reason is that you are trying in your last System.out to print data, which is an array, and that's the reason why you see a memory address.Try printing display(data) and you will see as the output the desired number.
try System.out.println(data[0]);
data is your array therefore printing data without an index will only print its memory location
Instead of printing the returned value, you are printing the data array memory location:
System.out.println(data);
You should change that line with:
System.out.println(display(data));
With that line we have:
Your display method is called and it prints the max value
Your display method returns the max value
println takes that returned value and prints it
private static int sort(int[] array){
int a, b, max = 0;
for (int i = 1;//If i was 0, it would have thrown an ArrayIndexOutOfBoundsException.
i < array.length; i++){
a = array[i-1];//The first element in the array.
b = array[i];//The second one, and so on.
if (a > b) max = a;//Check the bigger number.
else max = b;
}
return max;
}
private static void display(int nr){
System.out.print(nr);//Or what you want to do with the number.
}
public static void main(String[] args){
int[] data={10,90,30};
display(sort(data));
//Or do it like this.
int max = sort(data);
display(max);
}

Create method that prints the numbers between two specified numbers

So I'm creating a method in that is supposed to print the numbers between two specified numbers. I had it setup before in the main method but i can figure out how to make a method and call it into the main method. What my program does right now is it only prints what "int between" is equal to. I don't want anyone to just type the code out for me, i'm just looking for tips on what i should change. Last time i asked a question someone proceeded to just answer with code and it did not help me to learn anything.
So my question is what is causing the program to only display what between is equal to? I know that I need a value for the if loop to return something, but it needs to return the numbers between num1 & num2. My Professor Also said that the method needs to be "public static void Printer(int num1, int num2)" is that even possible? I kept getting an error so I switched to "int Printer".
package nortonaw_Assignment8;
public class Nortonaw_Assignment8 {
public static void main(String[] args) {
int between;
between = Printer(5, 20);
System.out.println(between);
}
public static int Printer (int num1, int num2){
int between = 0;
for (;num1<=num2; num1++);
return between;
}
}
1) There's a difference between printing out a value and returning a value.
When you"print" a value in a function, you are just writing out the value to screen or some other medium , but when you use the return statement, you are passing what you are returning to the caller of your function as well as control.
** I hope that makes sense to you?
2)"public static void Printer(int num1, int num2)" is possible.
currently your method is designed to return only one single number, so either you return a collection of numbers are you print the numbers inside Printer, in this case you can use the method signature suggested by your professor.
So I would write it like this:
public static void main(String[] args) {
Printer(5, 20);
}
public static void Printer (int num1, int num2) {
for (int i=num1;i<=num2; i++) {
System.out.println(i);
}
}
EDIT:
Note that I introduced a additional counter variable i because I think num1 and num2 should not be changed as they define the boundary of your range.
package printingTasks;
public class Printer {
public static void main(String[] args) {
printInBetween(25, 30); //Would print 26 -> 29
}
/*
* You don't need to return something if you just want to print it out to the console.
* So you can use void as return type
*/
public static void printInBetween(final int leftBoundary, final int rightBoundary){
/**
* Calculate the first number which should be printed.
* This number would be the leftBoundery plus one
* This number will be the starting point of your loop
*/
final int firstNumber = leftBoundary + 1;
// final int firstNumber = leftBoundary; //if you want to include the left boundary
for (
int currentNumber = firstNumber; //Set the counter of the the loop (currentNumber) to the first valid number
currentNumber < rightBoundary; //Run the loop while the loop counter is less than the rightBoundary
// currentNumber <= rightBoundary; //If you want to include the right boundary
currentNumber++ //Increment the loop counter with each iteration
){
/**
* In each iteration you will print the current value of the counter to the console
* Because your counter (currentNumber) will be incremented from the first valid number
* to the last number before the right boundary you will get all numbers between the two
* boundaries.
*/
System.out.println(currentNumber);
}
}
}
Your teacher wants you to print from the Printer method not directly in the main method. All the main method should be doing is calling the Printer method.
Here is the full snippit:
package nortonaw_Assignment8;
public class Nortonaw_Assignment8 {
public static void main(String[] args) {
Printer(5, 20);
}
public static void Printer (int num1, int num2) {
for (int i = num1+1;i<=num2-1; i++) {
System.out.println(i);
}
}
}

Java: How to put the value of a user defined attribute into an array?

For example, if this is my class...
public class Person {
private double height; //Height in inches
//constructors
public Person(double newHeight) {height = newHeight;}
public Person() {}
//Getter
public double getHeight() {return height;}
//Setter
public void setHeight(double newHeight) {height = newHeight;}
}
and then this is my driver...
import javax.swing.JOptionPane;
class Myclass {
public static void main{String[] args) {
String userInput;
int arraylen;
Person bob = new Person ();
double[] myarray;
userInput = JOptionPane.showInputDialog("How many heights do you have
to list?");
arraylen = Integer.parseInt(userInput);
myarray = new double[arraylen];
for(int i=0;i<myarray.length;i++) {
userInput = JOptionPane.showInputDialog("What is the next height?");
bob.setHeight(Double.parseDouble(userInput));
// I need something here to put that attribute value into the array.
}
}
}
So at this point I have a value in the height attribute and I need to figure out how to move that into an array. I'm sure putting user input into an attribute to just then move it to an array probably isn't the best way to do this, but it's for school, so it's what I need to figure out. Please share any suggestions of better ways to do it though. However, I'm mainly concerned with how to do it like this.
What you seem to want to do, setting the height of bob to a value, and then setting the entry in an array to the height of bob, can be done by adding the line:
myarray[i] = bob.getHeight();
to the end of your for loop.

How do you convert command line arguments to a double array for calculating sums?

So currently I get a "Sum = 0.0" and a Mean equals "NaN", after fighting a lot of messages that warned agains a "possible lossy conversion from double to int". I think the code is finally taking doubles, but still does not do what I would like it to: take values from the command line, place them into an array, sum these and then calculate the mean.
Any ideas where the errors lie?
public class StudentMarks{
protected double[] marks;
//create an array filled with double values
public StudentMarks(double[] marks){
this.marks = new double[0]; //set the default array size
}
public void setMarks(){
this.marks = marks;
}
public void getArray(){
//one can only print arrays using loops..
//took me a little to realise that erm.
for(int i=0; i<marks.length; i++)
System.out.println(marks[i]);
}
public double calSum(){
double totals = 0.0;
for(double i: marks) {
//double mLength = Double.parseDouble(marks[i]);
totals+= i;
}
return totals;
}
//A method to calculate the mean of all elements
public double calMean(){
double means = (calSum()/marks.length);
return means;
}
//A main method to test
public static void main(String[] args) {
// Check to see if the user has actually sent a paramter to the method
if (args.length != 7){
System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
System.exit(-1);
}
double[] prompt = new double[args.length];
for (int i =0; i<args.length; i++){
prompt[i] = Double.parseDouble(args[i]);
}
StudentMarks test = new StudentMarks(prompt);
test.getArray();
// Calculate the sum of all the values in the array and print it
System.out.println("Sum: "+ test.calSum());
// Calculate the mean of all the values in the array and print it
System.out.println("Mean: "+ test.calMean());
}
}
Instead of
this.marks = new double[0];
use
this.marks = marks;
You are currently assigning the marks member variable to be a zero-length array rather than the parameter, so the sum of the elements is zero, and marks.length is zero, so calSum()/marks.length is 0.0 / 0.0, which is defined to be NaN.
One problem was in the initializer of the class. The class is currently initialized to a 0 length array. Instead you should initialize it with your input.
Use
public StudentMarks(double[] marks){
this.marks = marks;
}
Instead of
public StudentMarks(double[] marks){
this.marks = new double[0];
}
Here is a fixed up version of the code. Take a look at the inline comments for clarity.
public class StudentMarks{
protected double[] marks;
//create an array filled with double values
//Pass in the array of marks to initialize the class
public StudentMarks(double[] marks){
this.marks = marks; //set the marks array in the class to the passed in one
}
//Set the class marks variable to the passed in one
public void setMarks(double[] marks){
this.marks = marks;
}
//Change the name to "printMarks" to better reflect the purpose of the method
public void printMarks(){
//one can only print arrays using loops..
//took me a little to realise that erm.
for(int i=0; i<marks.length; i++){
System.out.println(marks[i]);
}
}
//
public double calSum(){
double totals = 0.0;
for(double i: marks) {
//double mLength = Double.parseDouble(marks[i]);
totals+= i;
}
return totals;
}
//A method to calculate the mean of all elements
public double calMean(){
double means = (calSum()/marks.length);
return means;
}
//A main method to test
public static void main(String[] args) {
//Print out an error and exit only if we have less than 1 element passed in
if (args.length != 7){
System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
System.exit(-1);
}
double[] prompt = new double[args.length];
//Note that there is no error checking here
for (int i =0; i<args.length; i++){
prompt[i] = Double.parseDouble(args[i]);
}
//Initialize the StudentMarks class with the value of the input
StudentMarks test = new StudentMarks(prompt);
test.printMarks();
// Calculate the sum of all the values in the array and print it
System.out.println("Sum: "+ test.calSum());
// Calculate the mean of all the values in the array and print it
System.out.println("Mean: "+ test.calMean());
}
}

Iterating through an arraylist of objects

I am working on a project that has a class called Items and a method called totals that calculates a grand total for an array of Items objects.
for some reason it cant see Items, I know that I am missing something simple or obvious but I just cant figure it out. Ant help would be appreciated.
public void totals(){
int index=0;
for (Iterator it = items.iterator(); it.hasNext();) {
Items i = it.next();
double itotal;
itotal = items.get(index).Items.getTotal();
}
}
and here is the Items class
public class Items {
public String name;//instance variable for item name
public int number;//instance variable for number of item
public double price;//instance variable for unit price
public double total;//instance variable for total
Items(String name,int number,double price){
this.name=name;
this.number=number;
this.price=price;
total=number*price;
}
public void setName(String name){
this.name=name;
}
public void setNumber(int number){
this.number=number;
}
public void setPrice(double price){
this.price=price;
}
public void setTotal(){
total=number*price;
}
public String getName(){
return name;
}
public int getNumber(){
return number;
}
public double getTotal(){
return total;
}
public double getPrice(){
return price;
}
Thanks in advance for the help.
Basically, there are two flaws:
you never increment the itotal variable and it's declared inside the loop
you never access the variable i in the current iteration
And also, shouldn't your totals method return something (like itotal)?
The way I see it, the proper way of iterating over that items array is
public double totals(){
double itotal = 0.0; //#A
for (Iterator<Items> it = items.iterator(); it.hasNext();) { //#B
Items i = it.next(); //#C
itotal += i.getTotal(); //#D
}
return itotal; //#E
}
Basically:
#A Here you initialize the itotal variable (outside of the loop) that will contain the grand total for all items
#B You start iterating over all items
#C You get the next item in the array
#D You increment the grand total with the current item's total
#E You return the grand total
There are a number of potential issues here.
In your for loop, you declare Items i, but never use it. Maybe it = it.next() should be a part of the for loop instead?
You call items.get(index), but index is always 0. You might want to use it here instead.
You declare double itotal and assign it within the for loop, so it's overwritten on each iteration. Maybe you want to declare it with an initial value outside the loop, and then increment it inside the loop.

Categories

Resources