Variable is reset after loop - java

I'm learning Java and have written a program with a for loop in it. But my variable is 0 after I print it out. Why does it get reset? This is my code:
Private static int number;
public static void main(String[] args)
{
int number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print();
}
public static void print()
{
System.out.println("Print: " + number);
}
This is the result:
run:
Main: 10
Print: 0
BUILD SUCCESSFUL (total time: 0 seconds)

Your variable is not reset. This might be hard to grasp when you're new but by saying int number; you create a new variable number of type int. Also keep in mind that variables will remain in the scope where they were created and can't be used outside that scope. This means that if you initialize a variable in a while loop, it will only be available from within that while loop. The same applies to methods.
You created a variable number on the first line, this variable can be used by every method in your class and is set to zero by default. However, you created another variable number in your main method. This second variable only exists within your main method because that's the scope where it was created in.
Let me give you some ways to fix this:
Private static int number;
public static void main(String[] args)
{
//By removing `int`, we reference the variable that has already been initialized
//instead of creating a new one
number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print();
}
public static void print()
{
System.out.println("Print: " + number);
}
This is a possibility if your variable doesn't have to be accessed any further:
public static void main(String[] args)
{
int number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print(number);
}
//We use the created variable as a parameter
public static void print(int number)
{
System.out.println("Print: " + number);
}

You have two declarations of number, one as a private static class variable, and one as an local variable in main. The local variable in main is hiding the other variable, so the static variable isn't being updated at all.

You have two variables with the same name. One is a local variable which is updated in the main loop:
public static void main(String[] args)
{
int number = 0;
//...
}
The other is a static variable which is initialised to zero:
Private static int number;
(by the way, Private should be lowercase)
Your print method is using the static variable (which never changes). You can fix this by passing a parameter to the print function:
public static void print(int number)
{
System.out.println("Print: " + number);
}
and call that from your main method like so:
print(number);
You should also remove the static variable. It's unnecessary.

you re-declared int number inside main() method. It is like to create new variable.
Just delete 'int' and it should work.
Private static int number;
public static void main(String[] args)
{
number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print();
}
public static void print()
{
System.out.println("Print: " + number);
}

You have 2 different variables named number.
One is Private static int number and another one is inside the main function int number = 0.
I believe you wanted the static member to be changed inside your loop, thus you have to remove the declaration from the main function.
Private static int number;
public static void main(String[] args)
{
number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print();
}
public static void print()
{
System.out.println("Print: " + number);
}

Your issue is to do with the scope of your variables. If you want to keep a static 'number' variable then don't include 'int' when you initialize it in the 'main' method. (see code below)
private static int number;
public static void main(String[] args)
{
number = 0; //you are now initialising the global static variable and not a local variable to the main method.
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print();
}
public static void print()
{
System.out.println("Print: " + number);
}
OR
Personally, I prefer to avoid using global variables. you can pass 'number' in as a parameter to the 'print' method instead.
public static void main(String[] args)
{
int number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print(number);
}
public static void print(int number)
{
System.out.println("Print: " + number);
}

Related

so ive been working on this code and i think it might need nested methods but idk [duplicate]

