读取num并从1打印到num的程序

时间:2013-12-09 06:17:09

标签: java math logic

我需要逻辑方面的帮助,我需要程序从用户读取一个整数,然后将所有整数从1打印到num1。这就是我得到的:

 import java.util.Scanner;

     public class test 
    {       
    public static void main(String []args)
    {    

        Scanner scan = new Scanner(System.in);

        int num1;
        int num2;

        System.out.println("Enter any number:");
        num1 = scan.nextInt();

    while (num1<=num2) {    

        System.out.println(num+1);
    }
     }
    }

4 个答案:

答案 0 :(得分:3)

试试这个:

import java.util.Scanner;
    class test {
        public static void main(String[] args) {

            Scanner scan = new Scanner(System.in);

            int number;

            System.out.println("Enter any number:");
             // Note : The below statement will fail if user does not enter integer value
            number = scan.nextInt();

            // You can use while loop as well but for loop provides cleaner approach for iteration
            for (int i = 1; i <= number; i++) {
                // Print numbers sequentially from 1 to number
                System.out.println(i);
            }
        }
    }

答案 1 :(得分:0)

  

读取num并从1打印到num

的程序

尝试,

 System.out.println("Enter any number:");
 num1 = scan.nextInt();
 int i=1;
 while (i<=num1) {    
    System.out.println(i);
    i++;
 }

答案 2 :(得分:0)

喜欢这个

  int num1=0;
  int num2=0;
  System.out.println("Enter any number:");
  num1 = scan.nextInt();
  while (num2 <= num1) {    
       System.out.println(num2);
       num2++;
  } 

答案 3 :(得分:0)

非常感谢!自从我上次编写一个java程序以来,它已经有几年了,所以我有点生疏!这是我的最终代码:

import java.util.Scanner;

public class test
{
    public static void main (String[] args) 
    {
        Scanner scan = new Scanner(System.in);

        int num;
        int a=1;

        System.out.println("Enter any number:");
        num=scan.nextInt();

    while (a<=num)  
    {

        System.out.println(a);
        a++;}

    }}