New method, <identifier> expected error - java

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.

Related

Why we have to declare variable outside of if statement in Java [duplicate]

This question already has answers here:
What is 'scope' in Java?
(2 answers)
Closed 2 years ago.
In Java, if we run:
public class HelloWorld{
public static void main(String []args){
if (true) {
int test = 1;
} else {
int test = 2;
}
System.out.println(test);
}
}
It will throw:
HelloWorld.java:9: error: cannot find symbol
System.out.println(test);
^
symbol: variable test
location: class HelloWorld
1 error
However, in php, if we run:
<?php
//Enter your code here, enjoy!
if (true) {
$test = 1;
} else {
$test = 2;
}
echo $test;
It will print 1.
I suspect if that is because Java is strong typed language and php is weak typed language. Can someone give a more deep and lower level explanation?
In Java, the visibility scope of a variable is limited by {}
if (true) {
int test = 1;
} else {
int test = 2;
}
System.out.println(test);// Will fail to compile
It is also important to note the dead code as shown below:
int test;
if (true) {
test = 1;
} else {
test = 2;// Dead code
}
System.out.println(test);
Because of if (true) the else block will never be executed causing test = 2 to become the dead code.
This has nothing to do with difference between static and dynamic typing. The difference here between Java and PHP is variable scope.
In PHP $test = 1; will be part of the global scope as per docs.
In Java int test = 1; will be part of local scope, in your case limited to if block.
Java is "block scoped"; things introduced inside of one { } block go away at the end of that block.
PHP is "function scoped"; things introduced inside of a function last until the end of the function. If you're not in a function, the variable is a global, and lasts until the program completes.
In both languages, once something falls out of scope, it's garbage collected.

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.

Problems with calling a method using an array

I'm relevantly new to Java and just started my first semi serious assignment. I'm confident most of my code is working, the only problem is because I've been using classes I can't seem to call a method which uses an array into my main class. Every other method I want to call seems to work. I wonder if anyone has any explanation or easy solution to this?
Thanks in advance for taking time looking into, really appreciate it!
import java.util.Scanner;
public class GeographyQuizMain
{
public static void main(String[] args)
{
takeQuiz();
}
public static void takeQuiz(Question[][] questions)
{
int score = 0;
RandomNumber randomQuestion = new RandomNumber();
//user chooses catergory
int cat = pickCatergory();
//ask 10 questions
for(int i = 0; i < 10;)
{
Scanner answerChoice = new Scanner(System.in);
randomQuestion.dice();
int q = (randomQuestion.dice() - 1);
//checks to see if question as been asked before
if (!questions[cat][q].beenAsked)
{
questions[cat][q].beenAsked = true; //changes question status to beenAsked
System.out.println(questions[cat][q].promt);
String answer = answerChoice.nextLine();
System.out.println("\nYou picked: " + answer + "\nThe correct answer was: " + questions[cat][q].answer + "\n");
if(answer.equals(questions[cat][q].answer))
{
score++;
}
i++;
}
}
System.out.println("That is the end of the quiz!\n"
+ "You got " + score + "/10");
}
Your problem is with the call itself,
This line public static void takeQuiz(Question[][] questions) states that the method will accept a two dimensional array ([][]) of an object named Question.
On the other hand, your call - takeQuiz(); passes no array of such.
You should initialise an array of such to make this compile and pass it to the function. i.e.
Question[][] questionArray = GenerateQuestionArray(); //you should write this method
takeQuiz(questionArray);
Like you stated, it's clearly you're new to Java and I strongly suggest you to read the instructions and the information provided to you in class about that. I bet the details of Object initialisation, methods and arrays are covered there.
It seems that problem with your method call, in your method takeQuiz(); is taking 2 dimensional array for questions but at the calling time you are not providing that parameter so, compiler not able to found the method.
That's the problem.
try to use like this, this is simple an example for you. replace this with your actual values.
String[][] questions= new String[3][3];
takeQuiz(questions);
this will work.
You have called your method takeQuiz() without actually supplying its arguments Question[][] questions

How to use goto statement correctly

I am taking my high school AP Computer Science class.
I decided to throw a goto statement into a one of our labs just to play around, but I got this error.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token "goto", assert expected
restart cannot be resolved to a variable
at Chapter_3.Lab03_Chapter3.Factorial.main(Factorial.java:28)
I went to a goto question on Stackoverflow to find out how to do it properly, and I did exactly as was demonstrated in one of the answers. I really don't understand why the compiler wants an assert statement (at least that's what I assume it wants), nor do I have any idea how to use assert. It seems to want the restart part of goto restart; to be a variable, but restart is just a label that pulls the program back up to line 10 so that the user can enter a valid int. If it wants restart to be a variable, how do I do that?
import java.util.*;
public class Factorial
{
public static void main(String[] args)
{
int x = 1;
int factValue = 1;
Scanner userInput = new Scanner(System.in);
restart:
System.out.println("Please enter a nonzero, nonnegative value to be factorialized.");
int factInput = userInput.nextInt();
while(factInput<=0)
{
System.out.println("Enter a nonzero, nonnegative value to be factorialized.");
factInput = userInput.nextInt();
}
if(x<1)//This is another way of doing what the above while loop does, I just wanted to have some fun.
{
System.out.println("The number you entered is not valid. Please try again.");
goto restart;
}
while(x<=factInput)
{
factValue*=x;
x++;
}
System.out.println(factInput+"! = "+factValue);
userInput.close();
}
}
As already pointed out by all the answers goto - a reserved word in Java and is not used in the language.
restart: is called an identifier followed by a colon.
Here are a few things you need to take care of if you wish to achieve similar behavior -
outer: // Should be placed exactly before the loop
loopingConstructOne { // We can have statements before the outer but not inbetween the label and the loop
inner:
loopingConstructTwo {
continue; // This goes to the top of loopingConstructTwo and continue.
break; // This breaks out of loopingConstructTwo.
continue outer; // This goes to the outer label and reenters loopingConstructOne.
break outer; // This breaks out of the loopingConstructOne.
continue inner; // This will behave similar to continue.
break inner; // This will behave similar to break.
}
}
I'm not sure of whether should I say similar as I already have.
The Java keyword list specifies the goto keyword, but it is marked as "not used".
This was probably done in case it were to be added to a later version of Java.
If goto weren't on the list, and it were added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etcetera) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.
If you look up continue and break they accept a "Label". Experiment with that. Goto itself won't work.
public class BreakContinueWithLabel {
public static void main(String args[]) {
int[] numbers= new int[]{100,18,21,30};
//Outer loop checks if number is multiple of 2
OUTER: //outer label
for(int i = 0; i<numbers.length; i++){
if(i % 2 == 0){
System.out.println("Odd number: " + i +
", continue from OUTER label");
continue OUTER;
}
INNER:
for(int j = 0; j<numbers.length; j++){
System.out.println("Even number: " + i +
", break from INNER label");
break INNER;
}
}
}
}
Read more
Java does not support goto, it is reserved as a keyword in case they wanted to add it to a later version
goto doesn't do anything in Java.
Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.
There is not 'goto' in the Java world. The main reason was developers realized that complex codes which had goto would lead to making the code really pathetic and it would be almost impossible to enhance or maintain the code.
However this code could be modified a little and using the concept of continue and break we could make the code work.
import java.util.*;
public class Factorial
{
public static void main(String[] args)
{
int x = 1;
int factValue = 1;
Scanner userInput = new Scanner(System.in);
restart: while(true){
System.out.println("Please enter a nonzero, nonnegative value to be factorialized.");
int factInput = userInput.nextInt();
while(factInput<=0)
{
System.out.println("Enter a nonzero, nonnegative value to be factorialized.");
factInput = userInput.nextInt();
}
if(x<1)//This is another way of doing what the above while loop does, I just wanted to have some fun.
{
System.out.println("The number you entered is not valid. Please try again.");
continue restart;
}
while(x<=factInput)
{
factValue*=x;
x++;
}
System.out.println(factInput+"! = "+factValue);
userInput.close();
break restart;
}
}
}
goto is an unused reserved word in the language. So there is no goto. But, if you want absurdist theater you could coax one out of a language feature of labeling. But, rather than label a for loop which is sometimes useful you label a code block. You can, within that code block, call break on the label, spitting you to the end of the code block which is basically a goto, that only jumps forward in code.
System.out.println("1");
System.out.println("2");
System.out.println("3");
my_goto:
{
System.out.println("4");
System.out.println("5");
if (true) break my_goto;
System.out.println("6");
} //goto end location.
System.out.println("7");
System.out.println("8");
This will print 1, 2, 3, 4, 5, 7, 8. As the breaking the code block jumped to just after the code block. You can move the my_goto: { and if (true) break my_goto; and } //goto end location. statements. The important thing is just the break must be within the labeled code block.
This is even uglier than a real goto. Never actually do this.
But, it is sometimes useful to use labels and break and it is actually useful to know that if you label the code block and not the loop when you break you jump forward. So if you break the code block from within the loop, you not only abort the loop but you jump over the code between the end of the loop and the codeblock.

Changing a variable though a module in a loop (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

Categories

Resources