我的代码目前没有编译,我知道这是由于我的构造函数缺少返回 - 但如果我能得到一些帮助(因为我有一个我已经尝试修复的版本),它非常感谢。
我有2个文件,一个有构造函数,另一个访问该构造函数。我还应该注意,我在网上发现的所有帮助都说我必须使用if else语句,但这会导致更多错误。
我的主文件代码:
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)
}
}
以下是构造函数的代码(具有返回错误的代码):
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);
}
}
}
任何帮助都会受到赞赏,因为我整天都在研究这个问题,最后在我遇到这个问题时就完成了。
答案 0 :(得分:3)
首先,您有else {} else
,这是无效的
不太清楚你想要完成哪个......
删除构造函数和静态字段。你永远不会使用share
变量。
使outPutTablePrinter
方法使用您传递给它的参数。而且这种方法不会返回任何内容。它正在打印一个值。设为public static void
如果要保留构造函数,则需要翻转这些相等语句的顺序并删除static
关键字。
仍然使方法无效
public class SharePattern {
private int days;
private int share;
public SharePattern(int numberofDays, int sharePoints){
days = numberofDays;
share = sharePoints;
}
public void outPutTablePrinter() {
在主要方法中,您必须使用share.outPutTablePrinter()
答案 1 :(得分:0)
实际上非常简单(对不起我的无能):
我应该放
return (sharePoints);
我之前什么都没有
答案 2 :(得分:0)
如果我理解你的代码
,这就是我的建议<强> 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);
}