I'm creating a program that generates 100 random integers between 0 and 9 and displays the count for each number. I'm using an array of ten integers, counts, to store the number of 0s, 1s, ..., 9s.)
When I compile the program I get the error:
RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types;
generateNumbers();
required: int[]
found:generateNumbers();
reason: actual and formal argument lists differ in length
I get this error for the lines of code that I call the methods generateNumbers() and displayCounts() in the main method.
public class RandomNumbers {
public static void main(String[] args) {
//declares array for random numbers
int[] numbers = new int [99];
//calls the generateNumbers method
generateNumbers();
//calls the displayCounts method
displayCounts();
}
//*****************************************************************
private static int generateNumbers(int[] numbers){
for(int i = 0; i < 100; i++){
int randomNumber;
randomNumber = (int)(Math.random() *10);
numbers[i] = randomNumber;
return randomNumber;
}
}
//*****************************************************************
private static void displayCounts(int[] numbers){
int[] frequency = new int[10];
for(int i = 0, size = numbers.length; i < size; i++ ){
System.out.println((i) + " counts = " + frequency[i]);
}
}//end of displayCounts
}//end of class
generateNumbers() expects a parameter and you aren't passing one in!
generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.
call generateNumbers(numbers);, your generateNumbers(); expects int[] as an argument ans you were passing none, thus the error
The generateNumbers(int[] numbers) function definition has arguments (int[] numbers)that expects an array of integers. However, in the main, generateNumbers(); doesn't have any arguments.
To resolve it, simply add an array of numbers to the arguments while calling thegenerateNumbers() function in the main.
I think you want something like this. The formatting is off, but it should give the essential information you want.
import java.util.Scanner;
public class BookstoreCredit
{
public static void computeDiscount(String name, double gpa)
{
double credits;
credits = gpa * 10;
System.out.println(name + " your GPA is " +
gpa + " so your credit is $" + credits);
}
public static void main (String args[])
{
String studentName;
double gradeAverage;
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter Student name: ");
studentName = inputDevice.nextLine();
System.out.println("Enter student GPA: ");
gradeAverage = inputDevice.nextDouble();
computeDiscount(studentName, gradeAverage);
}
}
pass the array as a parameter when call the function, like
(generateNumbers(parameter),displayCounts(parameter))
If you get this error with Dagger Android dependency injection, first just try and clean and rebuild project. If that doesn't work, maybe delete the project .gradle cache. Sometimes Dagger just fails to generate the needed factory classes on changes.
public class RandomNumbers {
public static void main(String[] args) {
//declares array for random numbers
int[] numbers = new int [100];
//calls the generateNumbers method
generateNumbers(numbers); //passing the empty array
//calls the displayCounts method
displayCounts(numbers); //passing the array filled with random numbers
}
//*****************************************************************
private static void generateNumbers(int[] numbers){
for(int i = 0; i < 100; i++){
int randomNumber;
randomNumber = (int)(Math.random() *10);
numbers[i] = randomNumber;
} // here the function doesn't need to return.Since array is non primitive data type the changes done in the function automatically gets save in original array.
}
//*****************************************************************
private static void displayCounts(int[] numbers){
int count;
for(int i = 0, size = 10; i < size; i++ ){
count=0;
for(int j = 0; j < numbers.length ; j++ ){
if(i == numbers[j])
count++; //counts each occurence of digits ranging from 0 to 9
}
System.out.println((i) + " counts = " + count);
}
}//end of displayCounts
}//end of class

Output will not print the correct information

