要求用户输入数字

时间:2015-10-22 00:20:08

标签: java

所以只是想确保我的代码没问题。

目标是显示一个高4线的三角形,由两个不同的数字组成。该程序将要求两个数字:一个在0和4之间,一个在5和9之间。三角形的第一行和第三行将填充第一个数字;三角形的第二行和最后一行将填充第二个数字。

这是我的代码:

/*This program displays a triangle 4 lines high, made up of two different
numbers. The program will ask for two numbers: one between 0 and 4 
and one between 5 and 9. The first and third line of the triangle 
will be filled with the first number; the second and last line of the
triangle will be filled with the second number. */
import java.util.Scanner;

public class Question {
  public static void main(String args[]) {
   Scanner keyboard = new Scanner (System.in);
      int num1, num2;
      
	   System.out.print("Input a number between 0-4: ");
      num1 = keyboard.nextInt();
      
      System.out.print("Input a number between 5-9: ");
      num2 = keyboard.nextInt();
      
      if (num1>=0 && num1<=4 && num2>=5 && num2<=9){
      System.out.println("   \t   " + num1);
      System.out.println("  \t  "+num2 +" "+ num2);
      System.out.println(" \t " + num1+" "+ num1+" "+ num1);
      System.out.println("\t"+num2 +" "+ num2+" "+ num2+" "+ num2);

      }
      else{
         
      System.out.println("Please Try again!");
      }
   }
}

1 个答案:

答案 0 :(得分:1)

您的代码对我来说很好。我不知道你的问题是什么,但我做了一些测试:

jakesyl@jakesyl-ubuntu:~$ javac Question.java 
jakesyl@jakesyl-ubuntu:~$ java Question 
Input a number between 0-4: 4
Input a number between 5-9: 8
       4
      8 8
     4 4 4
    8 8 8 8
jakesyl@jakesyl-ubuntu:~$ java Question 
Input a number between 0-4: 0
Input a number between 5-9: 2
Please Try again!
jakesyl@jakesyl-ubuntu:~$ java Question 
Input a number between 0-4: 4
Input a number between 5-9: 2
Please Try again!
jakesyl@jakesyl-ubuntu:~$ java Question 
Input a number between 0-4: 6
Input a number between 5-9: 9
Please Try again!
jakesyl@jakesyl-ubuntu:~$ java Question
Input a number between 0-4: 2
Input a number between 5-9: 4
Please Try again!
jakesyl@jakesyl-ubuntu:~$ 

这里的一切看起来都不错!