Changing a variable though a module in a loop (java) - java

So I am trying to write a simple program for my Java class and I have asked the teacher for help however, this is a distance learning class and am not getting much help from that direction. So here I am.
The problem we have been asked to solve is to create a program that will
(1) ask the user for a number ,
(2) find the sum of all user defined numbers ,
(3) find the average of these numbers ,
(4) then out put them back to the user.
I use the numbers not only to line through things I have finished but because they must be separate modules to be called.
How can i get the userNum variable to update durring the while statments. Currently they are not. OR is there a simpler way to do this that im overlooking. Any help is greatly appreciated. Thank you.
public class P2 {
public static void main(String[] args) {
int userNumCount = 1;
double userNum = input();
double userSum = sum(userNum);
double userAverage = average(userSum, userNumCount);
sum(userNum);
while (userNum != 0 && sum(userNum) <= 100){
++userNumCount;
output(userSum, userAverage);
input();
sum(userNum);
average(userSum, userNumCount);
}//end else
while (userNum != 0 && sum(userNum) >=100){
++userNumCount;
JOptionPane.showMessageDialog (null, "Warning, your sum is currently over 100!!!!!");
output(sum(userNum), userAverage);
input();
sum(userNum);
average(userSum, userNumCount);
}//end else
if (input() == 0){
output(userSum, userAverage);
JOptionPane.showMessageDialog (null, "Thank you for using this program have a nice day.");
}//end else if
}//end main module
public static double input(){
String userNumString;
userNumString = JOptionPane.showInputDialog("Please enter your number or input 0 to end the program.");
double userInput = Double.parseDouble (userNumString);
return userInput;
}//end input module
public static double sum(double userNum){
double userSum =+userNum;
return userSum;
}//end sum module
public static double average (double userSum, int userNumCount){
double userAverage = userSum/userNumCount;
return userAverage;
}//end average module
public static void output (double userSum, double userAverage){
JOptionPane.showMessageDialog (null, "The sum of the numbers input so far is: " + userSum + ". And the Average is " + userAverage + "." );
}//end output module
}//end class

All of the values returned from methods in your main are just returning their values to nothing. When you pass variables to a function, they are passed by value. For example:
public void main(String args[]){
int f = 5;
doSomething(f);
System.out.println(f);
}
public int doSomething(int i){
i+=1;
return i;
}
The value returned by doSomething is 6, but the program outputs 5. When you call a function the int i is recreated independently of f. As of now, your program is just throwing those values away and keeping the old ones.
Also you have the variables in main called userSum, and userAverage, and in sum and average you redefine these in a different scope. When code flow comes into sum and average it creates new variables for that method. If you want these values to be the same you need to make them static, by defining them outside of your main method and declaring them static.
I think the problem you might be struggling with is scope. Pretty much every time you have an opening bracket the program changes scope. When a block is closed (when there is a closing bracket}, the scope of the variables ends, ie. they don't exist anymore. For example:
class someClass
{
//Block 0
static int staticNum = 0;
public static main(String args[])
{
//Block 1
int level1 = 0;
if(true)
{
//Block 2
int level2 = 0;
} else {
//Block 3
level1++; //ok because the level1 is accessible from here
staticNum++; //ok because staticNum is static
}
//resume block 1
level2++; //not ok because level2 was in a different scope
doSomething(level1)
}
public static void doSomething(int i){
//Block 5
int level1 = 0; //different than the one in the main method
i++; //ok but once execution leaves i wont exist anymore
staticNum++; //ok because staticNum is static and exists in the class's scope
level1++; //not ok because level1 is not defined for this scope
}
}
While execution is in a block, it can access any variable in blocks 'above' it in nesting level. Looking at the above, in Block 2 and 3 you can access anything in block 1 or block 0. Block 3 doesn't have access to the variables in block 2 because they are out of scope of one another, because when a block closes all variables instantiated in that block are freed. Block 5 has a completely different scope than block 1,2 and 3.
Block 0 is special because it is associated with the class. Anything outside of method bodies declared static are class wide variables, as in you can access it where ever you have access to the class. You would use something like ClassName.staticNum to access it in another class. Also when you access it inside of the class, any methods that you use the static values in need to be declared static as well.
Anything not declared static in the class body is an instance variable. It is associated with an instances of the class, these instances called objects. A class defines the template of an object. For example, lets say we have two objects of type Computer. The class Computer defines what variables each individual computer has(instance variables), and what variables every computer shares(static variables). So if I have Computer A with instance variables mouse and keyboard, it is completely different from another Computer B instance variables mouse and keyboard, but they can share a static variable called Computer.innernette.

