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.
Related
I am trying to print the number increment by 1 whenever i call the function, but i am not able to get the solution, below is my code
The blow is the function
public class Functions<var> {
int i=0;
public int value()
{
i++;
return i;
}
}
I am calling the above function here
import Java.Functions;
public class Increment {
public static void main(String[] args)
{
Functions EF = new Functions();
System.out.println(EF.value());
}
}
Whenever i run the program , i am getting only the output as 1 , but i want the output to be incremented by 1 . Could you please help. Thanks in Advance.
I believe your answer is with the scope of your variables and your understanding of them. You only call the method once in your given examples, so 1 is arguably the correct answer anyway. Below is a working example which will persist during runtime one variable and increment it every time a function is called. Your methods don't seem to follow the common Java patterns, so I'd recommend looking up some small example Hello, World snippets.
public class Example{
int persistedValue = 0; // Defined outside the scope of the method
public int increment(){
persistedValue++; // Increment the value by 1
return persistedValue; // Return the value of which you currently hold
// return persistedValue++;
}
}
This is due to the scope of "persistedValue". It exists within the class "Example" and so long as you hold that instance of "Example", it will hold a true value to your incremented value.
Test bases as follows:
public class TestBases {
static Example e; // Define the custom made class "Example"
public static void main(String[] args) {
e = new Example(); // Initialize "Example" with an instance of said class
System.out.println(e.increment()); // 1
System.out.println(e.increment()); // 2
System.out.println(e.increment()); // 3
}
}
If your desire is out of runtime persistence (the value persisting between application runs) then it would be best to investigate some method of file system saving (especially if this is for your Java practice!)
Your main problem is to increment the number value 1.
But you are calling your function only once. Even though you call the function many times you will get the value 1 only because it is not static variable so it will every time initialize to 0.
So please check below answer using static context.
Functions.java
public class Functions{
static int i=0;
public int value()
{
i++;
return i;
}
}
Increment.java
public class Increment{
public static void main(String []args){
Functions EF = new Functions();
System.out.println(EF.value());
System.out.println(EF.value());
System.out.println(EF.value());
}
}
Output:
1
2
3
If you design multi-threaded application, it will be better to use AtomicInteger.
The AtomicInteger class provides you an int variable which can be read and written atomically.
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.incrementAndGet();
I found the solution to this problem but can't figure out how it works. Can someone please explain this?
public static void main(String[] args) {
Object[] numbers = new Object[100];
Arrays.fill(numbers, new Object() {
private int count = 0;
#Override
public String toString() {
return Integer.toString(++count);
}
});
System.out.println(Arrays.toString(numbers));
}
[I could not comment to that answer directly because I dont have enough reputation points.]
Can someone please explain this?
This code is a use of
Arrays.fill(Object[] a, Object val)
Where the Object val provided is an anonymous class with its toString() method overridden.
Arrays.toString(numbers) calls the toString() on the anonymous class for each element in the a array. As the toString() is overridden to increment the count, you get incremented values each time it is called.
However, as #Eran has pointed out, it is not without a loop.
To be accurate, Arrays.fill() use a loop in its own implementation.
In general, Arrays.fill fills an array by assigning the second parameter to every element of the first parameter (your array).
Your example has an Array of type Object and a length of 100 elements.
In Arrays.fill(...) you generate a so-called anonymous class of type Object, which reimplements the toString-method by increasing the value of a counter (int count) and printing it after that.
Now, by calling Arrays.toString the toString() method of every element inside the array is executed (which is the same instance of the anonymous class here), resulting in printing the numbers from 1-100
System.out.println(1)
System.out.println(2)
System.out.println(3)
System.out.println(4)
System.out.println(5)
System.out.println(6)
System.out.println(7)
...
System.out.println(100)
:D
To avoid the code-generator proposed by Dmitry, this can be easily done with just copy-paste
int i=0;
System.out.println(++i);
System.out.println(++i);
System.out.println(++i);
System.out.println(++i);
System.out.println(++i);
...
System.out.println(++i);
Write the System.out.println(++i) once.
Copy and paste 4 times.
Then you pick those 5 lines and copy paste them again.
You should now have 10 times that line. Select those 10 lines and copy paste another 9 times.
done!
Here is a better solution:
IntStream.rangeClosed(0, 100).forEach(System.out::println);
I think it's self explanatory
What about this:
public class NoLoopPrint {
int max;
int from;
public NoLoopPrint(int max) {
this(1, max);
}
public NoLoopPrint(int from, int max) {
this.max = max;
this.from = from;
}
public String toString() {
if (from >= max) {
return String.valueOf(max);
}
System.out.println(from++);
return this.toString();
}
public static void main(String args[]) {
System.out.println(new NoLoopPrint(100));
System.out.println(new NoLoopPrint(10, 20));
}
}
Newbie completeing thinkJava book and trying to figure out one of the answers to the exercises. It calls for me to download the "GridWorld" files and complete the following steps:
Write a method named moveBug that takes a bug as a
parameter and invokes move. Test your method by calling it from main.
Modify moveBug so that it invokes canMove and moves the bug only if
it can.
Modify moveBug so that it takes an integer, n, as a parameter, and
moves the bug n times (if it can).
Modify moveBug so that if the bug can’t move, it invokes turn instead.
I am stuck on number 3, I can not figure out how to pass n into the "move() method"
-Please Help I am a newbie
My Code:
import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.Bug;
import info.gridworld.actor.Rock;
public class BugRunner
{
public static void main(String[] args)
{
ActorWorld world = new ActorWorld();
Bug redBug = new Bug();
world.add(redBug);
world.add(new Rock());
world.show();
moveBug(redBug,5);
System.out.println(redBug.getLocation());
}
public static void moveBug(Bug aBug, int n){
if(aBug.canMove() == true){
aBug.move();
} else {
aBug.turn();
}
}
}
You mean you're stuck on number 3:
Modify moveBug so that it takes an integer, n, as a parameter, and moves the bug n times (if it can).
This means write a loop, looping n times, calling move() once per iteration, if canMove() returns true.
BTW: if (canMove() == true) {...} is the long way to say if (canMove()) {...}.
And fix the indentation of the if statement.
Thanks for pointing me #Andreas
My Solution that worked:
public static void moveBug(Bug aBug, int n){
for(int i = 0; i < n; i++){
if(aBug.canMove())
{
aBug.move();
} else {
aBug.turn();
}
}
}
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[]);".
package bankAccount;
public class CurrentAccount {
int account[];
int lastMove;
int startingBalance = 1000;
CurrentAccount() {
lastMove = 0;
account = new int[10];
}
public void deposit(int value) {
account[lastMove] = value;
lastMove++;
}
public void draw(int value) {
account[lastMove] = value;
lastMove++;
}
public int settlement() {
int result = 0;
for (int i=0; i<account.length; i++) {
result = result + account[i] + startingBalance;
System.out.println("Result = " + result);
}
return result;
}
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
}
}
At the moment, when I run the class, the expected System.out.println does not appear, and if I simply move public static void main(String[] args) to the top, this generates multiple red points. What is the best way for me to refactor my code so it works in the expected way?
you can have another class called Main in the file Main.java in which you can write your
public static void main(String args[])
and call
c.settlement();
in you main() to print.
Also one more advice,
in your constructor you have
account = new int[10];
which can hold only 10 ints.
in your deposit() and draw() you are not checking the account size. When the value of lastMove is more than 10 , the whole code blows up.
Hence I suggest you to use ArrayList
You never called the settlement method...
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
c.settlement();
}
I have the feeling that you come from some non-OOP language, like C or PHP. So some explanation:
The main method is static: that means it "exists" even when there is no object instance created, it can be thought of as if it belonged to the class instance.
on the contrary, for the other methods to "work", an instance is required.
This way the main method can be (and is actually) used as the entry point of the application
It is executed, and when it exists, (if no other threads are left running) the application terminates.
so nothing else is run that is outside of this method just by itself...
so if you don't call c.settlement(); - it won't happen...
Other notes:
Running main doesn't create an instance of the enclosing class
with new CurrentAccount(), you create an object instance, which has states it stores, and can be manipulated
be careful with arrays, they have to be taken care of, which tends to be inconvenient at times...
Why do you expect the printed output to appear? You don't actually call the settlement method, so that command is not executed.
You did not call settlement.. so nothing appears
if you add c.settlement... it is fine..
You have not called deposit() and settlement() in the main method untill you call, You cannot get expected output.