I'm trying to make a program which asks the user a particular bird then how many of them they had seen at that point. If the use at any point enters the word 'END' then the system should print out the most seen bird and the number seen. However, when running my program if I enter 'END' at random points it instead returns that the most seen was END with 0 seen. I can't figure out how to make it work. I've tried different methods but it's just not working properly. Also, I've set the maximum array limit to 10 possitions but it continues after 10 and if i enter a value the system crashes. Have I written the limit part properly? Or am I missing something important?
import java.util.Scanner;
public class testing
{
public static void main (String[] param)
{
birdInput();
most();
System.exit(0);
}
public static void birdInput()
{
int i = 0;
String birdInput;
int numberInput;
Scanner scanner = new Scanner(System.in);
int maxVal = Integer.MIN_VALUE;
int maxValIndex = -1;
while (true)
{
System.out.println("What bird did you see?");
birdInput = scanner.nextLine();
if (birdInput.equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.exit(0);
}
else
{
String[] birds = new String[10];
int[] numbers = new int[10];
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
if (birds[i].equals("END"))
{
maxVal = numbers[i];
maxValIndex = i;
System.out.print("\nThe most common bird that you saw was the " + birds[maxValIndex] + " with " + maxVal + " being seen in total\n");
System.exit(0);
}
}
}
}
public static void most()
{
System.out.println("fdff");
}
}
This is my edit of Till Hemmerich's answer to my issue. I tried to remove the global variables and so combine the entire code into 1 method. However, I'm still having some issues. Been working at it but really confused.
import java.util.Scanner;
public class birds2
{
public static void main(String[] param)
{
birdInput();
System.exit(0);
}
public static void birdInput()
{
Scanner scanner = new Scanner(System.in);
String[] birds = new String[99999999];
int[] numbers = new int[99999999];
int i = 0;
int maxIndex;
while (i <= birds.length)
{
System.out.println("What bird did you see?");
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
}
int newnumber = numbers[i];
if ((newnumber > numbers.length))
{
maxIndex = i;
i++;
}
if (birds[i].toUpperCase().equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
}
}
You're re-declaring the birds and numbers arrays in each iteration of the loop. They should be declared and initialized only once, before the loop.
I changed a lot so im going to explain my changes here in total.
First of all i had to move the Array Definition out of your while-loop as >mentioned above, since other wise you would override these Arrays every time.
I also made them globally accessible to work with them in other methods.
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
in general I re structured the whole code a little bit to make it more readable and a little bit more object-orientated.
For example I created an method called inputCheck() which returns our input as a String and check if it equals END so you do not have to write your logic for this twice. (it also considers writing end lower or Uppercased by just Upper our input before checking it"if (input.toUpperCase().equals("END"))")
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
this method can now be called every time you need an input like this:
birds[i] = inputCheck();
but you need to be carefull if you want to get an integer out of it you first have to parse it like this:Integer.parseInt(inputCheck())
after that I wrote a method to search for the biggest Value in your numbers Array and getting its index:
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
it takes an int array as parameter and returns the index of the highest element in there as an Integer. Called like this:maxIndex = getMaxIndex(numbers);
Then after that I rewrote your end method. It now just calles our getMaxIndex method and prints some output to the console.
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
to fix your last problem (crashing after more then 10 inputs)I changed your while-loop. Since your array only has 10 places to put things it crashes if you try to put information in place number 11. it not looks like this:while (i <= birds.length) instead of while (true) this way the max loops it can take is the amout of places Array birds has and it wont crash anymore.
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
Here is the whole code in total:
import java.util.Scanner;
/**
*
* #author E0268617
*/
public class JavaApplication1 {
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
public static void main(String[] param) {
birdInput();
most();
System.exit(0);
}
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
public static void most() {
System.out.println("fdff");
}
}
I hope you understand where the Problems had been hidden if you have any Questions hit me up.

Return value executing a method?

import java.util.*;
public class Guess {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
intro();
int numGames = 0;
int numGuesses = game(console, r);
int max = max(numGuesses);
String again = "y";
do {
game(console, r);
System.out.println("Do you want to play again?");
again = console.next();
System.out.println();
numGames++;
} while (again.startsWith("y") || again.startsWith("Y"));
stats(numGames, numGuesses, max);
}
public static void intro() {...}
public static int game(Scanner console, Random r) {
System.out.println("I'm thinking of a number between 1 and 100...");
int answer = r.nextInt(100) + 1;
System.out.println("answer = " + answer);
int guess = -1;
int numGuesses = 0;
while (answer != guess) {
System.out.print("Your guess? ");
guess = console.nextInt();
numGuesses++;
if (guess > answer) {
System.out.println("It's lower.");
} else if (guess < answer) {
System.out.println("It's higher.");
} else {
System.out.println("You got it right in " + numGuesses + " guesses");
}
max(numGuesses);
}
return numGuesses;
}
public static int max(int numGuesses) {
int max = numGuesses;
if (max > numGuesses) {
max = numGuesses;
}
return max;
}
public static void stats(int numGames, int numGuesses, int max) {
System.out.println("Overall results:");
System.out.println(" total games = " + numGames);
System.out.println(" total guesses = " + numGuesses);
System.out.println(" guesses/game = " + numGuesses / numGames / 1.0);
System.out.println(" best game = " + max);
}
}
So this is a small part of my program and the problem I'm having is that my initial int for numGuesses (int numGuesses = game(console, r);) is executing the game method shown below.
All I want from the game method is the return value of numGuesses so that I can forward the value into a different method called stats(numGames, numGuesses, max); . How do I make it so that the initial value isn't executing the method and only the do/while loop is?
Is the way I produce a return statement wrong? Also, my return values aren't saving in my stats method so when I run it, I get the wrong answers.
Then you should put the code that's responsible of generating numGuesses in another method that you will use on both main and game, for example:
public static int game(Scanner console, Random r) {
int numGuesses = getNumberOfGuesses(..);
//continue implementation here
}
public static void main(String[] args) {
int numGuesses = getNumberOfGuesses(..);
//use value
}
You should get familiar with class variables. At the top of your class, you can declare a variable and also give it a value. That is what you should do with numGuesses if you want to access it from different methods in your class. Here is the Foobar example:
class Foo {
private int bar = 0;
private void foobar(int arg) {...}
}
You just need to watch out that you don't do int numGuesses somewehere in a method as that would create a second local variable. The class variable can be accessed via just the name.
Next, you want to keep track of the total games played and the total guesses. You can guess now (hahaha), that you need to use class variables as well. If you need to keep track of the total guesses even when the program is restarted you will need to store these values in a file, but that will be for another time.
Finally, two more little things.
1.) The method max. I do not know what max should do, but at the moment it is just returning the value passed to it. Also the if statement will never execute (x can't be higher than x).
2.) You should maybe consider not making everything static. It obviously works that way, but that is not, what is called object-oriented programming.

No main type error in java