This is incorrect.
public static double sum(double userNum){
double userSum =+userNum;
return userSum;
}
In a basic pseudo-language this is happening each time this method is called
receive userNum
create userSum
set userSum = 0
add userNum to userSum
give userSum
each time the method will return the value it is given, not the running total I think you are expecting.
If you have two variables declared with the same name, they are still different. What you want to do is refer to the same variable, to do this you need to have the references in the scope where the variable is declared.
to get the running total
public class P2 {
public static double userSum = 0;
//because this is a public member it's scope is global i.e. you can refer to it anywhere.
...
public static void main(String[] args) {
...
/* do not declare userSum here.
if you do any reference to userSum will use the local variable
not the global variable.
double userSum = 0; <-- declare local variable it's scope is until the
end of this method nothing outside the method
can see it but you can pass it as a parameter
userSum = 1; <-- local variable is set to 1
P2.userSum = 2; <-- local variable is set to 1 global is set to 2
*/
input();// for this the input method is called and returns a value,
// but you haven't said to put it anywhere so java will throw it away
// all that effort for nothing.
userNum = input(); // in this case it will put the new value in userNum.
}
public static double sum(double userNum){
userSum =+userNum; // do not declare userSum use it from the class context
return userSum;
}
...
}
for further reference scope

Related

How to make Java ignore previous instructions if specified sum is given?

