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 7 years ago.
Improve this question
import java.util.Scanner;
public class Recursion
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter n to start: ");
int n = in.nextInt();
System.out.println("Sum of numbers from 1 to " + n + ": " +new Recursion().sumUpTo(n));
}
}
/**
* Computes the sum of a range of numbers
*
* #param n an integer
* #return the sum of n range
*/
public int sumUpTo(int num){
if (num == 0)
{
return 0;
}
else{
return (num + sumUpTo(num-1))
}
}
This should be a very simple method, I know, but I can't seem to get it to compile. I keep getting "class, interface, or enum expected" on the public int sumUpTo(int num) line. This is the method that performs the actual computations. Any help would be greatly appreciated.
A couple things :
Your method is declared outside of the class
Missing semicolon on the line with your recursive call
You should be new to Object Oriented Programming. In Java a function(method) must be inside(belong) to a class. You either put public int sumUpTo(int num) inside public class Recursion or you can create another class and put it in there. But remember there should be only one public class inside a file.
In Java, everything must be inside of a class. Simply move your method to within the curly braces of the class and it should work.
The error class, interface, or enum expected is quite self-explained! It encountered code that wasn't inside of a class, inteface, or enum, and it wasn't expecting that, because that shouldn't happen!
In case you need to see what I mean:
public class Recursion {
public static void main (String[] args) {
// your code here...
}
// Where your method should have gone.
}
Also, welcome to Stack Overflow. Please remember to accept an answer if it answers your question.
Move your sumUpTo method inside the class.
import java.util.Scanner;
public class Recursion
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter n to start: ");
int n = in.nextInt();
System.out.println("Sum of numbers from 1 to " + n + ": " +new Recursion().sumUpTo(n));
}
/**
* Computes the sum of a range of numbers
*
* #param n an integer
* #return the sum of n range
*/
public int sumUpTo(int num){
if (num == 0)
{
return 0;
}
else{
return (num + sumUpTo(num-1));
}
}
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
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.
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.
Improve this question
Write a Java program with a recursive method that accepts a value i as input and computes the sum:
m(i) = 1/3 + 2/5 + 3/7 + 4/9 + 5/11 + ... + i/(2i + 1)
So far I have:
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter an i: ");
int i = sc.nextInt();
if (i == 0) {
System.out.println(0);
}
else {
System.out.println(i / (2 * i + 1) + (main(i-1)));
}
}
}
The code isn't compiling. Please help!!
Ok I think I finally understand what you're trying to do! The problem is you're actually trying to build a string! The method is doing what it should, your return just isn't really doing what it should.
import java.util.Scanner;
public class Recursion
{
private static String result = null;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an i: ");
int i = sc.nextInt();
System.out.println(recursion(i));
}
public static String recursion(int i)
{
if(i != 0)
{
if(result == null)
{
result = (i + "/" + (2 * i + 1));
recursion(i - 1);
}
else
{
result = result.concat(" + ").concat(i + "/" + (2 * i + 1));
recursion(i - 1);
}
}
return result;
}
}
Please let me know if this does what you want it to!
You shouldn't use recursion on the main function. Just create a second function that isn't the main and it should work:
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter an i: ");
int i = sc.nextInt();
System.out.println(recursion(i));
}
public int recursion(int i){
if (i == 0) {
return 0;
}
else {
return (i / (2 * i + 1) + (recursion(i-1)));
}
}
}
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 5 years ago.
Improve this question
My code does not currently compile, I know that it is due to a lack of a return for my constructor- but if I could please get some help (as I have a version that I have already tried to fix), it would greatly be appreciated.
I have 2 files, one that has a constructor, and one that accesses that constructor. I should also note, that all of the help I found online said that I have to use an if else statement, but that leads to more errors.
My code for the main file:
import java.util.Scanner;//importing scanner
public class QuestionTwo {
public static void main(String[] args) {
int numberofDays;//these two lines define variables
int sharePoints;
Scanner keyboard = new Scanner(System.in);//activating scanner
System.out.print("Number of days in the period: ");//asking question
numberofDays = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
System.out.print("Share points on the first day: ");//asking another question
sharePoints = keyboard.nextInt();//obtaining input by defining a variable as a keyboard input
while (numberofDays < 10 || numberofDays > 20)
{
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
}
SharePattern share = new SharePattern(numberofDays, sharePoints);
SharePattern.outPutTablePrinter(numberofDays, sharePoints);
//above two lines print day and share points, as well as the first line
of text (as it does not change)
}
}
Here is the code for the constructor (the one with the return error):
public class SharePattern {
private static int days;
private static int share;
public SharePattern(int numberofDays, int sharePoints)//constructor
{
numberofDays=days;
sharePoints=share;
}
public static int outPutTablePrinter(int numberofDays,int sharePoints){
for (int i = 2; i <= days; i++) {
if (days % 2 == 0)
if (i <= days / 2) {
share = share + 50;
} else {
share = share - 25;
} else {
if (i <= days / 2 + 1) {
share = share + 50;
} else {
share = share - 25;
}
}
}
System.out.println("The share points on the final day would be: "+share);
}
}
}
Any help would be appreciated, as I've been working on this problem all day and finally got finished when I came upon this problem.
First, you have an else {} else, which isn't valid
Not really clear which you're trying to accomplish..
Option 1
Remove the constructor and the static fields. You never use share variable.
Make your outPutTablePrinter method use the parameters you passed to it. And that method doesn't return anything. It's printing a value. Make it public static void
Option 2
If you want to keep the constructor, you need to flip the order of those equal statements and remove the static keyword.
Still make the method void
public class SharePattern {
private int days;
private int share;
public SharePattern(int numberofDays, int sharePoints){
days = numberofDays;
share = sharePoints;
}
public void outPutTablePrinter() {
And in the main method, you must use share.outPutTablePrinter()
It was actually extremely simple (sorry for my incompetence once again):
I should have put
return (sharePoints);
where i previously had nothing
This is what i suggest you if i understand correctly your code
SharePattern.class
private static int days;
private static int share;
public SharePattern(int numberofDays, int sharePoints)//constructor
{
days=numberofDays;
share=sharePoints;
}
public static void outPutTablePrinter(){
for (int i = 2; i <= days; i++) {
if (days % 2 == 0)
if (i <= days / 2) {
share = share + 50;
} else {
share = share - 25;
}
else
if (i <= days / 2 + 1) {
share = share + 50;
} else {
share = share - 25;
}
}
System.out.println("The share points on the final day would be: "+share);
}
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 5 years ago.
Improve this question
Given this requirement
Create a code which creates random number and ask user to make 2 guess and then print out the actual number and also state which one of your guess was closest
I am stuck at the last part. Please help.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package selectionexercises;
/**
*
*
* #author jhonpaul
*/
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("I have picked a number between 1 to 100 try to guess it.");
int randomNumber = (int) (Math.random() * 100 + 1);
System.out.println("Enter Your First Guess.");
int guess1;
guess1 = sc.nextInt();
System.out.println("Enter Your Second Guess.");
int guess2;
guess2 = sc.nextInt();
System.out.println("The number was " + randomNumber);
int range;
range = randomNumber;
}
}
Use Math.min(Math.abs(randomNumber-guess1), Math.abs(randomNumber-guess2))
Do something like this:
//Calculate difference and use absolute value (turn negative values into positive if necessary)
int difference1 = Math.abs(randomNumber - guess1)
int difference2 = Math.abs(randomBumber - guess2)
//Compare result
if(difference1<difference2) {
System.out.println("Guess1 was closer");
} else if (difference1>difference2) {
System.out.println("Guess2 was closer");
} else {
System.out.println("Both were equally close!");
}
There are shorter ways than this but scince you are a starter I think this is an understandable and easy to use way.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to finish my rational class for java and everywhere I have looked to make it finished doesn't have it near the same. I know I could use others programs that where made but the ones I have seen don't have it for where you put the input in when you run the program. This is the code I have so far
import java.util.Scanner;
public class Lab09ast
{
private static int num, den; // numerator and denominator of the rational number
public static void main (String[] args)
{
enterData();
Rational r = new Rational(num,den);
r.displayData();
}
public static void enterData()
{
Scanner input = new Scanner(System.in);
System.out.print("\nEnter the numerator ----> ");
num = input.nextInt();
System.out.print("\nEnter the denominator --> ");
den = input.nextInt();
}
}
class Rational
{
public void displayData()
{
System.out.println();
System.out.println(getNum() + "/" + getDen() + " equals " + getDecimal());
System.out.println();
}
private void getGCF(int n1,int n2)
{
int rem = 0;
do
{
rem = n1 % n2;
if (rem == 0)
gcf = n2;
else
{
n1 = n2;
n2 = rem;
}
}
while (rem != 0);
}
}
Member variables num and den (numerator and denominator) are in class Lab09ast. These should be in class Rational. Do you understand the concepts of classes and objects?
It's logical that a Rational object, which you make from the class Rational, has member variables for the numerator and denominator.
Also, those member variables must not be static. See Understanding Class Members to learn what static means and why it is not appropriate for these member variables.
The methods getNum() and getDen() should return the values of the num and den member variables, and should also be in class Rational.
Class Rational should also have a constructor that takes two arguments, for the numerator and denominator. You're already calling that constructor in the main method of class Lab09ast, but it's not in your class Rational yet.
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 8 years ago.
Improve this question
I'm creating a class for cars that has their make and model, and then every time the accelerator method is accessed it increases the speed by 5. I feel like I'm missing some key part about creating classes of your own, but I'm not sure what! Any help would be great. Here's my code:
import java.util.Scanner;
public class Car
{
public static void main (String[] args);
{
//Scanner object
Scanner kb = new Scanner(System.in);
//variables and declarations
int yearModel;
String make;
int speed = 0;
System.out.println("Enter model year: ");
yearModel= Integer.parseInt(kb.nextLine());
System.out.println("Enter make: ");
make = kb.nextLine();
//Car object
Car car = new Car(yearModel, make, speed);
System.out.println("Car model year: " + car.getModel() + "/nCar make: " + car.getMake());
//get speed 5 times
for (int i = 0; i > 5; i++);
{
System.out.println("Car's current speed: " + Accelerate(car.getSpeed()));
}
/**
Accelerator method
adds five to the speed every time it is accessed
#param speed car is currently going
#return new current speed, increased by five
*/
public int Accelerate(int speed)
{
int newSpeed = speed+5;
return newSpeed;
}
}
/**
Constructor
#param yearModel holds the cards model year
#param make holds the make of the car
*/
public Car(int yearModel, String make, int speed)
{
yearModel = yearModel;
make = make;
speed = speed;
}
//getSpeed method, returns current speed of car
public int getSpeed();
{
return speed;
}
//getYear method, returns model year #return year model
public int getModel()
{
return yearModel;
}
//getModel method, #return make
public String getMake()
{
return make;
}
}
and here are the errors I'm getting:
Car.java:37: error: illegal start of expression
public int Accelerate(int speed)
^
Car.java:37: error: ';' expected
public int Accelerate(int speed)
^
Car.java:37: error: ';' expected
public int Accelerate(int speed)
Any help would be great, I'm pretty new at this
You placed a semi-colon after a methods prototype:
public static void main (String[] args);
Same problem here:
public int getSpeed();
Also missing an ending brace after your static main method:
for (int i = 0; i > 5; i++) ;
{
System.out.println("Car's current speed: " + Accelerate(car.getSpeed()));
}
}
Also the semi-colon after the for statement shouldn't be there :D You must really like semi-colons.