This question already has answers here:
Cyclic reference in java [closed]
(3 answers)
Java classes reference each other
(3 answers)
Closed 5 years ago.
I've got two problems:
First: I'm getting StackOverflowError and I don't know how to fix it
Second: I'm using similar syntax in other projects and there was no problems with StackOverflowError. The second problem is in comments in my code. I want to change value of x in class ChangeValueOfVariable and use it in class DisplayValueOfVariable.
class DisplayValueOfVariable{
ChangeValueOfVariable change = new ChangeValueOfVariable();
public int x = 0;
public void showX(){
System.out.println("Value of x: "+x); //There is still x = 0
}
public void changedX(){
change.changeValue();
System.out.println("Value of x: " +x); // Unfortunately there is still x = 0, but I want here to use changed value
}
}
class ChangeValueOfVariable{
DisplayValueOfVariable disp = new DisplayValueOfVariable();
public void changeValue(){
disp.x++;
System.out.println("Value of x: "+disp.x); // Now x = 1
}
}
class Start{
public static void main(String[] args) {
DisplayValueOfVariable displayValueOfVariable = new DisplayValueOfVariable();
displayValueOfVariable.showX();
displayValueOfVariable.changedX();
}
}
I know, that I can change x in public void changedX(), but if I will have more variables it wouldn't help me in cleaning my code.
Thanks for your help ;)
I know that if I'll make something like this
class DisplayValueOfVariable {
public static void main(String[] args) {
int x = 0;
System.out.println(x);
x++;
System.out.println(x);
}
}
It will be my expected result, ok.
I understand that if I will use only one class(which I attached), my code would compile without errors and code would be simpler.
Unfortunately I have to split my code and save it as more classes.
I've got problem with operations(in other classes) on already existing variables.
Related
This question already has answers here:
Writing a function inside the main method - Java
(7 answers)
What is a classpath and how do I set it?
(10 answers)
Closed 2 years ago.
so I'm running a program in java and I can't really find the main error
this is my code:
public class Main
{
public static void main(String[] args) {
double myCheck = 50.00;
double yourCheck = 19.95;
double fiinalRATE = 0.15;
System.out.println("Tips are");
calcTip(myCheck);
calcTip(yourCheck);
public void calcTip(double bill);
{
tip = bill * fiinalRATE;
System.out.println("The tip should be at least " + tip);
}
}
and this is the error that I'm getting I think its the header but I don't really know what to put I'm kinda new at java though
You can't declare function inside function. You have to pull function out from main() to the Main.class
You cannot declare a method inside another method. So the compiler gets crazy :)
Just move you calcTip() function outside main() function (after closing curly bracket of main() or before declaration of main()).
public class Main
{
public static void main(String[] args) {
double myCheck = 50.00;
double yourCheck = 19.95;
double fiinalRATE = 0.15;
System.out.println("Tips are");
calcTip(myCheck);
calcTip(yourCheck);
}
public static void calcTip(double bill) {
// fiinalRate must be declared as parameter of calcTip()
// or as static field in Main class,
// otherwise the code doesn't compile.
double tip = bill * fiinalRATE;
System.out.println("The tip should be at least " + tip);
}
}
This question already has answers here:
Printing all variables value from a class
(9 answers)
Closed 6 years ago.
I have this simple class:
public class Events{
Boolean wentToGym;
String eventsToday;
public Events(Boolean wentToGym, String eventsToday){
this.wentToGym = wentToGym;
this.eventsToday = eventsToday;
}
Now for some reason I need to iterate through these fields and print them. As they are from different types, I thought I would use the Object declaration in the for-loop:
public static void main(String[] args){
Events events = new Events(true, "first trial");
for(Object e: events.getClass().getDeclaredFields){
System.out.println(e.toString);
}
}
Unfortunately not working because the object has no toString method. It gives me the same result you get when you try printing an array. And I dont know how to cast them inside the loop as they are declared as objects. Whats the best way to iterate through the attributes of a class and print them?
Edit: the question some guys rushed into referring to as duplicated is about attributes all of the same type (Strings), so there is no need for using an object nor the problem is the same. Its always a good idea to try helping by even reading the whole thing even if its harder than feeling important by simply flagging a question.
Is this what you're looking for?
import java.util.Arrays;
public class Events {
Boolean wentToGym;
String eventsToday;
public Events(Boolean wentToGym, String eventsToday) {
this.wentToGym = wentToGym;
this.eventsToday = eventsToday;
}
public static void main(String[] args) {
Events events = new Events(true, "first trial");
Arrays.stream(events.getClass().getDeclaredFields()).forEach(field -> {
try {
System.out.println(field.getName() + ": " + field.get(events));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
}
}
Output:
wentToGym: true
eventsToday: first trial
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();
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am a bit lost...I'm learning Java and have to program a small poll command line application.
We are supposed to program it in german first(to be consistent between us all), so I'll try to translate it, so it's easier to read for you.
My problem is, that it's throwing an exception (while compiling) as following:
Exception in thread "main" java.lang.NullPointerException
at communication.Poll.addQuestionItem(Poll.java:18)
at main.PollTool.main(PollTool.java:8)
am I initializing my array "questionItems" wrong? Aren't I supposed to do it like that? What's wrong here? Did I forget something? :(
main.PollTool:
package main;
import communication.Poll;
public class PollTool {
public static void main(String[] args) {
Poll poll = new Poll ("Best Smartphone:",3);
poll.addQuestionItem("iPhone"); //<--line 8
poll.addQuestionItem("Android");
poll.addQuestionItem("Windows Phone");
poll.askQuestions("This poll determines the polularity of different Smartphones.");
}
}
communication.Poll:
package communication;
import java.util.Scanner;
import calculations.QuestionItem;
public class Poll {
private String questionTitle;
private QuestionItem[] questionItems;
private int count;
private Scanner in = new Scanner(System.in);
public Poll(String s,int arraySize){
questionTitle = s;
questionItems = new QuestionItem[arraySize]; //<--problem here?
}
public void addQuestionItem(String s){
if(count<questionItems.length){
questionItems[count++].setItemText(s); // <--exception here
}
}
public void askQuestions(String topic){
System.out.println(topic);
System.out.println(questionTitle);
for(int i=0; i<questionItems.length; i++){
System.out.println("- - - "+ questionItems[i].getItemText() +" - - -");
System.out.print("Your numerical answer: ");
questionItems[i].vote(in.nextInt());
}
}
void evaluation(){
//not ready :)
}
}
calculation.QuestionItem:
package calculation;
public class QuestionItem {
int count;
int overall;
String text;
public void vote (int pointValue){
overall += pointValue;
count++;
}
public double getDurchschnitt(){
return (double) overall/count;
}
public void setItemText(String s){
text = s;
}
public String getItemText(){
return text;
}
}
When you initialize an array of objects like this:
questionItems = new QuestionItem[arraySize];
All of the values are null by default.
In addQuestionItem, you try to call a method on an object in the array. However, that object starts off null, so this line of code doesn't work:
questionItems[count++].setItemText(s);
What you have to do is initialize the object before setting the text:
questionItems[count] = new QuestionItem();
questionItems[count].setItemText(s);
count++;
Alternatively, you can do what Constant suggested, and initialize all the objects when you initialize the array.
By the looks of it, you're making the array but it doesn't contain the objects yet. You probably want this in the constructor instead.
questionItems = new QuestionItem[arraySize];
for(int i = 0; i < questionItems.length; i++) {
questionItems[i] = new QuestionItem();
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am new to Java and have just beginning doing some exercises a friend sent me. The exercise in question asks us to create a class Term for the terms of a polynomial, and another the class Polynomial itself, where the polynomial is represented as a fixed size array and the values of its fields are provided. I have written the following code:
class Term
{
int coeff;
int exponent;
}
public class Polynomial {
static int size=5;
Term[] poly;
public Polynomial()
{
poly = new Term[size];
for(int i=0;i<size;i++)
{
poly[i].coeff=0;
poly[i].exponent=0;
}
}
public static void main(String args[]) throws Exception
{
Polynomial p = new Polynomial();
}
}
And I keep getting the following exception:
Exception in thread "main" java.lang.NullPointerException
at prac.polynomial.<init>(polynomial.java:25)
at prac.polynomial.main(polynomial.java:34)
Please help me with what I am doing wrong here.
Array elements for an Object array are nullby default. Make sure they are initialized before attempting to access their fields
for (int i = 0; i < size; i++) {
poly[i] = new Term();
...
}
You created the array of Terms, but it's initialized to all nulls. You need to create your Terms.
for(int i=0;i<size;i++)
{
poly[i] = new Term();
poly[i].coeff=0;
poly[i].exponent=0;
}