How to convert double values to string in a text field - java

I want to do the average of 9 textfields and also the sum of them and place them in 2 other textfields by using a button, currently this code doesnt displays anything in the other textfiels. If i put anything, for example "A" instead of "%.Of" it would display the "A" in the textfield but not the average or the sum. Please i need help with a code that would work, dont mind if i need to change a lot.
This is what im working with:
private void jButton_RankingActionPerformed(java.awt.event.ActionEvent evt) {
double R[] = new double [14];
R[0] = Double.parseDouble(jTextField_Math.getText());
R[1]= Double.parseDouble(jTextField_English.getText());
R[2] = Double.parseDouble(jTextField_Spanish.getText());
R[3] = Double.parseDouble(jTextField_Biology.getText());
R[4] = Double.parseDouble(jTextField_Physics.getText());
R[5] = Double.parseDouble(jTextField_Chemestry.getText());
R[6] = Double.parseDouble(jTextField_PE.getText());
R[7] = Double.parseDouble(jTextField_Humanities.getText());
R[8] = Double.parseDouble(jTextField_Technology.getText());
R[9] = (R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8])/ 9;
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
String Average = String.format("%.Of",R[9]);
jTextField_Average.setText(Average);
String TotalScore = String.format("%.Of",R[10]);
jTextField_TotalScore.setText(TotalScore);
if(R[10]>=50)
{
jTextField_Ranking.setText("Superior");
}
else if (R[10]>=41){
jTextField_Ranking.setText("Alto");
}
else if (R[10]>=34){
jTextField_Ranking.setText("Basico");
}
else if (R[10]<=33){
jTextField_Ranking.setText("Bajo");

Since you mentioned that an A would print, it follows that jButton_RankingActionPerformed is being called. The issue you have is the format string you are using to print the total and average. You have mistakenly chosen the capital letter O rather than the number zero.
Replace this (which contains a capital letter O):
String.format("%.Of",R[9]);
With
1) No decimal will be printed: i.e. 50.2 would be 50
String.format("%.0f",R[9]);
2) Or perhaps you want to see one decimal place like 50.2
String.format("%.1f",R[9]);
Also a very small optimization is:
R[9] = (R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8])/ 9;
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
Could be replaced with:
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
R[9] = R[10] / 9;
or use a loop to calculate R[10]. (to add R[0] to R[8])

Related

Multidata Type Array In Java

