I want to know how to tell if an int has been changed (during the program).
Like with an if statement.
int i = 2;
int a = 1;
while(1 < 2) {
if(i % 100 == 0) i++;
}
if(i //Then checks if it changed) {
System.out.println("Changed :D");
}
Is there a way to tell if the variable i is changed DURING the program?
Since this is Java, are these variables data members of a class? In that case give them private access and provide getters and setters. Your setter can notify you if you so desire.
int i = 0;
boolean valueChanged = false;
while(some good condition) {
if (i % 100 == 0) {
i++;
valueChanged = true;
}
}
if(valueChanged) {
System.out.println("Changed :D");
}
// Your int variable
int i = 0;
// A scratch variable
int prev_value_of_i = i;
// Call this code to check whether i has changed since last call
if(i != prev_value_of_i) {
System.out.println("Changed :D");
prev_value_of_i = i;
}
Keep track of the original value of i in a separate variable and compare i to that?
This seems redundant, since the programmer should know when and where values are stored. If you don't, maybe step through with a debugger? #shoover's answer is the most flexible, handling however many unexpected times you might change the value without requiring adding lines of code inside your infinite loop.
class TalkativeInt{
private int x;
TalkativeInteger(int x){
this.x = x;
}
public void set(int a){
System.out.println("Changed!! "+x+" to "+a);
x = a;
}
public int get(){
//System.out.println("Accessed - that tickles");
return x;
}
}
Related
As an example we're combing through the permutations of the integer 123456789. Inspired by Heap's algorithm, we have the following
public static ArrayList<String> comb(char[] seq, int n, ArrayList<String> box){
if(n == 1){
if (isSquare(Integer.valueOf(String.valueOf(seq)))) {
box.add(String.valueOf(seq));
}
} else {
for(int i=0; i<n; i++){
comb(seq,n-1, box);
int j;
if ((n%2)==0) {
j = i;
} else {
j = 0;
}
char temp = seq[n-1];
seq[n-1] = seq[j];
seq[j] = temp;
}
}
return box;
}
In the present case we're interested whether a particular permutation is a square of an integer. Realised by
public static boolean isSquare(int n) {
if ((n%10)==2 || (n%10) ==3 || (n%10)==7 || (n%10) == 8) {
return false;
} else if ( (Math.sqrt(n)) % 1 ==0) {
return true;
} else {
return false;
}
}
However, to be able to use comb I must initialise an empty array outside of the method. What should I do to avoid inducing the need for global variable? I would still like to obtain a box with all solutions. I realise my error is in the parametrisation of comb .
Create a function that "wraps" the original recursive function, provides it with every parameter it needs and creates copies of objects if necessary:
Let's say you renamed your comb(...) function to combRecursive(...) for the sake of convenient naming.
public static ArrayList<String> comb(char[] seq, int n){
char[] seqCopy = Arrays.copyOf(seq, seq.length);
return combRecursive(seqCopy, n, new ArrayList());
}
I am just new at coding im not sure if this is even possible in my program i should be able to loop 1 - 2 - 1 - 2 - 1 - 2 alternating but im not sure what to do
what should i put inside this think function so every time i call it, it alternates between 1-2-1-2-1-2
example first time i called it think would return 1 then second time would return 2 then third time would return 1 again
public int think() {
int i=1;
int z=1;
if(i==1){
return i;
}
if(i==2){
return i;
}
return i;
}
The code below is getting the return value of think function
public static String askEnemy(Enemy enemy){
String x = "null";
switch (enemy.think()) {
case 1:
x = "Hit";
break;
case 2:
x = "Defend";
break;
case 3:
x = "Charge";
break;
}
return x;
}
The variables i and z are local to the think method and hence they get initialized to the values you have at the start each time they get called. You cannot carry forward state using them.
You need to have a member variable in the Enemy class for this.
class Enemy {
...
private int thinkVar = 1;
public int think() {
int thinkResult = thinkVar;
thinkVar = (thinkVar == 1) ? 2 : 1;
return thinkResult;
}
}
EDIT:
If you could have it as -1 and 1, you can simply write thinkVar = -thinkVar
You can benefit from using a global variable in you main class and can send it to your other class where think method is developed as a parameter. Check below:
public int think(int value)
{
if (value % 2 = 0)
return 21
else
return 1;
}
Main class:
int value = 1;
...
public static String askEnemy(Enemy enemy){
String x = "null";
switch (enemy.think(value)) {
case 1:
x = "Hit";
break;
case 2:
x = "Defend";
break;
case 3:
x = "Charge";
break;
}
value++;
return x;
}
A think variable inside of the Enemy class is needed. This way you can have multiple enemies all with different values. Otherwise, when you have one value for all Enemy objects then the value isn't independent for each object.
public class Enemy {
private int thinkValue;
public Enemy(){
thinkValue = 1;
}
//Other functions and variables are probably in this class.
public void setThinkValue(int value){
thinkValue = value;
}
public int getThinkValue(){
return thinkValue;
}
}
I know that the variable maxreps isn't in the scope of my main method so I wanted it call it by creating an object, but it still isn't able to get maxreps.
How could I fix this?
public class LUIS{
public void james(){
int current=1;
int maxreps=1;
String adriana = "aabbddddnsspkrrgg";
for(int a=0; a<adriana.length(); a++){
if(adriana.charAt(a) == adriana.charAt(a+1)){
current++;
if(maxreps>=current){
maxreps=current;
}
}
}
}
public static void main(String[] args){
LUIS fritz = new LUIS();
final int drei = fritz.james;
System.out.println(maxreps);
}
}
As you noted, scoping prevents seeing a variable defined in a different scope. You can resolve your particular issue by returning the value
public int james(){ // <-- change from void to an int return
int current=1;
int maxreps=1;
String adriana = "aabbddddnsspkrrgg";
for(int a=0; a<adriana.length(); a++){
if(adriana.charAt(a) == adriana.charAt(a+1)){
current++;
if(maxreps>=current){
maxreps=current;
}
}
}
return maxreps; // <-- return the value
}
And then in the main method set a variable to the returned value.
Alternatively, you can define it as a class variable, but there are reasons to avoid doing so -- globals are generally bad.
1) final int drei = fritz.james; cannot compile. You cannot invoke a method in this way (that is without ()).
2) Besides, the james() method should have a more meaningful name.
This method computes the max series of a same character. So, you could call it computeMaxSeries()
3) And instead being a void method, you could return the max series number.
4) Besides this :
for (int a = 0; a < adriana.length(); a++) {
if (adriana.charAt(a) == adriana.charAt(a + 1)) {
will throw a StringIndexOutOfBoundsException as adriana.charAt(a + 1) refers to an index beyond the valid limit of the String length.
You should rather iterate until the last index -1 :
for (int a = 0; a < adriana.length()-1; a++) {
5) At last this is not consistent since you update maxreps by relying on maxreps instead of current :
if(maxreps>=current){
maxreps=current;
}
You should rather write :
if (current >= maxreps) {
maxreps = current;
}
So, finally the method would be :
public int computeMaxSeries(){
int current=1;
int maxreps=1;
String adriana = "aabbddddnsspkrrgg";
for(int a=0; a<adriana.length()-1; a++){
if(adriana.charAt(a) == adriana.charAt(a+1)){
current++;
if (current >= maxreps) {
maxreps = current;
}
}
}
return maxreps;
}
Now you can do :
final int maxreps = fritz.computeMaxSeries();
System.out.println(maxreps);
I have an action listener that calls some methods and one of those methods counts the number of times that a loop inside of another method is run. The problem I am having is that the counter just adds to itself (I understand why I just don't know how to fix it) rather than resetting back to 0.
Here is my action listener code.
public double computeIterative(double n) throws InvalidInput {
int a=1, b=2;
int result = 0;
if (n>=0) {
if(n==0)return 0;
if(n==1)return 1;
if(n==2)return 2;
for(int i = 3; i <= n; i++) {
result = a+(2*b);
a=b;
b = result;
this.getEfficiency();
}
} else{
throw new InvalidInput();
}
return result;
}
ActionListener that calls methods and sets text:
public void actionPerformed(ActionEvent e) {
int n = Integer.parseInt(nField.getText());
//Try Catch for Iterate Radio Button
if (iterateBtn.isSelected()){
try {
double result = sequence.computeIterative(n);
int efficiency = sequence.getEfficiency();
rField.setText(Double.toString(result));
eField.setText(Integer.toString(efficiency));
}
catch (InvalidInput ex) {
}
}
The getEfficiency method counts how many times the loop inside computeIterative method is run and then sets it to a textField.
Here is my getEfficiency method:
public int getEfficiency() {
efficiency++;
return efficiency;
}
Now obviously this will just keep adding onto itself, and I am sure that I am looking way too hard for a solution but I just cant figure it out.
Basically, after the try, catch, I need to set efficiency to 0 so that the next time the computeIterative(n) method is called, I get a proper reading.
You could simply add a method resetEfficiency():
public int resetEfficiency() {
efficiency = 0;
}
And then call it at the beginning of computeIterative():
public double computeIterative(double n) throws InvalidInput {
this.resetEfficiency();
//rest of code goes here
//....
}
(Of course I'm assuming this is not multi-threaded or anything).
public double computeIterative(double n) throws InvalidInput {
int a=1, b=2;
int result = 0;
this.resetEfficiencyCounter(); //Call Reset if Number Got Invalid.
if (n>=0) {
if(n==0)return 0;
if(n==1)return 1;
if(n==2)return 2;
for(int i = 3; i <= n; i++) {
result = a+(2*b);
a=b;
b = result;
this.getEfficiency();
}
} else{
throw new InvalidInput();
}
return result;
}
add new Function Named resetEfficiencyCounter().
private void resetEfficiencyCounter(){
this.efficiency = 0;
}
I know that I'm overlooking something incredibly fundamental and elementary, but I need help with creating a mean function that, using only one parameter (the list containing the integers- in this case), calculates the mean of the given integers.
public static double mean (Cons lst) {
int total = (Integer) lst.data;
int count = //something to keep count through the recursion
if(lst.next == null) {
return total / count;
}
else return mean(lst.next); // return statement isn't correct, need help here as well
}
Any help would be great. If the easiest way to explain is by writing the method itself, then that'd be wonderful, but I'm just trying to figure out how to recursively keep a running count without adding params.
Thanks a lot.
You are developing your recursive mean function as a method of a Java Class. Why don't you declare your count and total local variables as attributes of that class?
class Mean {
static int total = 0;
static int count = 0;
public static double mean (Cons lst) {
total += (Integer) lst.data;
count += 1;
if(lst.next == null) {
double ret = total/count;
total = 0;
count = 0;
return ret;
}
return mean(lst.next); // return statement isn't correct, need help here as well
}
}
Other option is to include "count" as a second parameter of your recursive method. If you don't want the user to pass more parameters use two methods: "mean" method, with one parameter (your list), should call the second method "recursiveMean(list, 0)" containing your implementation.
public static double mean (Cons lst) {
return recursiveMean (lst, 0, 0)
}
public static double recursiveMean (Cons lst, int count, int total) {
total += (Integer) lst.data;
count += 1;
if(lst.next == null) {
return total / count;
}
return mean(lst.next,count,total); // return statement isn't correct, need help here as well
}
Nevertheless, I don't see why you are implementing a mean function as a recursive function unless it is some kind of educational exercise.