Literally started with Java today, and my professor has given my class the task of modifying some very basic code.
I want to modify the code to make it print a message if the sum of n1 and n2 is 666, but I don't want it to print the actual sum or the message that would normally go attached to it. I saw somewhere around here that a similar question was asked, but the solution doesn't seem to work for me. I have no idea why. Please help.
import java.io.Console;
import java.util.Scanner;
public class FirstProgram{
Console t = new Console();
public static void main(String[] args)
{
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
int n1, n2;
Scanner keyboard = new Scanner(System.in);
n1 = keyboard.nextInt( );
n2 = keyboard.nextInt( );
//This should print normally when the sum is anything BUT 666
System.out.println("The sum of those two numbers is");
System.out.println(n1 + n2);
//If the sum IS 666, I don't want it to print the above lines, just the one below.
if (n1 + n2 == 666);
t.println("Nice try, Satan");
}
}
It gives two major errors: the constructor Console() is not visible, and that I cannot make a static reference to a non-static field t. I have no idea what any of that means or how to fix it.
You should learn how to make conditional statements. Java will not "ignore" and pass to another thing if you don't tell it how to do that. Remeber: computer can't do anything if one do not tell it to do and how to do that.
You are not initializing n1 and n2, they should be initialized after getting the value from the input.
And as said in the comments, always wrap loops, conditional statements within curly braces{} to make sure the code that will be executed be the one inside braces.
import java.util.Scanner;
public class FirstProgramm{
public static void main(String[] args){
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
Scanner keyboard = new Scanner(System.in);
int n1 = keyboard.nextInt( );
int n2 = keyboard.nextInt( );
//See? the result is stored inside this variable
int sum = n1 + n2;
//If the sum is equal 666 then print the message
if(sum == 666) {
System.out.println("Nice try, Satan");
}else {
//Else if the sum is something else, print it
System.out.println("The sum of those two numbers is");
System.out.println(sum);
}
}
}
You can even play with the operator that the if uses to evaluates the condition:
if(sum != 666) { //If sum is `not equal to` 666... if the sum is anything else than 666, print it
System.out.println("The sum of those two numbers is");
System.out.println(sum);
}else {// But if it is 666, print what is inside the parentheses
System.out.println("Nice try, Satan");
}
I will try to help you out here.
Firstly: the constructor Console() is not visible
I think this is in reference to the fact that Console was not really meant to be accessed like that. The constructor of Console is private, meaning that outside classes cannot access it. To remedy this issue, when you want to print to the console, use System.console.
Secondly: I cannot make a static reference to a non-static field t
This one is a bit difficult to explain to someone new. Your main function is static, which means it can be accessed without having to instantiate the class that contains it. Your variable t is a instance variable, meaning that it can be accessed by every function in the class when the class has be initialized. However, because the main function is static, you cannot access a non-static variable, because it may not be initialized yet. If you want to access a instance variable in a static function, you need to make that variable static as well, making it a class variable, which will always be accessible.
Lastly
To getting your code working, you need to read up on if statements. This is a conditional statement that is basically asking if this statement is true, do this. There is an else if and else statements as well that say else if this statement is true, do this and else do this.
Example of proper if/else if/else statement:
if(iAmTrue == true)
{
//do this
}
else if(theOtherIAmTrue == true)
{
//do this
}
else
{
//do this because everything else was not true
}
So to fix your code, you would need to do this:
if(n1 + n2 == 666)
{
System.out.println("Nice try, Satan");
}
else
{
//Put your other print message(s) here.
}
I have rewritten the code for you with a few recommendations to achieve what you need.
import java.util.Scanner;
public class FirstProgram {
// I have removed the Console variable, you don't need that.
// System.out.println prints to the console.
// Use constants for any number or string used to give them meaning
private static final int DEVILS_NUMBER = 666;
public static void main(String[] args) {
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
Scanner keyboard = new Scanner(System.in);
// declare variables next to where they are used.
// additionally, never declare more than one variable per line.
// never do this: int n1, n2;
int n1 = keyboard.nextInt();
int n2 = keyboard.nextInt();
// store the sum in a variable so you can refer to it without doing the sum many times
int sum = n1 + n2;
//If the sum IS DEVILS_NUMBER, I don't want it to print the above lines, just the one below.
// always test the positive possibility first, never the negation
if (DEVILS_NUMBER == sum) {
System.out.println("Nice try, Satan");
} else {
//This should print normally when the sum is anything BUT DEVILS_NUMBER
System.out.println("The sum of those two numbers is");
System.out.println(n1 + n2);
}
}
Last but not least, have a look at Java Google Style for tips on how to properly format your code. If you are using an IDE like Eclipse, Intellij or NetBeans it can automatically format the code for you.

Java - Why void when I'm storing value in variable

So, the question is. If I'm calling method guess from class - Player and it is a void-type method without return statement in it, how come I'm able to store result of number = (int)(Math.random() * 10) in number variable for 3 different objects (p1, p2, p3)?
I'm little confused about when should I use return statement or void-type methods, because if number = (int)(Math.random() * 10) is giving some results which I want to use, why then I don't need to return this results from a method to pass them to the number variable which I declared in int number = 0;
public class Player {
int number = 0;
public void guess() {
number = (int)(Math.random() * 10);
System.out.println("I'm guessing " + number);
}
}
A void method does not return anything, but it still allows you to do things. (Print to the console, modify variables etc) The void keyword just means that it doesn't return a value. (In void methods you can still use a blank return; to end the method) And because you are modifying your number variable in the GuessGame object the changes you make will stay even though you don't return a variable. Try this simple test to see what I mean:
//In your GuessGame class
int number = 0;
public void foo() {
number++;
}
public static void main(String[] args) {
GuessGames games = new GuessGames();
games.foo();
System.out.println(games.number);
//Outputs 1
}
docs for the return statement
The point is: where is the result of Math.random() * 10 physically stored on your computer when your program is run? You list two options.
Options 1: Instance field
In this case the compiler instructs your operating system to reserve space for a int variable for the whole life of the Player object. The player object may live for microseconds, seconds, minutes, hours, days, months, ... it depends! This storage space is usually find in the RAM of the computer and from Java you can access it with the syntax myPlayer.number as long as you have a Player reference somewhere.
Options 2: Return value
In this case the compiler finds the space to store the result of the computation in a register of the Java virtual machine, that you can mentally map to a register of the physical processor. This value will only at best survive for a couple of processor cycles (there are gazillinos in a GHz CPU, so it's really a tiny little fracion of a second) if you don't store it somewhere else - and if you don't it's lost forever. See the following example:
private int someRandom;
private int gimmeARandom() {
return Math.random() * 10;
}
private int test() {
int someRandom = gimmeARandom(); // --> store the value until end of method
this.someRandom = someRandom; // --> further keep it so we can read it later
gimmeARandom(); // --> what did it returned? We'll never know
}
Void is different than static - void just means the function does not return anything, but it can still be a instance method, i.e. one that is associated with each new instance of a class. I think you're confusing this with the functionality of static, which allows methods to be called without an instance of the class.

New method, <identifier> expected error

I'm trying to write a program (for an assignment) that will – based on two absolute parameters – determine wether or not someone will be eligible for financial support. To accomplish this I have created three new methods, and currently I'm down to 1 error that I simply cannot comprehend. The error says "identifier expected" on this part of the code (in the bottom:
static void metodeTekst(tekst)
Here is my code:
import java.util.Scanner;
public class MinOppgave2a
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
String tastatur;
System.out.println();
System.out.println("\r\n" + "For aa kunne beregne ditt stoettegrunnlag, må du oppgi alderen din: ");
tastatur = in.nextLine();
int alder = Integer.parseInt(tastatur);
System.out.println();
System.out.println("\r\n" + "Bor du hjemme? Skriv 1 for «Ja», eller 2 for «Nei»: ");
tastatur = in.nextLine();
int hjemme = Integer.parseInt(tastatur);
System.out.println();
int i = 0;
while (i < 2)
{
i = i + 0;
}
metodeAlder(alder);
metodeHjemme(hjemme);
System.out.println("Du vil faa full studiestoette!");
}
static void metodeAlder(int alder)
{
if (alder <= 18 || alder >= 45)
i++;
else
metodeTekst(tekst);
}
static void metodeHjemme(int hjemme)
{
if (hjemme == 2)
i++;
else
metodeTekst(tekst);
}
static void metodeTekst(tekst)
{
String tekst = ("Du vil faa redusert eller ingen studiestoette.");
System.out.println(tekst);
}
}
I've tried for a good while to find an answer online, but in most cases where people have gotten this error they have forgotten to write a main method. I have not, as you see. Thanks in advance – I'm really new to Java, and appreciate all help!
Your method metodeTekst is wrong. It should either be
static void metodeTekst()
{
String tekst = "Du vil faa redusert eller ingen studiestoette.";
System.out.println(tekst);
}
or
static void metodeTekst(String tekst)
{
System.out.println(tekst);
}
but then you have to call it like this:
metodeTekst("Du vil faa redusert eller ingen studiestoette.");
Edit for OP's comment:
There are many additional problems with your code. The variable i in metodeAlder and metodeHjemme is outside if the scope of where i is initially defined (in main). If you really need to alter this variable inside your methods you have to declare it as a static field outside of your main.
Besides after everything compiles fine, this part
while (i < 2)
{
i = i + 0;
}
is pointless. You'll end up in an endless loop since you never change i so it will always be < 2. I would remove all occurrences of i since it doesn't do any meaningful and is not at all needed in your program.
Edit 2:
For your question as to why the compiler only now complains about i: It first checked, if all your method signatures were correct. Since it ran into previous error (with the wrong signature), it didn't need to check further. Now that you've fixed it, the compiler could continue to check the syntax "inside" the methods. And since i is only defined outisde of the method's scopes, it didn't know what i is supposed to be, hence the next compiler error.
Edit 3:
To make my explanation clearer look at the following example:
{
// Outer Scope
{
// Inner Scope A
}
{
// Inner Scope B
}
{
// Inner Scope C
}
}
Here, the three inner scopes A, B, C are isolated from each other. So variables defined in inner scope A are not visible to the other inner scopes B and C. In contrast, variables defined in the outer scope are visible to all inner scopes, since they are part of the outer scope as well.

Why can't these variables be resolved?

I need to write a program and, in one step of it, I need to construct a function that calculates the number of rabbits.
The problem is that Eclipse shows a message saying that the variable I created "cannot be resolved to a variable" and I don't understand why it happens. Can someone help me?
Here is part of my code
I am showing all my code because it would get bigger and it is not needed, in order to solve this problem
class Rabbits {
static int nbRabbits = initRabbits; // ERROR HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
static int nbFoxes = initFoxes; // ERROR HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
int rabbits = 0;
public static int calculateRabbits(int rabbits, int foxes, double AttackRate) {
for (int i = 0; i < Duration; ++i) {
rabbits = nbRabbits;
nbRabbits *= (1.0 + Rabbits_growth_rate - AttackRate * nbFoxes);
}
return nbRabbits;
}
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
// Enter initial population
int initFoxes = enterPopulation("foxes", 2, keyb); //at least 2 foxes
int initRabbits = enterPopulation("rabbits", 5, keyb); //at least 5 rabbits
// SOME MORE CODE HERE
} // end main
} // end of class
initRabbits and initFoxes are variables entered by the user when I call enterPopulation method.
I'm new to Java and, unfortunately, I cannot change the logic of this code. For example, I cannot put the calculateRabbits method inside the main neither change the begin or the end of the code.
initRabbits only exists within the main method. That is it's scope.
You are attempting to statically reference something it can't see. You are attempting to populate nRabbits before a value for innitRabbits exists. This is impossible.
Your trying to assign a value to your nb variables from a variable that hasn't been created yet. Skip making four variables and just assign the nbs to 0 outside of your main class, then give them the value you want inside it. They will then retain that value outside of the main class and be visible.
static int nbRabbits = 0;
static int nbFoxes = 0;
//in main class
nbFoxes = enterPopulation("foxes", 2, keyb); //at least 2 foxes
nbRabbits = enterPopulation("rabbits", 5, keyb); //at least 5 rabbits

