我一直在尝试编写一个程序,使用while循环返回输入的第一个和最后一个数字.
这是我到目前为止所得到的:
import java.util.Scanner;
public class FirstLastInt {
public static void main(String[]args)
{
int fdig, ldig, num;
Scanner in = new Scanner(System.in);
System.out.println("Enter an Integer.");
num = in.nextInt();
ldig = num%10;
while (num > 0)
{ fdig = num/10;
num = num/10;
System.out.println("The first digit is " + fdig + ", and the last digit is " + ldig + ".");
}
}
Run Code Online (Sandbox Code Playgroud)
num是输入的整数,fdig是第一个数字,ldig是最后一个数字.
我认为最后一位数字将始终为num%10,并且我实现了到目前为止使用while循环,就像它写的将返回第一个数字......以及一堆其他数字,我真的不需要.
例如:
run:
Enter an Integer.
98884
The first digit is 9888, and the last digit is 4.
The first digit is 988, and the last digit is 4.
The first digit is 98, and the last digit is 4.
The first digit is 9, and the last digit is 4.
The first digit is 0, and the last digit is 4.
BUILD SUCCESSFUL (total time: 3 seconds)
Run Code Online (Sandbox Code Playgroud)
看起来循环在我得到我想要的数字之前和之后运行.无论如何要指定我想要打印哪一行?(在示例中,它是"第一个数字是9,最后一个数字是4.")
如果你想继续使用你自己的代码来看看如何以这种方式实现它,那么改变你的while条件并在外面进行系统打印:
import java.util.Scanner;
public class FirstLastInt {
public static void main (String[] args) {
int ldig, num;
Scanner in = new Scanner(System.in);
System.out.println("Enter an Integer.");
num = in.nextInt();
ldig = num % 10;
// keep looping num until it is in the range of 0-9
while (num >= 10) {
num = num / 10;
}
//initialize fdig variable and set it equal to num, just to make things clearer
int fdig = num;
System.out.println("The first digit is " + fdig + ", and the last digit is " + ldig + ".");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7972 次 |
| 最近记录: |