简体   繁体   中英

Asking a user to input a number

so just want to make sure that my code's alright.

the objective is to 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.

here's my code:

 /*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!"); } } }

Your code looks fine to me. I can't tell what your question is, but I did a few tests:

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:~$ 

Everything looks good here!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM