[英]scanner java validation and multiple instances
我是java的新手,正在做作業。 我必須從用戶處請求3個輸入,並且需要驗證。 如果僅使用掃描儀的一個實例執行此操作,那么我會一團糟。
如果我使用三個實例進行一些變通,則我的代碼可以正常工作。 僅我認為這不是最佳做法。 我一直在閱讀有關掃描儀的手冊,但無法理解問題
謝謝
enter code here
Scanner input=new Scanner(System.in);
Scanner input2=new Scanner(System.in);
int input_integer=0;
double input_double=0.0;
String input_string="";
double value=0;
System.out.print("\n Please enter a number: ");
while(!input.hasNextInt()){
System.out.println("***** Error: the char inserted is not a number! *****");
String input_wrong=input.next();
System.out.print("\n Please enter a number: ");
}
input_integer=input.nextInt();
System.out.print("\n Please enter a double: ");
while(!input.hasNextDouble()){
System.out.println("***** Error: the char inserted is not a double! *****");
String input_wrong=input.next();
System.out.print("\n Please enter an double: ");
}
input_double=input.nextDouble();
System.out.print("\nPlease enter a string: ");
input_string=input.nextLine();
因此,我有兩個create 3掃描儀實例,並且還使用一個字符串在while循環中將錯誤的輸入分配給能夠再次提示。 有什么建議嗎? 我相信有更好的方法,但我會盡力理解。
謝謝!
我不確定我是否理解您遇到的問題,但是掃描儀有一些奇怪的行為,這些行為不會立即顯現出來。 例如,如果鍵入“ 1234bubble”,然后按Enter,則nextInt()將返回1234,下一個nextLine()將顯示“ bubble”。 對於這樣的輸入,通常不希望這樣做,因為“ 1234bubble”不是整數,並且當用戶按下Enter鍵時應該會失敗。
因此,我通常只使用nextLine()函數。 然后,我只是使用Integer.parseInt(..)之類的函數手動處理數據。 這樣,我可以保證以清晰明了的方式處理整行,這與其他創建混亂代碼的技術不同。
這是我編寫程序的方式:
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Main
{
static Random rand = new Random();
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
int input_integer = 0;
double input_double = 0.0;
String input_string = "";
double value = 0;
while (true)
{
System.out.print("Please enter an integer: ");
// Get the entire next line of text
String text = input.nextLine();
try
{
// Try to turn the line into an integer
input_integer = Integer.parseInt(text);
// Turning it into an int succeeded!
// Leave the while loop
break;
} catch (NumberFormatException e)
{
// Turning it into an int failed.
System.out.println("***** Error: the text inserted is not an integer! *****");
}
}
while (true)
{
System.out.print("Please enter a double: ");
// Get the entire next line of text
String text = input.nextLine();
try
{
// Try to turn the line into a double
input_double = Double.parseDouble(text);
// Turning it into an double succeeded!
// Leave the while loop
break;
} catch (NumberFormatException e)
{
// Turning it into an double failed.
System.out.println("***** Error: the text inserted is not a double! *****");
}
}
System.out.print("Please enter a string: ");
input_string = input.nextLine();
// This is done automatically when the program stops, but it's
// a good habit to get into for longer running programs.
input.close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.