Java print string and int on same line - java

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

Related

Converting Percentage

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.

Convert the int into double inside of a constructor

I have a constructor whose parameters are both int: Berries( int a, int b ) and I need to put a double in the place of "a" in the code: Berries( 23.45, 6). I tried with cast, but it does not work.
Can you help me please ?
the ugly solution
new Berries((new Double(23.45)).intValue(),6)
I am not sure why would you ever need that?
Either change the constructor to accept double, or send an integer value as an argument
Typecasting can be used to change the compile-time type of an expression. For example, a value of type double can be cast into a value of type integer. This is achieved by putting the desired type in parenthesis as in 'new Berries((int)23.45, 6)'. A working example of typecasting the arguments of a constructor is shown below.
public class Berries {
Berries(int a, int b) {
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args ) {
Berries b = new Berries((int)23.45, 6);
}
}
The output of running this is:
$ java Berries
a = 23 b = 6

Java printing inherited objects with a println method

I'm taking those first steps from python to java and here is my first of many Java questions do doubt.
When printing via a shortened print method, I'm running into a problem with the return value from a inherited class. I'm sure it's something simple about Java I don't get yet. I'm also trying to convert any integers the println method receives to a string with .tostring(), but I'm not sure if that is correct.
class Inheritance {
private static void println (Object line){
System.out.println(line.toString());
}
static class A {
public int multiply(int a, int b){
int val = a*b;
return val;
}
}
static class B extends A {
public int multiply(int a, int b) {
int val = a * b * 5;
return val;
}
}
public static void main(String[] args) {
B b_class = new B();
b_class.multiply(3,4);
println(b_class);
println("Hello World");
}
}
The output is as follows:
Inheritance$B#74a14482
Hello World
You can just use the method inside println
public static void main(String[] args) {
B b_class = new B();
println(Integer.ToString(b_class.multiply(3,4)));
println("Hello World");
}
For Java toString method default it will
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString()
so when you println b_class it will print: Inheritance$B#74a14482.
For your println (Object line) it's receiving Reference type(Object) to println, but as multiply method it's return a primitive type(int), it's not an object, you need to convert it to an Object for println method, as #StanteyS's answer, use Integer.toString can convert int to String.
What's the difference between primitive and reference types?
When you are executing println(b_class); implicitly it calls toString method of same class, which is inherited from Object class.
You need to override toString method to display correct output.
static class B extends A {
int val=0;
public int multiply(int a, int b) {
val = a * b * 5;
return val;
}
public String toString(){
return String.valueOf(val);
}
}
Now, println(b_class); will work as per your expectation.

understanding how to copy data

I am working on some homework for entry level java, and i ran in to this. I have no idea what it is having me do. Is this literally just setting "Date" equal to the value in "Date d"? or am I missing something? I don't feel like that long of an explanation would be used for a one line piece of code.
Could someone please explain what is happening here and what I am missing?
Copy constructor: this is a constructor that accepts one parameter of
type Date and then sets the receiving (or executing) objects instance
variables equal to those of the parameter object. The result is that
the receiving object is a copy of the formal parameter object:
public Date( Date d )
All you need to do is take all the fields of d and copy them over to the new Date. So if a Date has a time, a day, a month, and a year, copy all those to the new Date. That's it.
class Complex {
private double re, im;
// A normal parametrized constructor
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
// Overriding the toString of Object class
#Override
public String toString() {
return "(" + re + " + " + im + "i)";
}
}
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
// Following involves a copy constructor call
Complex c2 = new Complex(c1);
// Note that following doesn't involve a copy constructor call as
// non-primitive variables are just references.
Complex c3 = c2;
System.out.println(c2); // toString() of c2 is called here
}
}

Java overloading a method with two parameters

This problem is about overloading methods and I think I understand the basic idea but I get some weird error "Overloading.java:14".
Like my problem is that I don't know how to return two parameters of my method. So I thought maybe convert the method with the two int parameters with toString(), then return it. Something gone miserably wrong.
The output have to be following:
a 10
a and b 10, 20
char a
result 97
My problem as it is, is with the "a and b 10, 20", and have not done the "char a" just to make you guys aware. This is not homework.
Here is my code so far contains a main class and a helper class:
OverMain Class :
class OverMain {
public static void main(String args[]) {
Overload overload = new Overload();
int result;
System.out.println("a " + overload.test(10)); //prints a 10
System.out.println("a and b " + overload.test(10, 20)); //the method I have trouble with
result = overload.test('a'); //prints Result 97
System.out.println("Result " + result);
}
}
Overload Class:
//The class which is suppose to overload test methods
class Overload {
public int test(int a) {
return a;
}
public String test(int a, int b) {
String string = "";
string = test(a, b).toString();
return string;
}
}
It's not really clear what you're trying to do, but you don't return parameters, and I don't think overloading is really the problem here. To take overloading out of the situation, you can always change the methods to have different names - get it working that way, and then you can always change the names back later and work out any conflicts.
In your case I think you just need:
public String test(int a, int b) {
return a + ", " + b;
}
In other words, just use string concatenation and the automatic int to String conversion that the compiler will apply in order to use string concatenation.
Note that if your code actually compiled, you'd get a stack overflow because you're calling test(a, b) from test(int a, int b) - it would just call itself forever, until you ran out of stack space.
The problem is in your method test(int, int)
public String test(int a, int b) {
String string = "";
string = test(a, b).toString(); // Danger
return string;
}
You have a never ending recurrence relation
Solution: return a + ", " + b

Categories