This is the source code:
package feetToInches2;
public class Feet2Inches {
private double feetToInches_(double feet) {
return 12* feet;
}
private int max(int val1 int val2) {
if (val1 > val2) {
} else {
return (val2);
}
return 0;
}
}
When I try to run it, it says "Selection does not contain main type". I have asked my professor and he says sometimes eclipse does that and all I need to do is restart my computer. Is that true?
What you need is a main method. It is an entry point
public static void main(String[] args) {
//Your code here
}
in your case it can look like:
package feetToInches2;
public class Feet2Inches {
public double feetToInches_ (double feet) {
return 12* feet;
}
public int max(int val1, int val2) {
if (val1 > val2) {
return (val1);
}
else {
return (val2);
}
}
public static void main(String[] args) {
Feet2Inches converter=new Feet2Inches();
int max = converter.max(100,50);
double inches = converter.feetToInches_(10.5);
System.out.println("Max value = " + max);
System.out.println("Inches = " + inches);
}
}
i've changed your method modifiers so it would be more usefull. Class with no public method is unneeded class ;) I also fixed some of errors in your code.
EDIT:
If you want to allow people to youse your code to their own calculation you have two choises. You can take parameters from args array which holds parameters that was program runned with. or you can prompt for a data at the runtime.
1 Using parameters
public static void main(String[] args) {
Feet2Inches converter = new Feet2Inches();
if (args.length != 3) {
System.err.println("Missing arguments! give me three numbers");
System.exit(1);//error exit
}
int val1 = Integer.valueOf(args[0]);
int val2 = Integer.valueOf(args[1]);
double val3 = Double.valueOf(args[1]);
int max = converter.max(val1, val2);
double inches = converter.feetToInches_(val3);
System.out.println("Max value from (" + val1 + "," + val2 + ")= " + max);
System.out.println(val3 + "Feet = " + inches + " inches");
}
now you have to call your program with arguments Here you can see how to do it from cmd and Here is how to do it in Eclipse
2 ask user for parameters at runtime
public static void main(String[] args) {
Feet2Inches converter = new Feet2Inches();
Scanner input = new Scanner(System.in);
System.out.print("Argument 1:");
int val1 = input.nextInt();
System.out.print("Argument 2:");
int val2 = input.nextInt();
System.out.print("Argument 3:");
double val3 = input.nextDouble();
int max = converter.max(val1, val2);
double inches = converter.feetToInches_(val3);
System.out.println("Max value from (" + val1 + "," + val2 + ")= " + max);
System.out.println(val3 + "Feet = " + inches + " inches");
}
This is wrong
private int max(int val1 int val2)
it should be
private int max(int val1, int val2)
on top of that you a public static void main(String[] args) { from which you can call your methods.
In order to run a Java Application you always need to have public static void main(String[] args) method defined. This method should contain whatever the code you need to execute.

A program which calculate factorial from 1-9 by iteration

I am trying to write a program which can calculate factorial from 1-9 by iteration, but I encounter some problems while I am trying to. Please help me figure out my problems in my program, I am just learning programming.
The following is my program, please tell me what's wrong with it:
public class iterative {
static int ans=1;
public static void iteration() {
System.out.println("n n!");
for (int n=1; n<10; n++) {
while ((n-1)>0)
ans=n*(n-1);
System.out.println(n + " " + ans);
}
}
public static void main(String[] args) {
iteration();
}
}
First of all, don't use a static for ans. A local is what you want.
Secondly the factorial recurrence relationship you use is incorrect. You should do it like this.
int ans = 1;
for (int n=1; n<=9; n++) {
ans = ans*n;
System.out.println(n + " " + ans);
}
The answers above is close perfect,you also get it with the recursion:
here is code:
public class iterative {
public static int iteration(int n) {
int result;
if(n==1)return n;
else
result = n*iteration(n-1);
return result;
}
public static void main(String[] args) {
System.out.println("Result is :" + iteration(9));
}
}
I see three big problems.
Firstly, "ans" is global and is never reassigned. So over time it will display an accumulated incorrect value.
The other is that the while loop will run forever for n > 1.
Lastly, the recurrence relationship is wrong. Should be ans = ans * (n-1). See code.
The fact that you have nested loops suggests to me that you are trying to print a table of factorials.
Try this:
for (int n=1; n<10; n++) {
int ans = 1;
int x = 0;
while ((n-x)>0){
ans=ans*(n-x);
x++;
}
System.out.println(n + " " + ans);
}
Like #David's solution but shorter
for(int i=1, ans=1; i <= 9; i++, ans *= i)
System.out.println(i + " " + ans);
Your algorithm needed work as well:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
int i = 1;
while(i < 10)
iteration(i++);
}
public static void iteration(int max) {
System.out.println("n n!");
int ans = 1;
for (int n=1; n<=max; n++) {
ans *= n;
}
System.out.println(" " + ans);
}
ideone example

Categories

Resources