【发布时间】:2018-04-21 22:42:29
【问题描述】:
这是我当前的代码:
import java.util.Scanner;//importing scanner
public class QuestionOne {
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)//while loop makes sure the conditions stay true
{
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();
//above three lines ask for number of days until a value that fits within specification is obtained
}
System.out.println("Day " + " Share Points");
System.out.println(1 + " " + sharePoints);
//above two lines print day and share points, as well as the first line of text (as it does not change)
for (int i = 2; i <= numberofDays; i++) {
if (numberofDays % 2 == 0)
if (i <= numberofDays / 2) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
} else {
if (i <= numberofDays / 2 + 1) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
// above nested if else statements essentially calculate and concatenate the variables to obtain an answer that is then printed and repeated until the number of days is reached (starting from day two)
}
}
}
}
}
此代码可以按我的意愿编译和工作,但是,我不再希望它采用这种格式。相反,我希望它包含一个名为 DisplayStock 的方法;我想要这个方法的输入参数是 期间的天数和第一天的份额点数。该方法用于在指定期限内隔日增加50点,减少25点。那时的方法 显示一个表格,显示日期和这些日期的共享点。此方法不返回任何内容。
main方法会先让用户输入指定期间的天数和第一天的share点数(输入验证后,程序调用DisplayStock方法输出表格.
如果周期为 ll 天且 SharePoint 为 550,则当前的示例输出如下所示:
Day Share Points
1 550
2 600
3 575
4 625
5 600
6 650
7 625
8 675
9 650
10 700
11 675
所以基本上,我打算将代码从 if-else 语句转换为方法,以缓解可读性和功能问题。任何帮助,将不胜感激!我将继续努力,但我认为我无法达到我的预期。
【问题讨论】:
标签: java if-statement methods