Mad nuk e di nese ne kodin e vertet ke bere " if (trigFunc == "cos") " nese po duhet ta ndryshosh sic e kam bere une me poshte, klasa String te ofron "equals" method per te krahasuar dy stringje.
Kur te pyeta per specifikime e kisha llafin,
1. Nga merret input , nga console me komanden "java Trig 30 cos" psh. apo me " java Trig" dhe pastaj prompt userin per "30 cos" ??
2. Ka nevoje per try ... catch Exceptions, une po i ve megjithate.
Dikush tek "si te ..." per te njejten teme qe ke hapur ketu te ka rekomanduar "switch ... case" NUK mund te perdoret switch ne java per stringjet madje me mire mos te perdoret fare ne java, ne te kundert nga C ose C++ ne java switch reagon shemtuar ne disa raste, ka artikuj plot mbi kete ceshtje.
Ja dhe kodin vers. 1, do ti japesh komanden
java Trig 23 cos -- ne console (apo terminal po te perdoresh Unix)
Kodi:
import java.lang.Math;
public class Trig
{
public static void main(String[] args)
{
// Catch exceptions if there are any ...
try
{
double angle;
/* get the second argument in "java Trig args[0] args[1]
which will be args[1] the trigonometric funct.
*/
String function = args[1];
Double argDouble = new Double(args[0]); // Assign args[0] to a Double type object
angle = argDouble.doubleValue(); // tear the primitive double value out of that, could have been done in one step
angle = angle * ( Math.PI / 180 );
/* Get the function and calculate it. */
if (function.equals("cos") )
angle = Math.cos(angle);
else if (function.equals("sin") )
angle = Math.sin(angle);
else if (function.equals("tan") )
angle = Math.tan(angle);
else if (function.equals("cotan") )
angle = 1 / Math.cos(angle);
else
{
System.out.println("Enter a regular function: cos, sin, tan, cotan");
return;
}
System.out.println(angle); //Print the angle
}
catch (NumberFormatException e)
{
System.out.println("The angle MUST be a number ");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("There should be two arguments, an angle and a function");
}
} // finished with main
}
Krijoni Kontakt