Method and constructor implementation [closed] - java

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);
}

Related

What do I need to fix to get the code to compile? [closed]

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)));
}
}
}

What is wrong with this recursion method? [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 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));
}
}
}

Creating classes: Why are these ''illegal start of expression'' and ':' expected" errors happening? [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 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.

Answer returning 0

Total beginner in Java. My result keeps turning up as 0 where I want it to turn up as membercount * members (ie if there are 100 members and the weather = 1, the total should be 25). I can't seem to figure out where I'm going wrong. I figure I'm not properly having my program store the information entered by the user so the doubles keep reading as 0. Here is my code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package playgolf;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
* #author Alex
*/
public class PlayGolf {
public static void main(String[] args) {
golf stats = new golf();
stats.getData();
golf total = new golf();
total.display_data();
}
}
class golf {
private double members;
private double weather;
private double temp;
private double membercount;
public double total;
public void getData() {
Scanner input = new Scanner(System.in);
System.out.print("How many members are there?: ");
members = input.nextInt();
System.out.print("What is the weather like? (Enter 1 for sunny, 2 for overcast, 3 for rain): ");
weather = input.nextInt();
System.out.print("What is the temperature? (in Farenheight): ");
temp = input.nextInt();
if (weather == 1) {
membercount = .25;
if (weather == 2) {
membercount = .12;
if (weather == 3) {
membercount = .03;
}
}
}
if (temp < 32) {
membercount = 0;
System.out.println("No one will play today, it's too darn cold!");
}
total = (membercount * members);
}
public void display_data() {
System.out.println(" ");
System.out.println("This many members will play today: ");
System.out.println(total);
}
}
You create new object again, it should be:
public static void main(String[] args) {
golf stats = new golf();
stats.getData();
stats.display_data();
}
Bug 1
The code blocks related to your weather logic are messed up; the closing braces are in the wrong place.
Properly indented, your code looks like this:
if (weather == 1) {
membercount = .25;
if (weather == 2) {
membercount = .12;
if (weather == 3) {
membercount = .03;
}
}
}
Now you can probably already see the bug. If weather is 2, the weather == 2 condition will never be reached (weather cannot be 1 and 2 at the same time).
Corrected version:
if (weather == 1) {
membercount = .25;
}
else if (weather == 2) {
membercount = .12;
}
else if (weather == 3) {
membercount = .03;
}
Bug 2
Another bug is in the main method. You should call display_data() on the same object as getData(). This would work:
golf stats = new golf();
stats.getData();
stats.display_data();
Other problems & style issues
display_data is not idiomatic Java method name. Should be displayData.
Likewise, Java class names should start with uppercase letter. Golf, not golf. See e.g. this guide on Java naming conventions.
It's suspicious to use double to represent one of three possible values (weather). Use int, or better yet, an enum. Also for members it is a pretty odd choice of type.
Since your if conditions are nested, if weather != 1, the checks for weather == 2 and weather == 3 are never reached.
As a consequence, membercount is never set and takes the value of zero, yielding your zero result for total.
You should just have something like the following:
switch (weather) {
case 1:
membercount = .25;
break;
case 2:
membercount = .12;
break;
case 3:
membercount = .03;
break;
default:
// Do nothing or, better yet, produce an error
}
if (temp < 32) {
// ...
You could simply use a series of ifs, or an if-else chain. I'm using a switch because it's the safest choice in this case. This assumes that you change weather to be an int, which is actually preferable given your use of the variable. You should also esplicitly initialize the value of weather during declaration (or in the constructor, as you see fit):
private int weather = 0;
As pointed out by the other answers, you have a secondary bug in your listing: you should create only one object and have both calls on that, as follows:
golf stats = new golf();
stats.getData();
stats.display_data();
You are calling getData() on one instance (of golf) and calling display_data() on another one. The stats collects data, but the total does not. Try to call display_data() on stats instance / or call getData() on total instance / or use shared members (statics I mean).
golf stats = new golf();
stats.getData();
stats.display_data();
or
golf total = new golf();
total.getData();
total.display_data();

Else without if error: I dont understand why java isn't recognizing my if statment [duplicate]

This question already has answers here:
Error: 'else' without 'if' [closed]
(3 answers)
Closed 7 years ago.
At line 53 it is giving me an error of else without if. I clearly have an if statement, but i don't know what i'm doing wrong to make java not recognize it. I've tried moving around the braces and nothing is working.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Quiz6
{
public static void displayInfo()
{
System.out.println(
"\n\tAuthor: Allen Watson \n" +
"\tClass: \tCSCI 1250-001 \n" +
"\tDate: \t10/09/2013 \n" +
"\tLab: \tQuiz6 \n");
}
public static double calculatePay(int hourWorked, double hourlyRate)
{
double dPay;
dPay = (hourWorked * hourlyRate);
return dPay;
}
public static void main(String[] args)
{
Scanner Keyboard = new Scanner(System.in);
DecimalFormat dfMoney = new DecimalFormat("$#,##0.00");
String strName;
int iCount;
int iDaysWorked;
int iTotalHoursWorked;
int iSingleDayHours;
double dHourlyRate;
final byte WEEK = 7;
displayInfo();
System.out.print("\tWhat is your name: ");
strName = Keyboard.nextLine();
System.out.print("\n\tHow many days did you work this week: ");
iDaysWorked = Keyboard.nextByte();
System.out.print("\n\tHow much do you make an hour: ");
dHourlyRate = Keyboard.nextDouble();
if(dDaysWorked <= WEEK);
{
for(iCount = 1; iCount <= iDaysWorked ; iCount++)
{
System.out.print("\tHow many hours did you work on the day"+iCount+":");
iSingleDayHours = Keyboard.nextInt();
iSingleDayHours += iTotalHoursWorked;
}
}
else
{
bDaysWorked = 0;
System.out.print("A week can only have seven days");
}
calculatePay(iTotalHoursWorked,dHourlyRate);
System.out.print("Hello "+strName+", you worked a total of "+iTotalHoursWorked+" hours over "+iDaysWorked+" days.");
System.out.print("\nWith am hourly rate of "+dfMoney(dHourlyRate)+" you made "+dfMoney(dPay)+".");
}
}
Here's the problem:
if(dDaysWorked <= WEEK); // remove the ;
That trailing ; is making Java believe that the if statement is finished, and the {} block after it is outside the if condition, consequently the else part has no matching if preceding it.
This is a rather frequent bug, and a hard one to spot. If it weren't for the else block, the code would have compiled correctly, but it would have been wrong. Bottom line: never, ever put a ; in the opening line of an if, for or while statement.
if(dDaysWorked <= WEEK); - remove last ;

Categories

Resources