I don't know what to do next :
Create a new class "X" in a new package "prog1.printtools". In this class, first implement a class method "alsProzent" that returns a string value and receives a double and an int as formal parameters. In this method, you should now create (and return) a formatted string that represents a percentage representation of the double value, where the int parameter is to specify the number of decimal places. Use a comma as a decimal separator. A call as percent (0.12345,2) should return the string "12.34%". You do not have to round, but simply cut off more decimal places.
package prog1.printtools;
public class PrintTools {
public static void main(String[] args) {
public String alsProzent(double m, int n) {
return
}
//String Prozentzahldarstellung(double m) = String.format();
I don't think this is what they are looking for, but you could do this:
public String alsProzent(double m, int n) {
NumberFormat pctFormat = NumberFormat.getPercentInstance();
pctFormat.setMaximumFractionDigits(n);
pctFormat.setRoundingMode(RoundingMode.DOWN);
return pctFormat.format(m);
}
You can try something like this:
public static String alsProzent(double m, int n){
String format = String.format("%." + n + "f", m);
return format;
}
public static void main (String args[]){
System.out.println(alsProzent(10.2394, 2));
}
It's pretty straight forward when using String formatting. I just replaced the traditional decimal point value to take the value of user defined int.
Also I noticed that you've created the function inside a function. That isn't the convention and usually will result in errors. You can call a function or create an object inside another function but you can't define a function inside a function.
Related
I would like following effect -> I have object of class FluidArray which will be an array, but depending on the input it will be either int array or String array:
FluidArray XXX = new FluidArray;
XXX.YYY[] might be either String or int
In this case variable YYY of class XXX might be int array or String
Can I somehow declare variable type depending on some choice?
public class FluidArray
{
VarType YYY;
public static void FluidArray(int a)
{
double[] YYY = new double[15];
}
public static void FluidArray(String a)
{
String[] YYY = new String[15];
}
}
Let's say I want to make a sort method.
I input there unsorted array.
I take out sorted array.
The catch is I might want to sort String, double or int array and I don't want to write 3 sorting methods - I thought that my sorting method might work on some defined object and this object will be either String, double int depending on my choice.
I am trying to use Generic type, I got so far sth. like this:
public class test
{
public static void main(String[] args)
{
FluidArray<Integer> arrTest = new FluidArray<>();
arrTest.arr[1]=2;
arrTest.arr[2]=3;
arrTest.arr[3]=4;
}
public static class FluidArray<arrType>
{
public arrType[] arr = (arrType[])new Object[15];
}
}
I don't understand, why I can't get access to the array, compiler ends when inserting first value.
Read up on Generics. Thats what they are supposed to do
A part of my homework is to convert three double variables to one String and print it from the main method. I have created a separate class where I try to create the string. When I try to print the string from the main method, i dont understand how to do it.
Main-class
public static void main(String[] args) {
System.out.println(Point.toString());
}
Point
public class Point {
public String toString(Double xVal, Double yVal, Double zVal){
String p= Double.toString(this.xVal) + ":" + Double.toString(this.yVal) +
":" + Double.toString(this.zVal);
return p;
}
}
This is just a part of my code, can someone help me with the part where i try to print the string?
It seems that you tried to create some sort of utility class, so...
First you need to make the method which prints the values in Point class static, so you don't need to create instances of Point in order to call it.
Second, I highly recommend to change the method name in class Point because there is a toString method already inherited from Object. This may lead to confusions since the goal of the inherited method is not the same the one you created this toString method for.
Also, be careful inside the method to use the values received as parameter and not the (missing) instance attributes. That is, use values xVal, yVal and zVal, not this.xVal, this.yVal and this.zVal.
So, this would go kind of this way:
public class Point {
// changed from `toString` to `convertToString`, use the name which fits better your needs, except `toString`
public static String convertToString(Double xVal, Double yVal, Double zVal) {
// use `xVal`, not `this.xVal` and the same for the other variables
String p = Double.toString(xVal) + ":" + Double.toString(yVal) + ":" + Double.toString(zVal);
return p;
}
}
Then in your main class:
public class Main {
public static void main(String[] args) {
System.out.println(Point.convertToString(1d, 2d, 3d)); // you can replace this sample values with the real ones
}
}
Of course, there are many ways to do this, but the "proper" way, using toString would be to make the x, y and z values attributes of the class (and, optionally, a constructor and getters and setters for those attributes), and have toString print the values of those attributes of the current instance.
public class Point {
Double xVal, yVal, zVal;
public Point(Double x, Double y, Double z) {
this.xVal = x;
this.yVal = y;
this.zVal = z;
}
public String toString() {
return String.format("%s:%s:%s", this.xVal, this.yVal, this.zVal);
}
}
Here, String.format("%s:%s:%s", ...) is a nicer way to format the string with the three numbers, but you can just as well keep yours. The nth %s will automatically convert the parameter in that position to string and insert it at that position. You could also use e.g. %.2f for specific floating -point format with more options.
You can create a new instance of the Point class with the given coordinates and print it. Here, you do not have to explicitly call toString, as it will be automatically called when println tries to convert its argument to a string.
public static void main(String[] args) {
Point p = new Point(1.1, 2.2, 3.3);
System.out.println(p);
}
You need to create object of the class Point then invoke the method toString with the three double value as arguments, like you defined inside Point class.
public static void main(String[] args) {
Point p = new Point();
System.out.println(p.toString(2.0,3.5,4.6));
}
I think the correct way is to create a new point with its parameters and override the toString method inherited:
public class Point{
Double xVal; Double yVal; Double zVal;
void Point(Double xVal, Double yVal, Double zVal)
{
this.xVal = xVal;
this.yVal = yVal;
this.zVal = zVal;
}
#Override
public String toString(){
String p= Double.toString(this.xVal) + ":" + Double.toString(this.yVal) +
":" + Double.toString(this.zVal);
return p;
}
}
So the main:
public static void main(String[] args) {
Point p = new Point(1.3,2.0,.30);
System.out.println(p.toString());
}
i made a small program for summing two numbers
if i used a void type method it will be like this
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
getSum(x,y);
}
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
} }
here if i used a method that returns a value i will get same output!
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
int r = getSum(x,y);
System.out.println("sum = " + r);
}
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}}
so i'm confused what is the benefit of returning a value if i can finish my program with a void type method?
The point is not to get the result but the way we get the result
consider
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
}
will print the output to the screen after calculation
but when we use return
as you have done it later
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}
this function will respond back the sum. that sum can be stored in a variable
can be used afterwards
like in recursion
In small programs, you won't get the difference but while writing the big programs you have to make several functions which are being called several times and you may need the output of one function into other.
In that case, you will require return so that the output of one function can be used into other.
Hope this helps!!
I think the answer is that, if you're calling getSum() method with a return type in any other class.. you would get a returned value which can be used for further processing. .
Where as in void that's not possible... Hope this helps... Reply if any doubts..
I can understand why you have this question.
First of all, you should know that in real development, we do not use console logs.
System.out.Println();
This is used only for debugging and that too in very rare cases.
The whole point of a function is to take some input and convert to something else.
So,
public static int getSum(int x, int y) {
return x+y;
}
public static void main(String[] args) {
System.out.Println(getSum(5,10));
}
This is the better solution.
Best Regards,
Rakesh
When you use the keyword void it means that method doesn't return anything at all. If you declare a return type different to void at the method statement instead, that method must return obligatorily a valid value to the declared return type using the keyword return followed by a variable/value to send back to the class that called the method.
Defining methods here you have the java documentation for a method declaration
Answering your question, in small programs that work with primitive values it doesn't really matter but in complex program when you usually need to return specifics object types, i.e an ArrayList or actually an instance of a class you created you can't simply put it into a System.out.println and send it to the console, mostly you'll want to get something from a method and that something usually can be a more complex object than an integer or a string, the way to get that something is through the return type defined by the method's statement.
A common use of return types is when your method is static and it can't interact with the non-static instance variables of the class, this type of static methods usually get values from their arguments, do a certain kind of progress and then return a result that the method's caller can use.
Returning a value enables you to use that value in whichever way you want, including printing it or assigning it to variable for further processing. If on the other hand you print the value in the method and not return anything, i.e. making the method of type void, then that's all you can do with that method.
I was trying to print a string and int on a same line. But I get an error. I know my way around this error but why does the line System.out.println("This is a string: %i", c2.a);gives error whereas the line System.out.println("This is class method" + c2.a ); gives the correct output. Below is my code.
public class MyClass
{
private int a;
public double b;
public MyClass(int first, double second)
{
this.a = first;
this.b = second;
}
// new method
public static void incrementBoth(MyClass c1) {
c1.a = c1.a + 1;
c1.b = c1.b + 1.0;
}
//pass by valuye therefore no change
public static void incrementA(int a)
{
a = a+1;
}
public static void main(String[] args)
{
MyClass c1 = new MyClass(10, 20.5);
MyClass c2 = new MyClass(10, 31.5);
// different code below
incrementBoth(c2);
incrementA(c1.a);
System.out.println("This is a object passing: %i",c2.a);
System.out.println("This is object passing: " + c2.a );
System.out.println("This is pass by value: %d",c1.a);
}
}
My other question is does the line incrementBoth(c2) changes value of c2 because here whole object is passed to the method rather than passing by value in incrementA(c1.a)
You need to use the printf method and not println.
println is used to print primitive types, Strings and objects as they are. Also, println takes only one argument as input. That is the reason you are getting an error when you pass multiple arguments to it in your code.
printf on the other hand is used to format and then print the formatted string to the Standard output / error. This is what you should use in your code above for formatting the output.
Here's a reference to the tutorials.
Hope this helps!
Try:
int x = 3;
System.out.println("This is my number" + x);
The output should be:
This is my number 3
This question already has answers here:
Is it possible to pass arithmetic operators to a method in java?
(9 answers)
Closed 6 years ago.
In a Java program, I have these strings:
a= 8,7,"+"
b=1,5,"*"
Each line is a separate process. I want in each line, that two number calculated with that operator. But I don't want to use any type of condition system for detecting which operator is in each line.
In fact, my main problem is detecting the type of the operator without conditions. I don't want to use the Javascript engine. I want to know is there any efficient and standard way.
Another solution from J. Selva's response:
Improvements
single class
static block
better abstraction
import java.util.HashMap;
import java.util.Map;
/**
* Created by SEA-HAWK on 23/8/15.
*/
public abstract class Expr {
public static Map<String,Object> op;
static{
op=new HashMap<>();
op.put("+", new Expr() {
#Override
public int evaluate(int a, int b) {
return a + b;
}
});
op.put("-", new Expr() {
#Override
public int evaluate(int a, int b) {
return a - b;
}
});
op.put("*", new Expr() {
#Override
public int evaluate(int a, int b) {
return a * b;
}
});
op.put("/", new Expr() {
#Override
public int evaluate(int a, int b) {
return a / b; // decimal point loss
}
});
}
abstract public int evaluate(int a, int b);
public static int exprEval(String expr){
String a[]=expr.split(",");
a[2]=a[2].replaceAll("\"","");
return ((Expr)op.get(a[2])).evaluate(Integer.parseInt(a[0]),Integer.parseInt(a[1]));
}
}
Main function:
public static void main(String[] args) {
String x="20,10,\"*\"";
System.out.println(x+"="+Expr.exprEval(x));
x="20,10,\"+\"";
System.out.println(x+"="+Expr.exprEval(x));
x="20,10,\"-\"";
System.out.println(x+"="+Expr.exprEval(x));
x="20,10,\"/\"";
System.out.println(x+"="+Expr.exprEval(x));
}
Output:
20,10,"*"=200
20,10,"+"=30
20,10,"-"=10
20,10,"/"=2
Note: change datatype for float/decimal value computation.
First Split the string and store the operator in the Character variable. You can use split() to split a String and assign it to a String array. Access operator using the array index and assign it to a Character variable.
Now You can use Map<Character,Object> where you can store character and object to calculate in single structure and access later with character only without any if-else or switch.
Map<Character,Object> map = new HashMap<>();
map.put('+', plusObject);
map.put('-', minusObject);
map.put('*', multiplyObject);
map.put('/', divideObject);
To get the object type of operator, you can use map.get(character) it will return the object according to the character and null otherwise.
Update: Create four classes and a object for each class namely plusObject, minusObject, multiplyObject,divideObject. These are the objects that you add to HashMap initially. Have a evaluate() function in each class. Now with the returned object, call the evaluate() method which will make call to respective class. You need not check the Object type using any conditional statements.
You can convert the postfix expression into infix mathematical expression and execute it using expression evaluator in Java or javascript(not preferred). As you recommend java, following link will help you:
evaluating-a-math-expression-given-in-string-form
java-parse-a-mathematical-expression-given-as-a-string-and-return-a-number
Answer from above two links:
You can pass it to a BeanShell bsh.Interpreter, something like this:
Interpreter interpreter = new Interpreter();
interpreter.eval("result = 5+4*(7-15)");
System.out.println(interpreter.get("result"));
Let us know if your issue gets resolved.