Complete newbie here guys. I'm working on a Java program to prompt the user for 3 variables which are used to calculate a future investment's value. Everything works perfectly, except when it comes time to put both my datatypes into ONE array.
Here's what the output SHOULD look like:
Year Future Value
1 $1093.80
2 $1196.41
3 $1308.65
...
This is what mine looks like:
Year 1
Future Value 1093.81
Year 2
Future Value 1196.41
Year 3
Future Value 1308.65
...
My year is an int value and my Future value is a double (rounded). I've been sitting here racking my brain and all the forums I can find and haven't been successful. Every time I put both value into an array I get an error about putting two different datatypes together. Any insight would be greatly appreciated. Below is the code for my full program:
import java.util.Scanner;
class investmentValue {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter investment amount: $");
double i = s.nextDouble();
System.out.print("Enter percentage rate: ");
double r = s.nextDouble()/100;
System.out.print("Enter number of years: ");
int y = s.nextInt();
for (y=1; y<=30; y++) {
double f = futureInvestmentValue(i,r,y);
System.out.println("Year " + y);
System.out.println("Future Value " + f);
}
}
public static double futureInvestmentValue (double investmentAmount, double monthlyInterestRate, int years){
double value=1;
value = investmentAmount*Math.pow((1+(monthlyInterestRate/12)),(years * 12));
double roundValue = Math.round(value*100.0)/100.0;
return roundValue;
}
}
One solution is to start by implementing a pad function. Something like,
public static String pad(String in, int len) {
StringBuilder sb = new StringBuilder(len);
sb.append(in);
for (int i = in.length(); i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
Now we can combine that with String.format() to get the dollars and cents, use a consistent printf() for the header and output lines. To get something like,
// Print the header.
System.out.printf("%s %s%n", pad("Year", 12), "Future Value");
for (int y = 1; y <= 30; y++) {
String year = pad(String.valueOf(y), 13); // <-- One more in your alignment.
String fv = String.format("$%.2f", futureInvestmentValue(i,r,y));
System.out.printf("%s %s%n", year, fv);
}
The System.out.println command isn't the only method available to you!
Try this in your loop:
System.out.print(y); // note that we use print() instead of println()
System.out.print('\t'); // tab character to format things nicely
System.out.println(f); // ok - now ready for println() so we move to the next line
Naturally, you'll want to do something similar to put your headings in.
PS - I'm pretty sure this is just an output formatting question - you don't really want to put all these values into a single array, right?
Given that you really are looking for formatted output, it may be better to use the printf() method.
The following inside the loop (instead of the 3 lines I wrote above) should do the trick (untested - I haven't used printf() format strings in a long, long time).
System.out.printf("%i\t$%0.2f", y, f);
EDIT: edited to answer your question in the comments about constructors... You should also check out this for further understanding
You could create a class that will hold both of the arrays...
This would give you a single object, let's call it StockData, that holds two arrays for the two separate types you need. You need to create the object once and then insert the data separately by type.
class StockData {
double[] data1;
int[] data2;
// default constructor
StockData() {
}
// constructor
StockData(double[] data1, int[] data2) {
this.data1 = data1;
this.data2 = data2;
}
// getters, setters...
}
Then you add data to an array of its type:
// using default constructor to add a single value to both arrays
StockData sd = new StockData();
sd.data1[INDEX_X] = YOUR_DOUBLE;
sd.data2[INDEX_X] = YOUR_INT;
// using default constructor to add all data to both arrays
StockData sd = new StockData();
sd.data1 = YOUR_ARRAY_OF_DOUBLE;
sd.data2 = YOUR_ARRAY_OF_INTS;
// using constructor to add all array data directly
StockData sd = new StockData(YOUR_ARRAY_OF_DOUBLE, YOUR_ARRAY_OF_INTS);
You could also have an object that will hold the double and int value, so the object will represent a single stock information of 2 values and then create an array containing those objects...
class StockData {
double data1;
int data2;
// default constructor same as before
// constructor
StockData(double data1, int data2) {
this.data1 = data1;
this.data2 = data2;
}
// getters, setters...
}
// ...
Adding data:
// create an array of StockData objects
StockData[] sd = new StockData[TOTAL_AMOUNT_OF_DATA];
// ... obtain your data
// using default constructor to add a single value to the array
sd[INDEX_X] = new StockData();
sd[INDEX_X].data1 = YOUR_DOUBLE;
sd[INDEX_X].data2 = YOUR_INT;
// using constructor to add all data directly
sd[INDEX_X] = new StockData(YOUR_DOUBLE, YOUR_INT);
If you want the program to have an specific format you could try to change your code and put this where your for is:
System.out.println("Year Future Value");
for (y=1; y<=30; y++) {
double f = futureInvestmentValue(i,r,y);
System.out.print(y);
System.out.println(" " + f);
}
this way you will have your output in the format you need without using arrays. But if you want to do an array for this you could declare an array of objects and create a new object with two attributes (year and future value)
Also your class name is investmentValue and it is recommended that all classes start with upper case it should be InvestmentValue
I hope that this can help you
A fun data structure you would be able to use here is a Map (more specifically in Java, a HashMap). What you are doing is associating one value with another, an integer to a double, so you could make something that looks like this:
Map<Integer, Double> myMap = new HashMap<>();
This would take the year as the integer, and the double as the price value, and you could iterate over the map to print each value.
Additionally if you really are looking for a "multidata type array," Java automatically casts from integer to double should you need to. For example:
int i = 2;
double[] arr = new double[2];
arr[0] = 3.14
arr[1] = i;
The above code is perfectly valid.

How can I store a bunch of double in a single double?

I edited my post.
:: New logic problem, everytime I input only 1 integer the += only prints 0.
System.out.print("\nEnter the property code: ");
sPropertyCode = input.next();
bError = false; //set to false
dTotalCommission += dCommissionRate;
dTotalSales += dSellPrice;
if (sPropertyCode.equalsIgnoreCase("R"))//if r or R dRate will store 7,...perform calculation for dCommissionRate
{
dRate = 7;
dCommissionRate = dSellPrice * (dRate/100);
System.out.print("Total commission on this property is $" +dCommissionRate);
} //this works and prints the calculated amount of rate but when it is going to the last line....
if (sYesOrNo.equalsIgnoreCase("n"))
{
System.out.println(sApplicationReport);//prints the Summary Report
System.out.println ("----------------------------------------------------------");
System.out.println ("Total property sales: $" + dTotalSales);//all the stored values for dSellPrice will be added and printed
System.out.println("Total Commissions: $"+ dTotalCommission);//This part only prints 0.00 instead of the calcuated dCommissionRate
break;
}
dTotalPrice += dSellPrice
means : dTotalPrice = dTotalPrice + dSellPrice
But if you want to store 10000 and 20000 in a single variable , you can use an arrayList :
Example :
ArrayList<Double> myValues = new ArrayList<Double>();
myValues.add(10000 );
myValues.add(200O00 );
// etc.
If you want to show them :
for(int i = 0 ; i < myValues.size(); i++){
Double mySingleValue = myValues.get(i);
System.out.println(mySingleValue.toString());
}
Hm. It's kind of hard to follow your thinking, but here is my best shot.
Your code here (dTotalPrice += dSellPrice) Will add the value of dSellPrice to dTotalPrice.
aside from a semicolon you aren't missing anything.
Instead of trying to store multiple doubles in a single double variable, why not try and store your multiple doubles in an array? Therefore you could store your multiple number values in this array and then pick out the ones you want.
You'd just reassign the variable. No problem.
Try it!
double dada = 10.7;
/* run jump play */
dada = 3.141592653589;
However, what makes more sense is to use an array.
declare a double array -
double[] myNumbers = {28.3, 21.2};

multiply user input through JTextField with an array of double values

I'm very new to Java (and programming in general). I'm working on a program that should accept a double value from user through a JTextField and multiply it with quite a few double values in an array, and display the result in a JTextArea. A kind of calculator you could say.
Right now, I only see the result of the input multiplied with the last value in the array(0.50) and im sure there's something with my loop, array or something missing, I just cant figure out what.
double[] percRM = {0.65, 0.75, 0.85, 0.70, 0.80, 0.90, 0.30, 0.40, 0.50};
double dDouble;
double pFinal;
if(ae.getSource() == pressbutton){
pDouble = Double.parseDouble(presstext.getText());
for (int j=0;j<percRM.length;j++){
pFinal = percRM[j] * pDouble;
}
resulttext.setText("The Sum is:" + "\n" + pFinal+ "\t");
}
I also have a JFrame with quite a few buttons. Please tell me if you want me to show my entire code.
And while im here, I wonder how I can add some text next to each value printed, lets say user input is 100, the result will be(example):
The sum is:
Week1:
Set1 = 65
Set2 = 75
Set3 = 85
etc.
appreciate any help, thanks
Your problem is that you're calling setText(...) on the JTextArea and doing so after the loop is over. setText(..) will erase everything that the JTextArea is currently showing and replace it with your new text -- now what you want. The append(...) method just adds new text tot he bottom.
Instead call append(...) and do so inside of the loop.
for (int i = 0; i < someLength; i++) {
double value = doSomeCalculation():
myTextField.append("result: " + value + "\n");
}

Reading from CSV who has char and int

I got a task. The input of the Java Decathlon program is a CSV-like text file. The task is to output an XML file with all athletes in ascending order of their places, containing all the input data plus total score and the place in the competition (in case of equal scores, athletes must share the places, e.g. 3-4 and 3-4 instead of 3 and 4)
This is my cvs file:
Jana Kari;12.61;5.00;9.22;1.50;60.39;16.43;21.60;2.60;35.81;5.25.72
Eva Narun;13.04;4.53;7.79;1.55;64.72;18.74;24.20;2.40;28.20;6.50.76
Maja Hope;13.75;4.84;10.12;1.50;68.44;19.18;30.85;2.80;33.88;6.22.75
Kirke Kanda;13.43;4.35;8.64;1.50;66.06;19.05;24.89;2.20;33.48;6.51.01
I got these constants for each decathlon event
double[] A = new double[]{25.4347,0.14354,51.39,0.8465,1.53775,5.74352,12.91,0.2797,10.14,0.03768};
double[] B = new double[]{18,220,1.5,75,82,28.5,4,100,7,480};
double[] C = new double[]{1.81,1.4,1.05,1.42,1.81,1.92,1.1,1.35,1.08,1.85};
Formula for points is
Points = INT(A(B — P)^C) for track events (faster time produces a better score)
Points = INT(A(P — B)^C) for field events (greater distance or height produces a better score)
"P" is persons records (from cvs). I dont really understand how to read properly from file that it would allow me to do calculations with numbers only. Should i use two dimensional array for cvs file ? Its very confusing and im stuck.
EDIT
Well i believe for outputing later to xml file one dimensional array is better. The point of my task is code simplicity, but CVS file may be expanded to N lines so i never know how much rows it will have. I want to use number array in this code:
double[] A = new double[]{25.4347,0.14354,51.39,0.8465,1.53775,5.74352,12.91,0.2797,10.14,0.03768};
double[] B = new double[]{18,220,1.5,75,82,28.5,4,100,7,480};
double[] C = new double[]{1.81,1.4,1.05,1.42,1.81,1.92,1.1,1.35,1.08,1.85};
double PTS;
double finalscore;
for (int i = 0; i < P.length;i++ )
{
finalscore=0;
if (i == 0)
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
else if (i == 4)
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
else if (i == 5 || i == 9)
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
else
{
PTS = A[i]* Math.pow((P[i]-B[i]),C[i]);
}
finalscore = finalscore + PTS;
}
System.out.println(finalscore);
}
}
Where P[] would be array first lane of number without name.
P.S it seems code above gives me result NaN when i use
double[] P = new double[]{12.61,5.00,9.22,1.50,60.39,16.43,21.60,2.60,35.81,5.272};
Yes, you have the right idea - you can use a two dimensional array. I would also recommend you create a class called Person, as this is Java programming and Java is object-oriented, but if you have not studied creating multiple classes yet, you can skip that bit and just do it with two arrays, one one-dimensional array for the names and one two-dimensional array for the numbers.
For the one-dimensional array approach
public class Person {
String name;
double[] scores;
int minutes;
int seconds;
int hundredths;
public Person(String line) {
String[] splitted = line.split(";");
name = splitted[0];
// now fill in the other fields
for(int i = 1; i < splitted.length - 1; i++) {
scores[i - 1] = Double.parseDouble(splitted[i]);
}
String times = splitted[splitted.length - 1].split("\\.");
minutes = Integer.parseInt(time[0]);
// etc. - fill in the rest
}
}
(Actually, this might be wrong, because I assumed most of the numbers are scores, but I guess they are really seconds and hundredths of a second. It doesn't really matter, unless you could have a time over one minute for those events.)
Then you need to have an array of Person objects in your other class - let's make it quite big so that it will be big enough hopefully:
Person[] array = new Person[10000];
Now have a loop, and whenever you read a line from the file you just call the constructor.
array[j] = new Person(line);
Nice approach, isn't it?

Trying to Make an Average Finder, Not Using ReadLine(), using Only Console

New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;

Categories