我如何反复将java中的数字乘以2直到达到一百万?

时间:2018-09-11 18:09:31

标签: java while-loop do-while multiplication

import java.util.Scanner;

class Main {

    static Scanner userInput = new Scanner(System.in);

    public static void main(String[] args) {
        int testNumber = userInput.nextInt();
        do{
             System.out.println(newNumber * 2);
             newNumber++;
        }while( testNumber < 1000000);
    }
}

6 个答案:

答案 0 :(得分:3)

将数字乘以2后,您需要更新数字。

newNumber = newNumber * 2;
System.out.println(newNumber);

您还使用newNumbertestNumber,而newNumber似乎没有在任何地方定义...

}while( ***testNumber***newNumber*** < 1000000);

您需要选择一个,因为如果要更新newNumber但在循环中比较testNumber,则会创建一个无限循环。

除非您在发布后遗漏了某些内容,否则显示的代码不应编译。

答案 1 :(得分:1)

您对循环有正确的想法,但是变量有多个问题。

  1. 您的第一个问题是您从用户那里读了一个变量-<,但是(错误地)您正在操纵一个完全不同变量-testNumber。 / li>
  2. 第二个问题是您要测试未更改变量作为停止条件。

您可能希望循环如下:

newNumber

答案 2 :(得分:1)

您还可以为其创建递归方法。

public int reachMillion(int num) {
  if(num<=0)
    return -1;          // indicating it is not possible.
  if(num>=1000000)      // Base Condition denoting we have reached 1 million 
    return num;
  return reachMillion(num*2); // recursive part to multiply by 2 until we reach 1 million
}

答案 3 :(得分:1)

class Main {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
    int newNumber = 0;

    do{
       System.out.println("Enter a positive number: ");

       try{
          newNumber = userInput.nextInt();
       }catch(Exception ignored){  }

       System.out.println("");

    }while(newNumber <= 0);

    System.out.println("-----  " + newNumber + "  multiply by 2 ------");

    while(newNumber <= 1_000_000){
         System.out.print("2 * " + newNumber +" = ");
         newNumber <<= 1;//in some compilers left shift is faster than multiply           
         System.out.println(newNumber);
    }

}

答案 4 :(得分:1)

@brso05 has done well描述这里出了什么问题。我想提供一个完整的示例:

import java.util.Scanner;



public class Main {

    private static Scanner userInputScanner = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.print("Please input a number: ");

        int userInputNumber = userInputScanner.nextInt();
        System.out.println();

        int newNumber = userInputNumber;

        while (newNumber < 1_000_000) {
            newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
            System.out.println(newNumber);
        }
    }
}

Try it online!


当心!!该代码不会处理任何错误的用户输入。例如,如果给它0,它将永远循环;如果给它foo,它将崩溃。如果您想处理用户输入的所有极端情况,可以这样做:

import java.util.*;



public class Main {

    private static Scanner userInputScanner = new Scanner(System.in);

    public static void main(String[] args) {

        int userInputNumber;

        // 
        while(true) {
            System.out.print("Please input a number: ");
            if (userInputScanner.hasNext()) {
                // The user gave us something, but we don't know if it's a number

                String rawUserInput = userInputScanner.next();

                try {
                    userInputNumber = Integer.parseInt(rawUserInput);

                    // If that previous line runs, the user has given us an integer!
                    System.out.println();
                    if (userInputNumber > 0) {
                        // The user has given a valid number. Break out of the loop and multiply it!
                        break;
                    }
                    else {
                        // The user has given a bad number. Tell them why and ask again.
                        System.out.println("The number has to be greater than 0.");
                    }
                }
                catch (NumberFormatException exception) {
                    // The user has given us something, but it wasn't an integer
                    System.out.println();
                    System.out.println("That is not a number: " + exception.getMessage());
                }
            }
            else {
                // There is no input, so we can't do anything.
                return;
            }
        }
        // Done looping through user input

        int newNumber = userInputNumber;

        while (newNumber < 1_000_000) {
            newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
            System.out.println(newNumber);
        }
    }
}

Try it online!

答案 5 :(得分:0)

do-while循环中有一个棘手的部分。在这种类型的循环中,首先执行do部分。对于下面的示例,尽管输入已经大于1000000,但它会显示1000001。

public void doWhileLoop() {

    int num = 1000001;
    do {
        System.out.println(num);
        num *= 2;
    } while (num < 1000000);
}

因此,在do-while循环中执行某些操作之前,最好使用一些保护性子句(也称为if-statements)。喜欢,

public void doWhileLoop() {

     int num = 1000001;
     if(num >= 1000000) {
        return;
     }
     do {
         System.out.println(num);
         num *= 2;
     } while (num < 1000000);
}