Java Method Call Array

How do I pass an array from my main method to another method? I'm having an error with the parameters. Do I use the return value from main? And since the return value from main is an array, should the parameters for the call of main have brackets? Should there be a value between those brackets?
public class arraysAndMethods {
public void printArray(double[] arr) {
int x = arraysAndMethods.main(double[i] arr);//error with paremeters
for (int i = 0; i < studGrades.lenght; i++)
System.out.print(studGrades[i] + " ");
}// end of printArray method
public static double[] main(String args[]){// double array
java.util.Scanner input = new java.util.Scanner(System.in); // input scanner
System.out.println("What is the size of the class?");
int n = input.nextInt();
double[] arr = new double[n];// declare and initialize array to have n many elements
for (int i = 0; i < arr.length;i++) {// input grades for each students
System.out.println("What is the grade of student #" + (i+1));
arr[i] = input.nextDouble();
} // end of for loop
return arr;
}// end of main method
}// end of class
Just pass the name, not the type.
int x = arraysAndMethods.main(arr);
EDIT:
Besides that, your code shows a few other problems.
main(...) is the entry point to your application. It doesn't make sense to call main(...) from the other method. It should be the other way around.
main(...) HAS TO have the following signature: public static void main(String[] args). You cannot declare it to return an array of double.
This whole thing doesn't make much sense. If you're hoping to have this as the main method of a Java program, this won't work because the main method must have a void return type. Regardless, you have a syntax error here:
int x = arraysAndMethods.main(double[i] arr);//error with paremeters
Instead it should be
int x = arraysAndMethods.main(arr);//error with paremeters
as the variable has already been declared. I'm not sure what you were trying to do with double[i], but that syntax is more like a declaration, i.e.
double[] someArrayName = new double[5];
Your main method is where the program begins execution. In other words you should be calling printArray() from within main, not the other way around
I think I see where the confusion is. Perhaps this will help.
First I think you should understand something very important about Java.
Your main method is the FIRST method that is run.
So let's give a short walk through of how a Java program is created without an IDE.
First, you write your code in a text file and rename it to arraysAndMethods.java when you're done. Next we need to take your code and put it into a form that is usable by the computer it is first compiled down to bytecode with the following from the command line:javac arraysAndMethods.java
After it is compiled you can run the program with this command: java arraysAndMethods
Your program will run if there are no problems.
You say that you want to pass variables things into the main method? Here is how you do that from the command line: java arraysAndMethods 45.6 38.2 5.5 105.3
Looking at your main method, it takes the following arguments: (String args[])
So in your case, the 45.6 38.2 5.5 105.3 would be passed into your main method as an array of strings. With the first entry being 45.6, followed by 38.2, then 5.5 and finally 105.3.
It would look like this in the array: ["45.6"],["38.2"],["5.5"],["105.3"] but they are all Strings and not doubles.
All of this is to say that if you want to pass something in to your main method, you'll either need to do it through the command line, or look up how your individual IDE (i.e. Eclipse, Netbeans, etc.) handles that.
So to recap: The parameters in the main method are coming in from the console unless other specifications are made, and in your case it is returning an array of type double.
I know this is quite verbose, but bear with me, I'm almost done.
When a Java program is run(I'm simplifying a bit here), it comes into the main method and executes the first line it sees. When it's done with that one, it goes onto the next line, and so forth until it gets to the end of the main method. Then the program is done.
So everything MUST be done in the main method. Although you can call other Classes and methods from the main method.
Now that you have the explanation, here is what I would do to fix your code:
public class arraysAndMethods {//Changed from arraysAndMethods to ArraysAndMethods because classes are always capitalized
public static void printArray(double[] arr) {//Added static so this could be used within the same class as the main method.
//int x = arraysAndMethods.main(double[i] arr); No need for this line
for (int i = 0; i < arr.length; i++)// Changed "studGrades.lenght" to arr.length
System.out.print(arr[i] + " ");//Changed "studGrades" to arr
}// end of printArray method
public static void main(String args[]){// Changed the return type to "void". No need to return the double array.
java.util.Scanner input = new java.util.Scanner(System.in); // input scanner
System.out.println("What is the size of the class?");
int n = input.nextInt();
double[] arr = new double[n];// declare and initialize array to have n many elements
for (int i = 0; i < arr.length;i++) {// input grades for each students
System.out.println("What is the grade of student #" + (i+1));
arr[i] = input.nextDouble();
} // end of for loop
printArray(arr);
//return arr; No need for this line
}// end of main method
}// end of class
Please be sure to mark the best answer when you're ready and up-vote any answers or comments you feel helped. Not just for this question, where you are the original poster, but for other question threads as well.

Categories

Resources