有 Java 编程相关的问题?

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

java计算一个范围内输入用户的数字乘以多少

我在为考试做练习准备时又遇到了一个问题。 大家能帮我吗?非常感谢

write a program input an integer in the range 100 to 200 inclusive. If the user enters invalid input then your algorithm should re-prompt the user until the input is valid. Your algorithm should then count how many numbers between 500 and 1000 which are multiples of the number input. Finally, the count should be output to the user. You should make good use of sub-modules.

这是我的密码

import java.util.*;

public class Exam3
{
    public static void main(String args[])
    {
        int count = 0;
        int input = 0;

        Scanner sc = new Scanner(System.in);

            System.out.println("Enter number: ");
            input = sc.nextInt();

           while(input < 100 || input > 200)
            {
                System.out.println("Enter number between 100 to 200");
                input = sc.nextInt();

                count ++;

            }   
          System.out.println("count is: " + count);     
    }
    public static void int getCount(int input, int count)
    {
        for(int i = 499;i <= 1000; i++ )
        {
                if(i % input==0)
                {
                    count++;
                }            
        }
        return count;
    }
}

共 (1) 个答案

  1. # 1 楼答案

    算法应该是:

    输入正确后,找到[5001000]范围内的所有倍数。数一数

    根据我们的数学知识,检查所有的数字是一种糟糕的方法,在k*ak*a + a之间没有可被a整除的数字

    知道这一点并拥有input我们将temp的初始化值input放大input。如果在[500, 1000]范围内,我们放大计数器。就这么简单

    public static void main(String args[]) {
        int count = 0;
        int input = 0;
    
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number: ");
        input = sc.nextInt();
    
        while (input < 100 || input > 200) {
            System.out.println("Enter number between 100 to 200");
            input = sc.nextInt();
            count++;
        }
        System.out.println(input + " fits " + count(input) + " times");
    }
    
    
    private static int count(int input) {
        int result = 0;
        int temp = input;
        while (temp <= 1000) {
            if (temp >= 500) {
                result++;
            }
            temp += input;
        }
        return result;
    }
    

    根据你的代码,我发现了一些问题。我将指出它们,因为这对练习Java很重要

    • 方法可以是void或返回int。你不能有void int。在本例中,我们返回int,因此int是返回类型
    • 坚持Java风格很重要。不要放太多空行,保持缩进
    • 使用EclipseIntelliJIntelliJ更专业)。它们将指向未使用的代码块,这样您就知道getCount没有被调用