gpt4 book ai didi

java - 倒数和打印循环时遇到问题

转载 作者:行者123 更新时间:2023-11-30 08:38:17 24 4
gpt4 key购买 nike

所以我需要我的代码在 3 个用户输入时递增打印出来,我有第二个 java 文件使用点符号来执行方法。所以它应该像这样运行。

选择 > 起始值 - 选择增量值 - 选择 > 结束值所有这些都是用户输入,如果起始值 > 然后结束然后从起始值开始计算用户输入增量,我需要拥有它。但如果结束

import java.util.Scanner;

public class logic {

public static void main(String [] args) {

//new scanner
Scanner input = new Scanner(System.in);

//Data
char ch = 0;
int start = 0;
int end = 0;
int inc = 0;
String printStr = "";
final int SENTINEL = -1;
String menu ="Looping (Demo)" +
"\nStart Value\t [S]" +
"\nIncrement value [I]" +
"\nEnd Value\t [E]" +
"\nFor Looping\t [F]" +
"\nQuit\t\t [Q]" +
"\nEnter Option > ";

while(ch != SENTINEL) {

switch(ch) {
case 'S':
case 's':

start = UtilsDM.readInt("Enter loop start value: ", false);
break;

case 'I':
case 'i':
inc = UtilsDM.readInt("Enter loop increment value: ", false);
break;

case 'E':
case 'e':
end = UtilsDM.readInt("Enter loops end value: ", false);
break;

case 'F':
case 'f':
if(start <= end){
for (int i=start; i<=end; i+=inc) {
System.out.print(i + " ");
}//end loop +
}//end if
else if(start >= end){
for (int i=end; i<=start; i-=inc) {
System.out.print(i + " ");
}//end loop -
}//end else if

System.out.println("\n");
break;

case 'Q':
case 'q':
System.out.println("Terminating upon user command.");
System.exit(0);
break;

default:
System.out.println("Unrecognized character");
break;
}//end switch

ch = UtilsDM.readChar(menu, false);
}//end loop







//computations, algorithms

//outputs, formatting, display
} //end main

}//end class

最佳答案

将大小写“F”更改为如下,我已经评论了更改:-

 case 'F':
case 'f':
if(start < end || (start < 0 && end < 0 && end > start)) // start < end or start = -3 and end = -7
{
for (int i=start; i<=end; i+=inc)
{
System.out.print(i + " ");
}
}
else if(start > end || (start < 0 && end < 0 && start > end)) // if start = - 7 and end = -3
{
for (int i=end; i>=start; i-=inc) // should be greater than
{
System.out.print(i + " ");
}
}
else if(start == end)
{
System.out.println(end);
}

关于java - 倒数和打印循环时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36672299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com