使用Java编译接受任何输入的代码,从字符串到双精度,浮点数,整数等,但只能基于整数进行处理。如果它收到一个double,float或者一个字符串,它只会产生一条提示用户再次尝试的消息。我不确定如何滚动,所以这是我现在的代码。仅限严格整数如果/然后循环
import java.util.Scanner;
public class Sand
{
public static void main(String[] args)
{
int firstInt, secondInt, thirdInt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Hi. I'm going to be asking you for three integers in just a moment.");
System.out.println("An integer is defined as a WHOLE number that's not a fraction or decimal.");
System.out.println("I swear to you, I will go off if you put in a non-whole number...");
System.out.println("Okay go ahead and type in the first of the three integers:");
if (keyboard.hasNextInt())
{
firstInt = keyboard.nextInt();
System.out.println("Red.");
System.out.println("So the first integer is " + firstInt);
System.out.println("Okay go ahead and type in the second of the three integers: ");
if (keyboard.hasNextInt())
{
secondInt = keyboard.nextInt();
System.out.println("Green.");
System.out.println("So the first and second integers are " + firstInt + " and " + secondInt);
}
else
{
System.out.println("Orange.");
System.out.println("Please try again.");
}
}
else
{
System.out.println("Blue.");
System.out.println("Please try again.");
}
}
}
我有橙色和蓝色表示有一些输入错误,但它不完整的时间。我不知道如何处理这个问题,无论是循环还是for循环或try/catch。在学习Java时,我是新手,所以一些#注解在这方面会很有帮助。该代码旨在从字符串中读取用户中的三个整数。这很简单,但分析输入是我挣扎的地方。
“代码旨在从用户字符串中读取三个用户整数的数字” - 您是否尝试提取用户输入的字符串中出现的前三个整数。前 - 如果输入是 - “1年去2名水手赢3美元”是你的程序应该提取1 2和3?或者输入应该是1(和)2(和)3? – opensam
这对你来说可能有点高级,但是如果输入不正确,使用异常和异常处理来让事务死掉可能是一个很好的方法来处理这样的问题 – ControlAltDel