Using functions in Java Programming [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have doubt in using functions in java. I have wrote code for sum of natural numbers using a recursive function but I don't understand the error I am getting. I know it's a silly question though I'm a beginner and I need a brief explanation.
Here is the code
import java.util.Scanner;
public class natural {
public static int main(String args[]){
int a, s = 0,y;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number:");
int x = in.nextInt();
public static int SN(y)
{
if(x==1)
{
return 1;
}
else{
int N = SN(x-1) + x;
return N;
System.out.println("THE SUM IS :"+x);
}
}

Several problems:
You cannot declare a method within a method. Your SN method must be declared outside of the main method.
The parameter y in your SN method must have a type. Based on usage, it is probably supposed to be an int, so the method signature should look like SN(int y).
Despite the method parameter being called y, you appear to be using x everywhere. You should change x to y in the SN method, since that is the label of the data being passed to the method.
As others have pointed out, statements after the return line are unreachable, and as Matt Coubrough said, your IDE is likely warning you about this. Place it before the return line.

Well, one problem here is that you have an unreachable statement. Your System.out.println("THE SUM IS...") is never reached.

Related

Java Beginner - Java Code Errors Advice Needed [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
First off, I am a BEGINNER in Java. I am finally taking my core classes in college. I am in Computer Science 1 and I'm correcting a code I got from a book as a practice so I can gain a better understanding on how to fix codes. It's a simple code, however, I keep running into 3 errors every single time. I need advice on how to correct them! I am new to all of this so it can be frustrating at times. Thanks!
public class Mistakes
{
public static void main(String[] args);
{
int y;
int x = 12;
y + x = y;
System.out.println("This is what y + x equals: "+y);
System.out.print("This is what t equals: "+t);
}
}
I keep running into 3 errors:
java:3: error: missing method body, or declare abstract
public void main(String[] args);
^
java:7: error: unexpected type
y + x = y;
^
required: variable
found: value
java:9: error: cannot find symbol
System.out.print("This is what t equals: "+t);
^
symbol: variable t
location: class Mistakes
Do I change t into x?
Do I change public class to public abstract?
Any advice will be greatly appreciated!
First, your main() method has a ; after it's declaration. This is allowed only if the method you are declaring is abstract and, thus, has no "body". In this case, you should remove the semicolon. Look below:
public static void main(String[] args) {
//Your code here
}
Second, your assignment operation is wrong. In Java (and in programming in general) you must first specify a variable and then the value it is going to receive (literally or, in your case, through an expression). You should do it as shown below:
y = x + y; //the value of y will be equal to x+y
In this case you could even use a shortcut, if you want to:
y += x; //this expression will have the same effect as the shown above
Finally, you are getting the last error because the variable t wasn't declared, so the method System.out.print() is trying to print a variable that doesn't exist. In this case, you should either remove the symbol t or declare a variable with this name, like I do below:
int t = 3;
System.out.print("This is what t is equals to " + t); //t will be 3

Program That Teaches Someone Multiplication with Random Numbers

I am writing a program (game) that teaches someone multiplication. In this program, random pair of numbers are to be generated and inserted into the question: "What is x * y = z?" If the person answers correctly, then the system will print out "Very Good!" If the person does not answer the question correctly, then the system will print out, "No. Please try again." (Which, in return, the program will continue to ask the question until the person answers the question correctly.) As the person answers the question correctly, a new method will generate another question for the person to answer.
My code is breaking at the variable "answer" and the if statement "(guess != answer)."
Here is my code:
public class Exercise_535 {
public class Multiply{
SecureRandom randomNumbers = new SecureRandom();
int answer;
}
public void Quiz() {
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter your answer: ");
guess = input.nextInt();
while(guess != -1)
{
checkResponse(guess);
System.out.println("Enter your answer: ");
guess = input.nextInt();
}
}
public void createQuestion(){
SecureRandom randomNumbers = new SecureRandom();
int digit1 = randomNumbers.nextInt();
int digit2 = randomNumbers.nextInt();
answer = digit1 * digit2;
System.out.printf("How much is %d times %d\n", digit1, digit2);
}
public void checkResponse(){
if (guess != answer)
System.out.println("No. Please try again.");
else{
System.out.print("Very Good!");
createQuestion();
}
}
}
Is there anyone that is able to help, or at least point me in the correct direction?
Thanks.
It is important to understand the scope of variables. In java if you create a variable (where you say int guess or int answer) that variable only lives within whatever curly braces you put it in -> { }. So if you need that variable in another method, you need to pass it that variable in the parentheses. checkResponse() doesn't know what guess or answer are, because they aren't declared in that scope, and you don't pass them in at the start of the function (you could have checkResponse(int guess, int answer) and then pass those in when you call it, for example).
You have an inner class Multiply, is there a reason you created a class within a class? There are reasons to do that, but it doesn't seem like you have any reason to do that here.
Also I don't see a main function, which is the entry point to a Java program, and all other functions need to be called from there (so Main() could then call Quiz() in your case, which would then call your other two functions). Computers read programs one line at a time, and when you call a function/method (like Quiz()) it jumps to that part, and then returns when that function calls "return".
I know this is a lot of information, but it doesn't seem like you understand how Java programs flow. What are you using to study Java? If you are reading a book or doing a course, I recommend reviewing some of the earlier lessons, to understand the flow of the program better. It is difficult for people to answer your question because the way your code is set up doesn't have a logical flow (which is why it isn't working). Hope this helps a little.

Logic errors within java segment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
The following Java code segment is supposed to print, as a double, the mean average of a sequence of non-negative integers entered by the user. A negative input signals the end of the sequence (it is not itself part of the sequence). However, the code is not working. I am supposed to find 4 logic errors within this segment. Please help me find the 4 logic errors?? I know one is its integer division.
public class practice
{
public static void main (String[]args)
{
int sum = 0;
int numVals = 0;
Scanner scan = new Scanner(System.in);
System.out.println(("enter next integer (-ve to stop): "));
int i = scan.nextInt();
while (i > 0)
{
sum = sum + i;
numVals = numVals + 1;
}
System.out.println("average = " + sum / numVals);
}
}
I won't give you full solution, however, it'll be helpful if you pay attention to:
int division as you said,
does your loop terminate? Is someone changing i? Hint: No, and
how do you ask for input? Do you see any loops there? Why it's asking you for only one input?
Not an error, but pay attention to Java Naming Conventions, class name should begin with upper case
Since the homework is for logic errors, I could point out other errors.
the class name should start with upper case letter.
the println doesn't need two nested parenthesis.
the sum should be a long rather than an int to avoid overflows.

Java, Methods? Or constructors ? I am not sure what to call it [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am not sure if you see what I am trying to do here but basically I have a few questions and problems
1)The part that is called public MethodPractice() ... what is this called? is this considered a constructor a method or what?
2)The part named MethodPracticeDiff() . . . is this allowed and if so how do I insert it into the main method for execution...
Do you guys see what I am trying to do here? Basically I want to split the program up into different pieces for example let say I wanted my own space for a calculation method to add to numbers up
and another method to define the numbers like give them a value
and a last method with a for loop making the numbers printout 10times
Any who before I make this more confusing than what it is, my question is how do I make this program execute
public class MethodPractice {
public static void main (String[]args){
MethodPractice add = new MethodPractice();
//MethodPracticeDiff add2 = new MethodPracticeDiff();
}
public MethodPractice() {
int x = 0;
int y = 99 ;
int total = x + y;
System.out.println(total);
}
public void MethodPracticeDiff(){
int z = 10;
int k = 25;
int total = z + k;
System.out.println(total);
}
}
(1) If it's in class MethodPractice, it's a constructor.
(2) Yes, this is allowed. But it's a method not a constructor. Standard practice is to begin it with a lowercase letter.
As follows in the main() method:
MethodPractice add = new MethodPractice();
add.methodPracticeDiff();
MethodPractice() is a constructor -- it has no return value and matches the name of the class.
MethodPracticeDiff() is a method -- it has a return value and does not match the name of a class.
You call methods once you have an instance of the class. e.g.
MethodPractice add = new MethodPractice();
add.MethodPracticeDiff();

Comparing elements of two arrays in a for loop (java)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
It seems to be a very common question relating with arrays and comparing in java, however I couldn't find the right answer in all of these for my case.
In this application I am trying to make a program which 'encrypts' text given by the user. For example: user gives characters 'a b c' and the program returns it as '# # $'. But as you may notice I am having some issues in the code
"pozita[i] = j;".
Why won't this code work? It doesn't give me an error? Or is there anyway of doing it as "new pozita[i]" or anything like that?
Well, I'd be glad if someone could help me through. I am stuck for a while. Thanks in advance! :)
import java.util.*;
import javax.swing.*;
import java.awt.*;
public class TestPerProgram extends JFrame
{
char[] alfabeti = {'a','b','c','r','n','t'};
char[] kodimi = {'#','#','%','*','^','$'};
int[] pozita;
//Scanner merr = new Scanner(System.in);
String fn = JOptionPane.showInputDialog("Jepe tekstin:");
char[] input = fn.toCharArray();
void numro()
{
for (int i=0; i<=input.length; i++)
{
for(int j=0; j<=input.length; j++)
{
if(alfabeti[j] == input[i])
{
pozita[i] = j;
System.out.println(pozita[i]);
}
}
}
/*
for (int k=0; k<=input.length; k++)
{
System.out.println(pozita[k]);
}
*/
}
public static void main(String[] args)
{
TestPerProgram pjesa = new TestPerProgram();
pjesa.numro();
}
}
I'm not 100% clear on how your algorithm is supposed to work, but it seems you may want to replace the line
pozita[i] = j;
with
pozita[i] = kodimi[j];
Right now, you are only writing the matching index to pozita, not a replacement character.
If my assumption is correct, you would also change
int[] pozita;
to
char[] pozita;
and initialize it to an array of length input.Length.
You never instantiated the array pozita. After you instantiate pozita, you can then start overriding the values in pozita. You are assigning j to posita[i] , posita is null.
Do something like:
int posita[] = new int[20]
and if you don't want to set size then just use an arraylist.
You have not requested memory to be allocated for your variable pozita or otherwise instantiated it. The way you are currently using it, you would write pozita[] = new int[input.length]; at some point after retrieving your input from the user.

Categories