这是我第一次参加编程课程。这也是我的第一个任务,我不知道如何设置用户的数字输入,范围从1000到9999.
我的任务是创建一个代码,要求用户输入四位整数,然后显示彼此相应的3个空格(提示:使用除法和余数算术)。 我终于让它打印出彼此远离的每个3号空间。
问题在于我的老师说四位数整数的范围是1000-9999。因此,当我尝试输入0001时,它打印出来: 0 0 0 1
如果我放12345,它会打印出来: 12 3 4 5
无论如何都要这样做?
非常感谢你帮助我
我可以发布一张图片,因为我是这个论坛的新手。
import java.util.Scanner;
public class DigitsDemo
{
public static void main ( String[] args )
{
Scanner input = new Scanner ( System.in );
System.out.print ( "Enter four digit numbers: " );//prompt the user to enter numbers
int n = input.nextInt();//read number entered by user
// determine the 5 digits
int Digit1 = n / 1000;
int Digit2 = n % 1000 / 100;
int Digit3 = n % 1000 % 100 / 10;
int Digit4 = n % 1000 % 100 % 10 / 1;
System.out.println ( "The four digits integers are:" );
System.out.printf ( "%d %d %d %d\n%s\n", Digit1, Digit2, Digit3, Digit4, "Written by blabla" );
}
答案 0 :(得分:0)
my teacher says that a four digit integer are ranging from 1000-9999
每次用户将数据输入到流时,您需要一个while循环检查数据,如果是if statement
则检查整数是否超出范围,如果是,则让用户再次尝试。< / p>
<强>样品:强>
public static void main ( String[] args )
{
Scanner input = new Scanner ( System.in );
System.out.print ( "Enter four digit numbers: " );//prompt the user to enter numbers
int n = input.nextInt();//read number entered by user
// determine the 5 digits
int Digit1;
int Digit2;
int Digit3;
int Digit4;
while(true)
{
if(n < 1000 || n > 9999)
{
System.out.println("Out of range, Sorry try again:");
System.out.print ( "Enter four digit numbers: " );//prompt the user to enter numbers
n = input.nextInt();//read number entered by user
} else
{
Digit1 = n / 1000;
Digit2 = n % 1000 / 100;
Digit3 = n % 1000 % 100 / 10;
Digit4 = n % 1000 % 100 % 10 / 1;
break;
}
}
System.out.println ( "The four digits integers are:" );
System.out.printf ( "%d %d %d %d\n%s\n", Digit1, Digit2, Digit3, Digit4, "Written by blabla" );
}
<强>结果:强>
Enter four digit numbers: 12345
Out of range, Sorry try again:
Enter four digit numbers: 1234
The four digits integers are:
1 2 3 4
Written by blabla