I want the variable called "number" to stay the same value when the method is called multiple times. It seems like it resets between each method call. I don't see why it would because the variable is declared outside the method.
This is the first class:
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
for(int counter = 0; counter < 5; counter++) {
Output display = new Output();
display.outputNumber();
}
}
}
This is the second class:
public class Output {
int number;
public void outputNumber() {
number++;
System.out.println(number);
}
}
When I run this, it outputs
1
1
1
1
1
I want it to output:
1
2
3
4
5
Moving this line of code: Output display = new Output(); outside the loop should give you the desired output.
Each time you create a new object, the number of that object is initialized to 0, which explains your current output.
Reusing the object reuses number, and hence you get the desired output.
Every time you create a new Output(), you create a new object that starts from scratch. In this case, you are creating 5 new objects, incrementing each only once, and getting your series of 1s.
You will probably want to create a single Output outside of the loop and then simply increment inside the loop. That way it's the same object, and the values are thus maintained.
Your Output object is getting created for each loop and the number variable of the Output class is always instantiated to the default int value of 0. Hence each time it increments 0 to 1 and displays only 1.
You could either drop incrementing the number variable in the Output class and do the increment in the actual class and pass the value to the Output class.
public class Output {
int number;
public Output (int number) {
this.number = number;
}
public void outputNumber() {
System.out.println(number);
}
}
And accordingly, change your calls to the Output class from the for loop in the Input class as well.
You also might want to change the for loop counter variable instantion from 0 to 1 and change the condition check to <=5 instead of <5.
Related
Im supposed to write a method divideByTwo that takes an integer as a parameter and returns the number divided by 2. and i need to try to solve the problem with a single program statement in the method. I don't know how to fix the problem, i've used modulo, while loop, changed the return value but still don't know what i am doing wrong. Any kind of help appreciated!
this is what i've done so far:
public static int divideByTwo(int a){
int i = 0;
while(i < 1){
System.out.print(a/2);
i++;
}
return a;
}
expected output
The reason why you are getting 51 when you're entering 10 in the example is because it prints 10/2 = 5 and then it returns i which is 1. Then you are printing the method with parameter 10 which prints 5 in the method and then 1 as the return value. If you just want to divide the number by two, then all you need to write in the method is return a/2; and then just print the method divideByTwo(a);.
You are out-thinking yourself. The method has a simple purpose - divide the value provided by 2 and return that result.
remove the print statement - there is nothing to print
remove the loop and loop variable - there is nothing to loop over
That leaves you with...
public static int divideByTwo(int a) {
return a;
}
... but we don't want a - we want a divided by 2. You did the division in your print statement so do that division in the return statement and you are done.
public static int divideByTwo(int a) {
return a/2;
}
The answer was in you all along!
I have a sceanrio where there is a list of 12 items in a page but at a time, it will display 5 items
in the screen,we need to scroll
down to get the list of remainig 7 items, I need to print the Number of these items( 0,1,2----11),
I have written a for loop in a funtion which will run for the first 5 item till its max size,then again scroll,
then again Iam calling the function containing forloop to get number of remaining item.
At first ,i can print by giving System.println(i) which will print
0 to 5 but second time when the loop runs, it will again print 0 to 5 for the remaining set of items,intead i need to
print 6,7,8 and so on.
Below is the method which iam calling:
switchToggleAndClickInfoIcon(); //first loop will run to print numbers for each list till 7 which is good
scrollToElement("Brakes"); //scroll down for next set of items
switchToggleAndClickInfoIcon(); //again loop will execute but numebr will again print 0 to 7 instead I need 8,9,10,11 etc
Below is the loop implementation:-
public void switchToggleAndClickInfoIcon{
for(int i=0;i<list.size();i++{
System.out.println( "Serial no" +i ,+list.get(i).text());
//here i is printing 0 to 7 when this method is called first which is fine but when again scrolled and called this method again, loop will print 0 to 7, instead i need to print the next 8 , 9,10.....
}
Thanks for the additional info. I have created a sample approach to retrieve the value from the given lastIndex value. it will be holding the last index value to continue the next iteration with as starting index.
public class TestCode {
private static int lastIndex = 0;
public static void main(String[] args) {
List<Integer> value = new ArrayList<Integer>();
for(int i =0;i<10;i++) {
value.add(i);
}
retrieveValueFromList(value);
value.add(10);
value.add(11);
value.add(12);
value.add(13);
value.add(14);
retrieveValueFromList(value);
}
public static void retrieveValueFromList(List<Integer> holder) {
for (int i = lastIndex; i < holder.size(); i++) {
System.out.println("value from the list : "+i);
}
}
}
so this is the main code for my text-based game.
import java.util.Scanner;
public class D_M_RPG {
public static void main(String[] args) {
//Creating the class to call on my toolbox
D_M_RPGtoolbox toolbox = new D_M_RPGtoolbox();
//Creating the scanner class for user input
Scanner input = new Scanner(System.in);
//Initiating variables and final variables aswell as arrays
//token variable to validate open spots in an array
int slotCounter = 0;
int inventoryExpander = 11;
//First initiated will be the character creation variables
String hairColor = "";
String eyeColor = "";
String skinColor = "";
String gender = "";
//Initiating the arrays for character inventory slots
String[] weaponSlots = new String[10];
//initiating the arrays for the character creation
String[] hairColorARR = {"black","Green","Yellow","Brown","Blue","Blonde","Grey","White"};
String[] eyeColorARR = {"Green","Brown","Blue","Grey",};
String[] skinColorARR = {"White","brown","Black",};
String[] genderARR = {"Male","Female"};
//Creating the introduction title and introduction
System.out.println("Welcome to, COLD OMEN.");
System.out.println("\nNOVEMBER 12th, 2150: ONTARIO, CANADA");
System.out.println("\nYou hear loud shouts and gun fire all around you but can't pinpoint the location of anything, you feel a bit dazed until someone grabs you and you open your eyes and snap out of it.");
System.out.println("\nUnknown: 'Get up, its time to move out. Take this.'");
System.out.println("\nUnknown hands you a 'M4-A4 RIFLE'");
System.out.println("\nyou manage to catch a small glimpse of him before you get up.");
//Character creation screen
System.out.println();
//ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "M4-A4 RIFLE");
System.out.println("\n" + weaponSlots[0]);
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "ak47");
System.out.println(weaponSlots[0]);
}
}
so I have this method I made to basically add an "item" to the weaponSlots array (the inventory) but whenever I run it it will add to the first element in the array [0] but it wont incremement the slotcounter which should go up by one every time the method is used so that I dont replace any items in the array It should just add items until its full which is checked using the inventoryExpander variable. at the moment I have it printing the element at 0 and 0 for the array but i have checked 1 aswell and 1 is just null no item added it only just replaces the element at 0. heres the code for the method to increment etc:
public class D_M_RPGtoolbox {
//method for random number generating to be used for crit hits, turns, loot generation etc
public int randomGen(){
int x = (int) (Math.random()*((20-0)+1)+0);
return x;
}
//method for inserting into an array ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER FIX
public void insert(String[] a, int b, int d , String c) {
if(b < d) {
a[b] = c;
b++;
}//end of if statement
}//end of method
}
What you are actually performing the ++ operation on in b is a copy of the value in slotCounter.
The variable slotCounter is passed into insert "by-value".
This unlike what you probably imagine, that it is passed "by-reference".
One solution would be to do the slotCounter++ from the call row instead; and another would be to let the toolbox own the slotCounter variable completely.
This question uses the image of passing a copy of document content (by value) where changes to the document would not be seen by the sender; or as a link to a shared document (by reference), where changes could be made to the same page that the sender sees.
Its always going to be zero since you are passing zero and incrementing the local variable b.
Try calling the method as below with post increment ++ to slotCounter and see if it works for you,
toolbox.insert(weaponSlots, slotCounter++, inventoryExpander, "M4-A4 RIFLE");
public class Test
{
public static int addOne(int[] numb)
{
for(int i=0;i<numb.length;i++){
System.out.println(numb[i]+1);
int result = numb[i];
}
return (numbers.length);
}
}
Main:
public class Main
{
public static void main(String[] args)
{
int[] numO = {2,2,4,4,6};
System.out.println(Test.addOne(numO)); /
}
}
Output:
3,3,5,5,7,5
I was trying out arrays in java as I am starting to learn arrays, I set five numbers in the array and using a for loop, wanted to add the numbers in the array by 1, e.g. Array containing (1,2,3) would be (2,3,4) and outputting the total number 9, instead of 2,3,4 and a random number. How can I achieve this?
You are never actually changing the value contained within the numb array, what you are doing is taking the existing value and adding outputting it with 1 added to it
System.out.println(numb[i] + 1);
To change the value you must increment the value outside
numb[i]++;
System.out.println(numb[i]);
That should solve your problem of not retaining the changed value in the array. However there is another error that I can see that would prevent you from outputting the correct result value. By doing result + numb[i]; you are preforming an operation but not setting the result variable equal to anything. To set it add to the value it already contains you would do result = result + numb[i] or more properly result += numb[i]
Hope this helps!
I have a 10x10 multiplication table. I need to code in so that when a user inputs a certain number, 50 for example, the numbers >50 are replaced by a character and the rest remain the same.
I know how to do this using strings but I have no clue how to do this in this situation. Any help will be appreciated.
public class task4{
public static void main(String args[]){
int Multiples = 10;
System.out.format(" Table");
for(int z = 1; z<=Multiples;z++ ) {
System.out.format("%5d",z);
}
System.out.println();
System.out.println("-------------------------------------------------------------------------------------------------------");
for(int i = 1 ;i<=Multiples;i++) {
System.out.format("%5d |",i);
for(int j=1;j<=Multiples;j++) {
System.out.format("%5d",i*j);
}
System.out.println();
}
}
}
That seems to be simple enough problem, basically you have table drawing code, your for loops, so we function that off into a nice little method public void drawTable(){} which we call to draw the table initially, but we also provide an overloaded version which takes a number public void drawTable(int maxDispNum){} and this method is the same except if i*j >maxDispNum we print a character instead. then in main we can simply while(true){ read val; drawTable(val);}
alternativley if you want to maintain a permanent record of what's been removed stored the table in an array, 10*10 in your case and use some marker, -1 works here to indicate removed, and simply check for that in your draw method,