I'm new to java and having trouble basically passing an array through to a method in another class, using the values to compute a new array, and then passing that back again to print. The problem is that when it prints the array it always prints the empty string. When I step through in debug mode I can see that the values are getting passed in and the array gets generated, but then when it prints it is always empty. It seems like somehow to code is failing to return the correct array maybe. Here is my code
public static void main(String[] args) {
double[] rnoDivs;
double[] rnoEarnings;
Company rno = new Company();
rnoDivs = new double[] {355, 355, 315, 240, 190};
rno.yearlyDividendsGrowth(rnoDivs);
rnoEarnings = new double[] {0.019, 3.451, 5.210, 3.543, 2.960};
rno.yearlyEarningsGrowth(rnoEarnings);
This is passed through to my other class
public class Company {
double[] yearlyEarningsGrowth = {};
public double[] getYearlyEarningsGrowth(){return yearlyEarningsGrowth;}
public double[] yearlyEarningsGrowth(double[] yearlyEarnings){
double[] yearlyEarningsGrowth = new double[yearlyEarnings.length];
for (int x = 0; x <= yearlyEarnings.length; x++) {
if (x < yearlyEarnings.length - 1) {
yearlyEarningsGrowth[x] = (yearlyEarnings[x] / yearlyEarnings[x + 1]) * 100;
}
}
return yearlyEarningsGrowth;
}
}
And then I try to print this statment
Company[] companies = {rno};
for(int i=0; i < companies.length; i++) {
double[] array = companies[i].getYearlyEarningsGrowth();
System.out.println("Yearly earnings growth: " + Arrays.toString(array));
}
But then I just get the array "[]". Any help with this would be appreciated! I seem to be going in circles because everything looks correct.
Related
I am trying to convert a String array to int array and then compare elements if they are equal so far i am getting an error, first this is the method that converts string array to to int array
private static int[] convertStringArrayToIntArray(String[] strVals) {
int[] intVals = new int[strVals.length];
for (int i=0; i < strVals.length; i++) {
intVals[i] = Integer.parseInt(strVals[i]);
}
Arrays.sort(intVals);
return intVals;
}
Now the method below is where i am getting the exception
public static String ScaleBalancingCorrect(String[] strArr) {
int[] startWeights = convertStringArrayToIntArray(strArr[0].replaceAll("[^0-9,]", "").split(","));
int[] availWeights = convertStringArrayToIntArray(("0," + strArr[1]).replaceAll("[^0-9,]", "").split(","));
if (startWeights[0] != startWeights[1]) { //I get exception here
for (int i = 0; i < availWeights.length; i++) {
// omited code for brevity
this is what i was running when i got the exception
public static void main(String [] arg) {
String [] arr = {"34","1277"};
ScaleBalancingCorrect(arr);
}
Maybe it's just a typo and you wanted to write if (startWeights[0] != availWeights[1]).
availWeights will always have at least two elements, since you add 0 as a first element before the supplied other element(s).
startWeights, however, as in your example, may only have one element (in your example, it's 34).
I have a problem with my code below:
public class stringToChar {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
char[] sCharArr;
String[] odd = new String[n];
String[] even = new String[n];
for(int i = 0; i < n; i++) {
sCharArr = in.next().toCharArray();
for(int j = 0; j < sCharArr.length; j++) {
if(j % 2 == 0)
even[i] += sCharArr[j];
else
odd[i] += sCharArr[j];
}
}
for(int i = 0; i < n; i++) {
System.out.println(even[i] + " " + odd[i]);
}
}
}
My issue is on the output it has a Null in the result. Here is a sample scenario:
2
John
Cena
Answer should be:
Jh on
Cn ea
But my code answer is:
NullJh Nullon
NullCn Nullea
Your problem is that the new arrays are initialized with all null Strings. Then your code is not assigning values to all array elements, but just to some of them!
Finally you print your array, and surprise, those values that were null and that have not been changed - are still null (and when you print a null string ... it prints "null" [ yes, null, not Null; you got a little mistake there in your output example ]
You see, you iterate from 0 to the length of your two arrays. And if the number is even, you put a value in the even[i]; and if the value is odd, it goes to odd[i]. Lets take even - in that case, odd[i] simply stays null!
One way to fix that:
List<String> even = new ArrayList<>();
List<String> odd = new ArrayList<>();
And now, instead of setting a certain index in even/odd; you simply do:
even.add(some new value);
and to add those single characters:
even.add(new String(sCharArr));
Doing so, even and odd will (in the end) contain exactly the values that you added to each list; but no "residual" nulls. For the record: the way how you split up strings, to then pull them back into a String array isn't exactly the most simple/straight forward way to solve the problem.
But I leave "further" simplifications" as exercise to the user.
hello everyone I got this codes but I need to make some constraint on my arrays: public static void main (String[] args)
{Random myRand = new Random ();
// Pick array size T from 1 to 100.
int T = 1 + myRand.nextInt(5);
System.out.println("T="+(T));
int C = 1 + myRand.nextInt(100);
System.out.println("C="+(C));
// Declare array of size T.
int [] production_cost=new int [T];
int []stock1= new int [T];
int[]stock2= new int [T];
int[]fix_cost1= new int [T];
int[]fix_cost2= new int [T];
int[] Demands=new int[T];
// Fill the array with random numbers.
{for (int i=0; i< T; i++){
production_cost[i] = myRand.nextInt(Integer.max(0,20));
stock1[i] = myRand.nextInt(Integer.max(0, 20));
stock2[i]= myRand.nextInt(Integer.max(0,20));
fix_cost1[i]=myRand.nextInt(Integer.max(10, 20) );
fix_cost2[i]=myRand.nextInt(Integer.max(20,30));
Demands[i] = myRand.nextInt(Integer.max(1,C));}
System.out.println("p2::"+Arrays.toString(production_cost));
System.out.println("h1::"+Arrays.toString(stock1));
System.out.println("h2::"+Arrays.toString(stock2));
System.out.println("K1::"+Arrays.toString(fix_cost1));
System.out.println("K2::"+Arrays.toString(fix_cost2));
System.out.println("d::"+Arrays.toString(Demands));
You can see this link : Fill an array with random numbers
You need to add logic to assign random values to double[] array using
randomFill method.
Change
public static double[] list(){
anArray = new double[10];
return anArray; }
To
public static double[] list() {
anArray = new double[10];
for(int i=0;i<anArray.length;i++)
{
anArray[i] = randomFill();
}
return anArray; }
Then you can call methods, including list() and print() in main method to generate random double values and print the
double[] array in console.
public static void main(String args[]) {
list(); print(); }
One result is as follows:
-2.89783865E8
1.605018025E9
-1.55668528E9
-1.589135498E9
-6.33159518E8
-1.038278095E9
-4.2632203E8
1.310182951E9
1.350639892E9
6.7543543E7
I get a runtime-error that says: Exception in thread "main" java.lang.ClassCastException: lab07.Loan cannot be cast to [Llab07.Loan;
at lab07.TestLoanClass.main(TestLoanClass.java:27).
The fault might be in the serializable class Loan, but have a look at this one first. Because it all works just fine if I avoid using arrays. I am using the Eclipse IDE.
public class TestLoanClass {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
Loan[] loan = new Loan[5];
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("Exercise19_06.dat"));
for (int i = 0; i < 5; i++) {
loan[i] = new Loan(1.5 * i,i * 2,10000 * i);
output.writeObject(loan[i]);
}
output.close();
ObjectInputStream input = new ObjectInputStream(new FileInputStream(
"Exercise19_06.dat"));
//Conversion below is perfectly legal to type, but I get an error when
//I run the program. Appearently it has something with Object being
//cast to a Loan. Shouldn't the error show up while writing the code?
Loan[] loanRead = (Loan[]) (input.readObject());
//However, it work's just fine if I avoid using an array
for (int j = 0; j < 5; j++) {
System.out
.printf("The loan was created on %s\n"
+ "The monthly payment is %.2f\nThe total payment is %.2f\n",
loanRead[j].getLoanDate().toString(),
loanRead[j].getMonthlyPayment(),
loanRead[j].getTotalPayment());
}
input.close();
}
}
Delete Loan[] loanRead = (Loan[]) (input.readObject()); and put loan[j] = (Loan) (input.readObject()); in a second for loop.
And of course change all occurences of loanRead[j] in a for loop with loan[j].
Before I state my question, I would like to thank everyone who helped me on my previous question. Anywho, I am currently getting the memory offsets as result even when I place it to the to a toString method. I've read most of the questions regarding the toString method and have somewhat of a understanding, I just wanted to make sure if I'm implementing this correctly. If you feel that this is a redundant question, I understand. Thanks for the help in advance.
Ship class
import java.util.Scanner;
public class Ship{
int type;
public String [][] shipPiece = new String[11][11];
Scanner in = new Scanner(System.in);
//Coordinate xy = new Coordinate();
//private Coordinate[] bawdPiece = {new section()};
public Ship(){
}
public String[][] placeShip()
{
System.out.println();
for(int x = 1; x<10; x++)
{
for(int y = 1; y<10; y++)
{
shipPiece[x][y] = "0";
System.out.print("|" + shipPiece);
}
}
return shipPiece;
}
public String toString()
{
StringBuilder temp = new StringBuilder();
temp.append(shipPiece);
return temp.toString();
}
public String toString()
{
StringBuilder temp = new StringBuilder();
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
temp.append(String.valueOf(shipPiece[x][y]);
}
temp.append("\n");
}
return temp.toString();
}
Also another thing I would like to point out is your array initialization. You initialize it with 11 x 11 indices, but your loop is only adding 9 values to each row and column Loop starts at 1 and ends at 9. You may want to fix your initialization to 10 x 10 and make your loop start at 0.
If I understand the question correctly, you are trying to get the index of the shipPiece as a string?
If that's the case try String.ValueOf(index), you'll obviously have to do this twice as you have a 2-dimensional array.
Ex:
String s = String.ValueOf(xIndex) + "," + String.ValueOf(yIndex);