Can i write sin(whatever) in Java and have it work?
public static void main(String[] args) {
try {
double check = Double.parseDouble(args[0]);
} catch (NumberFormatException e) {
System.exit(0);
}
sin(args[0]);
}
No it won't, you have to call sin with a number like this:
sin(Double.parseDouble(args[0]));
You can either import it statically from Math package or use the syntax
y = Math.sin(x);
with doubles x and y.
In your case x can be e.g. check but have to declare it outside the block.
no you have to pass in a double or something that can be implicitly converted to a double (no objects or Strings)
public static void main(String[] args) {
double check;
try {
check = Double.parseDouble(args[0]);
} catch (NumberFormatException e) {
System.exit(0);
}
System.out.println(Math.sin(check));
}
If you are running anything below Java 1.5, no. If you aren't, you can, using static imports; you can write import static java.lang.Math.*; and then sin(whatever); and this is OK. Be aware of the warning from Sun, though:
Q: So when should you use static imports?
A: Very Sparingly!
If you happen to be running something below Java 1.5, you can still write sin(whatever), but this method must be present...
public static double sin(double x) { Math.sin(x); }
Why would you want to? For example if your arg is "I wandered lonely as a cloud", what is the meaning of sin() of it? Check your input - that's a basic tenet of programming.
Related
I managed to make these two classess, but "score" has to have 7 digits after the dot. I cannot modify Main class. I think I should use String.format("%.7f", ...) but I don't know where. Please help.
MAIN:
public class Main {
public static void main(String[] args) {
Calc c = new Calc();
String score = c.doCalc(args[0]);
System.out.println(score);
}
}
CALC:
public class Calc {
public String doCalc(String cmd) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
return engine.eval(cmd).toString();
}
catch (ScriptException e) {
return "Invalid command to calc";
}
}
}
Instead of using system.out.println, you should use system.out.format or system.out.printf. See a short tutorial from Oracle on using it here. Why exactly can't you modify the main class? That seems to be where your score is being printed..
You can parse the string result back to Double and feed it to String.format:
try {
return String.format("%.7f", Double.valueOf(engine.eval(cmd).toString()));
}
catch (Exception e) {
return "Invalid command to calc";
}
You could of course feed the result directly to String.format without the toString and valueOf round trip, like so:
return String.format("%.7f", engine.eval(cmd));
But that only works when the eval result is a valid floating point number. To deal with other cases like integers or non-numbers, you'd have to put in a few type checks and make the code look more cluttered.
I have certain issue. while I do understand the reason code returns "Nothing" and 24.0 I can't quite grasp why I'm getting: "Nothing" 24.0 AND 9.0. Can someone please explain the issue better? Thank you, here is the code.
class Object {
int w; int h; int d;
void test() { System.out.print("araferi ");}
double volum() {return w*h*d;}
void volum(double x) {
System.out.print(" "+ --x);}
}
public class Test {
public static void main (String[] args){
Object ob1=new Object();
ob1.w=2;
ob1.h=3;
ob1.d=4;
ob1.test();
ob1.volum(10);
System.out.print(" "+ob1.volum());
}
}
The line ob1.volum(10); calls the second volum method, which decrements then prints its argument. That's what's showing you 9.0.
The function:
void volum(double x) {
System.out.print(" "+ --x);}
}
Will print out a value of 9 as you've applied a pre-decrement to the value you passed in (10)
The 9.0 output comes from this line:
ob1.volum(10);
which receives 10 as argument, but in the body of the method it's being decreased (--x), that's why you get 9.
Note: Don't use Object as the name of a class, since it's the root of the class hierarchy in Java. Change it to something else, like MyObject.
I am trying to run this program but I cannot, the compiler is sending me a ".class" error.
Can somebody help me with my problem and if it is possible a general tip about ".class" error?
Here is the program:
import java.io.*;
class Bus
{
private int kostos;
private int plithos;
private int typepiv;
Bus(int x,int y,int z)
{
kostos=x;
plithos=y;
typepiv=z;
}
public void KB(int[] x)
{
try{
for(int i=1;i<5;i++)
{
if(typepiv==2)
{
plithos=plithos+plithos/2;
kostos=kostos-kostos/2;
}
if(typepiv==3)
{
plithos=plithos-plithos/5;
kostos=kostos-kostos*25/100;
}
if(typepiv==1)
{
plithos=plithos;
kostos=kostos;
}
x[i]=plithos*kostos;
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}
class testBus
{
public static void main(String args[])
{
String leof[]=new String[4];
int leof1[][]=new int[4][3];
for(int i=1;i<5;i++)
{
System.out.println("dwste onoma leoforiou");
leof[i]=UserInput.getString();
System.out.println("dwste kostos thesis enilika");
leof1[i][1]=UserInput.getInteger();
System.out.println("dwste plithos thesewn");
leof1[i][2]=UserInput.getInteger();
System.out.println("dwste tupos epibath gia enilikes=1,gia
paidia=2,gia suntaksiouxous=3");
leof1[i][3]=UserInput.getInteger();
Bus leof2=new Bus(leof1[i][1],leof1[i][2],leof1[i][3]);
}
int KostEnoik[]=new int[4];
----->leof2.KB(KostEnoik);
System.out.print("onoleo");
System.out.print(" ");
System.out.print("plithos");
System.out.print(" ");
System.out.print("kost(EURO)");
System.out.print("typepiv");
System.out.print(" ");
System.out.print("apotelesma kostEnoik");
for(int g=1;g<5;g++)
{
System.out.print(leof[g]);
System.out.print(leof1[g][2]);
System.out.print(leof1[g][1]);
System.out.print(leof1[g][3]);
System.out.print(KostEnoik[g]);
}
}
}
the compiler message says :
testBus.java:56:error:cannot find symbol
leof2.KB(KostEnoik);
symbol:bariable leof2
location:class testBus
1 error
Remove the array brackets [] when invoking KB
leof2.KB(KostEnoik);
and remove the preceding enclosing brace }.
Aside: Java naming conventions indicate that variables start with a lowercase letter e.g. kostEnoik. Also consider giving the method KB a meaningful name, e.g. calculateCost
Read Java naming conventions
concern is with your access
leof2.KB(KostEnoik[]);
You are trying to access the "leof2" variable outside of the scope in which it is defined i.e. outside for loop and scope is upto for loop and that's why the compiler will not be able to find that varialble .
leof1[i][3]=UserInput.getInteger();
Bus leof2=new Bus(leof1[i][1],leof1[i][2],leof1[i][3]);
}
int KostEnoik[]=new int[4];
leof2.KB(KostEnoik[]);
You are trying to access the "leof2" variable outside of the scope in which it's defined (in this particular case, the for loop) and that's not allowed.
method KB takes an int array as argument, but you don't have to add the [] when passing the argument. The correct line is
leof2.KB(KostEnoik);
However, there's something pretty odd with you logic: you're repeatedly (for loop) setting leof2, but only the last iteration of the loop will have any effect. I'm almost certain that that's not what you actually want, but the correct answer to where Bus leof2 should actually be defined depends on the correction of that issue.
leof2.KB(KostEnoik); this is the main culprit. whether you have imported UserInput.
Also try to go through the Java Basics
any method can be invoked using object when it is non static or class name when it is static. Please consider this link
Get leof2 object out side the For Loop.
Don't type [] when you pass the array as argument "leof2.KB(KostEnoik[]);".
I'm learning about constructors.
When I try to compile the following code, I get the error "variable input and shape are not initialized."
Could anyone tell me why and how to solve it?
public class Try {
public static void main(String[] args)
{
String input;//user key in the height and width
int shape;//triangle or square
Count gen = new Count(input , shape);//is this the right way to code?
gen.solve();
}
}
public class Count {
public Count(String inp, int shp) {
String input_value = inp;
shape_type = shp;
}
public void solve () {
if shape_type==3{
//count the triangle
}
else if shape_type==4{
//count the square
}
}
}
You haven't given shape or input values yet before you try using them. Either you can give them dummy values for now, like
String input = "test";
int shape = 3;
Or get the string and integer from the user; in that case, you might want to take a look at how to use a Scanner.
By leaving input and shape without values, at:
String input;
int shape;
they are uninitialized, so Java doesn't know what their values really are.
I assume this is some kind of homework. I took the liberty of reformating and fixing your code a little.
You have to initialize any variable you are going to use. The only exception is when you are using class members (those are initialized automatically to some default value). See below that the members of the Count class aren't explicitly initialized.
This is some working code. Also note that i change the solve method a little (the if blocks should have had () around the expression. But what you are trying to do is usually better done with a switch block as shown below. Also I declared two members inside the Count class to remember the values provided at construction time in order to be able to use them when calling the solve() method.
public class Try {
public static void main(String[] args) {
String input = null; //user key in the height and width
int shape = 0; //triangle or square
Count gen = new Count(input, shape);//is this the right way to code?
gen.solve();
}
}
class Count {
String input_value;
int shape_type;
public Count(String inp, int shp) {
this.input_value = inp;
this.shape_type = shp;
}
public void solve() {
switch (this.shape_type) {
case 3:
// count the triangle
break;
case 4:
// count the square
break;
}
}
}
Proper formatting of the code usually helps :).
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.