有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java处理周数并查找未来天数

考虑到两个输入,我试图找到计算未来工作日的方法:

  1. 当前工作日(范围为0-6,其中0为周日)
  2. 从当前工作日开始执行多少计数(任意数字)
  3. 这里,如果用户以前从当前工作日开始=3,并且 计数=7
  4. 然后我预计它会回到3,类似的14或21
  5. 如何对此进行推广,使计数在此固定范围内 0-6而不拔出

我已经做了一些code,发布在下面

public class ThoseDays {

    public static void main(String[] args) {

        Scanner obj = new Scanner(System.in);
        System.out.print("Enter number between 0-6 : ");
        int startFromHere = obj.nextInt();

        System.out.print("Enter number to count position from " + startFromHere + " : ");
        int rotateFromHere = obj.nextInt(); 


        System.out.print( startFromHere +  rotateFromHere);

        obj.close();
    }
}

实际结果:

> Enter the number between 0-6: 3
> Enter the number to count position from 3: 7
> 10

预期结果:

> Enter the number between 0-6: 3
> Enter the number to count position from 3: 7
> 3

共 (2) 个答案

  1. # 1 楼答案

    嗨,我建议你在他们到达7天后用modulo来轮换Another tutorial here

    public class ThoseDays {
    
      public static void main(String[] args) {
    
      //Scanner implements AutoCloseable
      //https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
        try (Scanner obj = new Scanner(System.in)) { 
          System.out.print("Enter number between 0-6 : ");
          int startFromHere = obj.nextInt();
    
          System.out.print("Enter number to count position from " + startFromHere + " : ");
          int rotateFromHere = obj.nextInt();
          int absoluteNumber = startFromHere + rotateFromHere;
          System.out.println(absoluteNumber);
          int rotatedNumber = absoluteNumber % 7;
          System.out.println(rotatedNumber);
        }
      }
    }
    
  2. # 2 楼答案

    代码:

    import java.util.*;
    public class ThoseDays {
    
        public static void main(String[] args) {
    
            Scanner obj = new Scanner(System.in);
        System.out.println("note : 0:sun 1-6:mon-saturday");
            System.out.println("Enter the number between 0-6: ");// 0:sun 1-6:mon-saturday
    
            int startFromHere = obj.nextInt();
    
            System.out.println("Enter the number to count position from " + startFromHere+ ": ");
            int rotateFromHere =obj.nextInt();
            if(rotateFromHere%7==0)
            {
                System.out.println(startFromHere);
            }
            if(rotateFromHere%7!=0)
            {
           int dayOfWeek=(startFromHere+(rotateFromHere%7));
           if(dayOfWeek>=7)
           {
               System.out.println((dayOfWeek%7));
           }
           else
           {
               System.out.print(dayOfWeek);
           }
            }
    
    
            obj.close();
        }
    }
    

    通过改变条件和使用模来尝试这段代码,我会得到所有正确的结果

    输出:
    从这里开始=3
    从这里旋转=7或14或21或7的倍数
    提供与开始日期相同的日期

    如果轮换日期为>;开始日期
    例如:

    startFromHere = 3 //wednesday
    rotateFromHere = 11
    

    输出将为:0,表示星期天

    检查此代码,如果有用,请给我评分。谢谢