I have this simple problem I'm trying to do. I'm trying to write a program that doubles these five numbers. Then I want to compute the average of these numbers and print them out. The code runs with no errors, but it will not print my answer for some reason. How can I get it to print the output of the problem or simply print something? I am using Netbeans.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package marina;
/**
*
* #author bax
*/
public class Precedence {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
double grade1 = 100;
double grade2 = 75;
double grade3 = 88;
double grade4 = 65;
double grade5 = 99;
int x = (int) (grade1+grade2+grade3+grade4+grade5/5.0);
System.out.println(x);
}
}
Output:
run:
BUILD SUCCESSFUL (total time: 0 seconds)
(Like I said in the comments:)
Make sure you have your file open and press Shift + F6, which runs the current file. Notice that if you press just F6 then the main project will be run, not necessarily this project. Also, make sure you hit the Clean and build option, to clean up cache and so on.
group your additions in brackets(elm1+elm2)/5 and then divide it by 5
int x = (int) ((grade1+grade2+grade3+grade4+grade5)/5);
System.out.println(x);
System.out.println() will print to the console, so make sure you run it there.
Further, you are not calculating an average. Division has higher precedence than addition. Rewrite like:
int x = (int) ((grade1+grade2+grade3+grade4+grade5)/5.0);
If you're using Eclipse or another IDE to run your program, there should be a "console" window somewhere in the IDE, that will display the console output.
To run your program without an IDE, run the following in a console (cmd on windows, terminal/bash on linux, ...):
javac MyFile.java
java MyFile
If that doesn't work, you will have to add the JDK binaries to your PATH.
It should print the result but you have also a mistake with the calculation.
You only divide grade5 through 5.0.
This is what you want to do I think:
int x = (int) ((grade1+grade2+grade3+grade4+grade5) / 5.0);
Try also:
System.out.println("Result: " + x);
int x = (int) (grade1+grade2+grade3+grade4+grade5/5.0);
(1+1+1+1+5/5)=5
(1+1+1+2+5)/5 = 2
Related
enter image description hereI'm learning how those arithmetic operation and using notepad and command prompt and checking those if its right at my phone's calculator and laptops calculator and it gives different answer . I'm using java language
I've tried computing it manually
Int x =12;
float y = 13.54f;
System.out.println(x/y+" devide 12 - 13.54");//0.88691795 on my calcu i get 0.886262924667...
TL;DR: Unable to reproduce.
From question:
I've tried computing it manually
Int x =12;
float y = 13.54f;
System.out.println(x/y+" devide 12 - 13.54");//0.88691795 on my calcu i get 0.886262924667...
I don't know where you get 0.88691795
When I run your code, I get 0.88626295
Here is extended version of your code, with output:
int x = 12;
float y = 13.54f;
double z = 13.54;
System.out.println(x/y + " using float math");
System.out.println(x/z + " using double math");
System.out.println("0.886262924667... using calcu");
0.88626295 using float math
0.8862629246676514 using double math
0.886262924667... using calcu
As you can see, none of it gives the result you claim to get. Please try again.
I'm trying to take user input in the form of myMonthlyPayment, myAnnualInterestRate, and myPrincipal in order to calculate the number of months needed to pay off debt by using The formula I've attached to this post. What I have in eclipse for the formula right now is:
monthsNeeded = ((Math.log(myMonthlyPayment) - Math.log(myMonthlyPayment)
- ((myAnnualInterestRate / 1200.0) * myPrincipal))
/ ((Math.log(myAnnualInterestRate) / 1200.0) + 1.0));
I should be getting an output of 79 months with the inputs I'm using but instead I'm getting -62. I know the formula is correct, I'm almost positive I've made a mistake somewhere in the translation of it into Java. If someone could point it out that would be greatly appreciated!
So I've fixed it, with a sample input and output.
I didn't put much effort into making this code beautiful but you can see that even separating it into 3 parts using method extraction (although I didn't know how to name them, lacking the domain knowledge) made the code easier to understand.
public class Example {
public static void main(String[] args) {
double myMonthlyPayment = 2000;
double myAnnualInterestRate = 5;
double myPrincipal = 200000;
System.out.println(a(myMonthlyPayment));
System.out.println(b(myPrincipal, myAnnualInterestRate, myMonthlyPayment));
System.out.println(c(myAnnualInterestRate));
double monthsNeeded = (a(myMonthlyPayment) - b(myPrincipal, myAnnualInterestRate, myMonthlyPayment))
/ c(myAnnualInterestRate);
System.out.println(monthsNeeded);
}
private static double c(double myAnnualInterestRate) {
return Math.log((myAnnualInterestRate / 1200.0) + 1);
}
private static double b(double myPrinicipal, double myAnnualInterestRate, double myMonthlyPayment) {
return Math.log(myMonthlyPayment - (myAnnualInterestRate / 1200.0) * myPrinicipal);
}
private static double a(double myMonthlyPayment) {
return Math.log(myMonthlyPayment);
}
}
I think this is what you're looking for:
monthsNeeded = (Math.log(myMonthlyPayment) - Math.log(myMonthlyPayment - myAnnualInterestRate / 1200d * myPrincipal)) / Math.log(myAnnualInterestRate / 1200d + 1);
It seems that, in your solution, you weren't calculating your myAnnualInterestRate/1200*myPrincipal inside your second Math.log(...). You had also left some calculations outside of Math.log(...) in the bottom half of your equation.
If you have an equation that does an operation inside a natural log, when you convert that equation to Java code, the operation needs to still be done, inside the natural log:
ln(someNumber + 10)
would be converted to:
Math.log(someNumber + 10),
NOT:
Math.log(someNumber) + 10
Hope this helps and good luck. :)
I'm using LibSVM with the weka in my java code. I am trying to do a regression. Below is my code,
public static void predict() {
try {
DataSource sourcePref1 = new DataSource("train_pref2new.arff");
Instances trainData = sourcePref1.getDataSet();
DataSource sourcePref2 = new DataSource("testDatanew.arff");
Instances testData = sourcePref2.getDataSet();
if (trainData.classIndex() == -1) {
trainData.setClassIndex(trainData.numAttributes() - 2);
}
if (testData.classIndex() == -1) {
testData.setClassIndex(testData.numAttributes() - 2);
}
LibSVM svm1 = new LibSVM();
String options = ("-S 3 -K 2 -D 3 -G 1000.0 -R 0.0 -N 0.5 -M 40.0 -C 1.0 -E 0.001 -P 0.1");
String[] optionsArray = options.split(" ");
svm1.setOptions(optionsArray);
svm1.buildClassifier(trainData);
for (int i = 0; i < testData.numInstances(); i++) {
double pref1 = svm1.classifyInstance(testData.instance(i));
System.out.println("predicted value : " + pref1);
}
} catch (Exception ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
But the predicted value I am getting from this code is different than the predicted value I am getting by using the Weka GUI.
Example:
Below is a single testing data that I have given for both java code and weka GUI.
The Java code predicted the value as 1.9064516129032265 while the Weka GUI's predicted value is 10.043. I am using the same training data set and the same parameters for both Java code and Weka GUI.
I hope you understand my question.Could any one tell me whats wrong with my code?
You are using the wrong algorithm to perform SVM regression. LibSVM is used for classification. The one you want is SMOreg, which a specific SVM for regression.
Below is a complete example that shows how to use SMOreg using both the Weka Explorer GUI as well as the Java API. For data, I will use the cpu.arff data file that comes with the Weka distribution. Note that I'll use this file for both training and test, but ideally you would have separate data sets.
Using the Weka Explorer GUI
Open the WEKA Explorer GUI, click on the Preprocess tab, click on Open File, and then open the cpu.arff file that should be in your Weka distribution. On my system, the file is under weka-3-8-1/data/cpu.arff. The Explorer window should look like the following:
Click on the Classify tab. It should really be called "Prediction" because you can do both classification and regression here. Under Classifier, click on Choose and then select weka --> classifiers --> functions --> SMOreg, as shown below.
Now build the regression model and evaluate it. Under Test Options choose Use training set so that our the training set is used for testing as well (as I mentioned above, this is not the ideal methodology). Now press Start, and the result should look like the following:
Make a note of the RMSE value (74.5996). We'll revisit that in the Java code implementation.
Using the Java API
Below is a complete Java program that uses the Weka API to replicate the results shown earlier in the Weka Explorer GUI.
import weka.classifiers.functions.SMOreg;
import weka.classifiers.Evaluation;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
public class Tester {
/**
* Builds a regression model using SMOreg, the SVM for regression, and
* evaluates it with the Evalution framework.
*/
public void buildAndEvaluate(String trainingArff, String testArff) throws Exception {
System.out.printf("buildAndEvaluate() called.\n");
// Load the training and test instances.
Instances trainingInstances = DataSource.read(trainingArff);
Instances testInstances = DataSource.read(testArff);
// Set the true value to be the last field in each instance.
trainingInstances.setClassIndex(trainingInstances.numAttributes()-1);
testInstances.setClassIndex(testInstances.numAttributes()-1);
// Build the SMOregression model.
SMOreg smo = new SMOreg();
smo.buildClassifier(trainingInstances);
// Use Weka's evaluation framework.
Evaluation eval = new Evaluation(trainingInstances);
eval.evaluateModel(smo, testInstances);
// Print the options that were used in the ML algorithm.
String[] options = smo.getOptions();
System.out.printf("Options used:\n");
for (String option : options) {
System.out.printf("%s ", option);
}
System.out.printf("\n\n");
// Print the algorithm details.
System.out.printf("Algorithm:\n %s\n", smo.toString());
// Print the evaluation results.
System.out.printf("%s\n", eval.toSummaryString("\nResults\n=====\n", false));
}
/**
* Builds a regression model using SMOreg, the SVM for regression, and
* tests each data instance individually to compute RMSE.
*/
public void buildAndTestEachInstance(String trainingArff, String testArff) throws Exception {
System.out.printf("buildAndTestEachInstance() called.\n");
// Load the training and test instances.
Instances trainingInstances = DataSource.read(trainingArff);
Instances testInstances = DataSource.read(testArff);
// Set the true value to be the last field in each instance.
trainingInstances.setClassIndex(trainingInstances.numAttributes()-1);
testInstances.setClassIndex(testInstances.numAttributes()-1);
// Build the SMOregression model.
SMOreg smo = new SMOreg();
smo.buildClassifier(trainingInstances);
int numTestInstances = testInstances.numInstances();
// This variable accumulates the squared error from each test instance.
double sumOfSquaredError = 0.0;
// Loop over each test instance.
for (int i = 0; i < numTestInstances; i++) {
Instance instance = testInstances.instance(i);
double trueValue = instance.value(testInstances.classIndex());
double predictedValue = smo.classifyInstance(instance);
// Uncomment the next line to see every prediction on the test instances.
//System.out.printf("true=%10.5f, predicted=%10.5f\n", trueValue, predictedValue);
double error = trueValue - predictedValue;
sumOfSquaredError += (error * error);
}
// Print the RMSE results.
double rmse = Math.sqrt(sumOfSquaredError / numTestInstances);
System.out.printf("RMSE = %10.5f\n", rmse);
}
public static void main(String argv[]) throws Exception {
Tester classify = new Tester();
classify.buildAndEvaluate("../weka-3-8-1/data/cpu.arff", "../weka-3-8-1/data/cpu.arff");
classify.buildAndTestEachInstance("../weka-3-8-1/data/cpu.arff", "../weka-3-8-1/data/cpu.arff");
}
}
I've written two functions that train an SMOreg model and evaluate the model by running prediction on the training data.
buildAndEvaluate() evaluates the model by using the Weka
Evaluation framework to run a suite of tests to get the exact same
results as the Explorer GUI. Notably, it produces an RMSE value.
buildAndTestEachInstance() evaluates the model by explicitly
looping over each test instance, making a prediction, computing the
error, and computing an overall RMSE. Note that this RMSE matches
the one from buildAndEvaluate(), which in turn matches the one
from the Explorer GUI.
Below is the result from compiling and running the program.
prompt> javac -cp weka.jar Tester.java
prompt> java -cp .:weka.jar Tester
buildAndEvaluate() called.
Options used:
-C 1.0 -N 0 -I weka.classifiers.functions.supportVector.RegSMOImproved -T 0.001 -V -P 1.0E-12 -L 0.001 -W 1 -K weka.classifiers.functions.supportVector.PolyKernel -E 1.0 -C 250007
Algorithm:
SMOreg
weights (not support vectors):
+ 0.01 * (normalized) MYCT
+ 0.4321 * (normalized) MMIN
+ 0.1847 * (normalized) MMAX
+ 0.1175 * (normalized) CACH
+ 0.0973 * (normalized) CHMIN
+ 0.0235 * (normalized) CHMAX
- 0.0168
Number of kernel evaluations: 21945 (93.081% cached)
Results
=====
Correlation coefficient 0.9044
Mean absolute error 31.7392
Root mean squared error 74.5996
Relative absolute error 33.0908 %
Root relative squared error 46.4953 %
Total Number of Instances 209
buildAndTestEachInstance() called.
RMSE = 74.59964
I'm supposed to create a simple program in Java that will take a value for a price and another for a discount. The price must be float and the discount must be int. I managed to create the program well enough to apply the discount properly.
To further on my problem here's my code:
import java.util.Scanner;
public class Ex_g {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner dados = new Scanner(System.in);
float preco;
int desconto;
// System.out.println("preco?");
do {
preco = dados.nextFloat();
} while (preco > 1000.00);
// System.out.println("desconto?");
do {
desconto = dados.nextInt();
} while ( (desconto < 0) && (desconto > 100));
float res = (float)preco - (preco * desconto/100);
System.out.printf("%.2f\n", res);
}
}
It is nothing complicated but the problem resides on how it takes the values, I'm supposed to enter the price as "500.00" for example, yet the program only takes "500,00" difference being it needs a comma.
I am aware that netbeans (I'm using netbeans) does this kind of thing but what made me come here and write this post is the fact that the values are printed with commas (,) too instead of dots ( . ) and thus the platform I'm sending this code to considers the exercise to be wrong...
I'll be trying another compiler but at the same time I'd like to hear someone's opinion on why I can't enter decimal values separated by a dot. And if possible, how can I fix it.
Thanks in advance.
I tried to make a program (in Java) that calculates pi with the Chudnovsky algorithm but it has the output NaN (Not a Number). Please help me find mistakes in my code, or improve my code. (I don't have a lot of Java programming knowledge)
You can find Chudnovsky's algorithm here:
https://en.wikipedia.org/wiki/Chudnovsky_algorithm
here is my code:
package main;
public class Class1 {
public static void main(String[] args)
{
double nr1=0,nr2=0,nr3=0,pi=0;
int fo1=1, fo2=1, fo3=1;
for(int i=0; i<=20; i++){
for(int fl1=1; fl1<=(6*i); fl1++){fo1 = fo1 * fl1;}
for(int fl2=1; fl2<=(3*i); fl2++){fo2 = fo2 * fl2;}
for(int fl3=1; fl3<=(i); fl3++){fo3 = fo3 * fl3;}
nr1 = ( (Math.pow(-1, i)) * (fo1) * ((545140134*i) + 13591409) );
nr2 = ( (fo2) * (Math.pow(fo3, i)) * ( Math.pow(Math.pow(640320, 3), (i+(1/2)) )) );
nr3 = 12 * (nr1/nr2);
}
pi = 1/nr3;
System.out.println((Math.PI));
System.out.println(pi);
}
}
There are many issues here.
As Andy mentioned, 1/2 is not 0.5.
You are using integers to compute things like 120! which is completely out of bounds for any primitive type.
f01,f02,f03 should be initialized inside each loop, otherwise they grow even bigger
It is not trivial to fix it. You can take a look at
Error calculating pi using the Chudnovsky algorithm - Java
and
http://www.craig-wood.com/nick/articles/pi-chudnovsky/
for some hints, but don't expect built-in primitive types to work with that algorithm.