私は ユーザーが何かを入力し、入力にどのようなタイプのデータが出力されるのかを示すJavaプログラムを作成しますか?たとえば :データ型の認識
Input: 25
Output: integer
Input: ABC
Output: string
Input: 12.7
Output: float/double.
私は
私は ユーザーが何かを入力し、入力にどのようなタイプのデータが出力されるのかを示すJavaプログラムを作成しますか?たとえば :データ型の認識
Input: 25
Output: integer
Input: ABC
Output: string
Input: 12.7
Output: float/double.
私は
これはあなたの目的のために働く必要があります。
import java.util.Scanner;
public class DataType
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
if(in.hasNextByte(2))
System.out.println("Byte");
else if(in.hasNextInt())
System.out.println("Integer");
else if(in.hasNextFloat())
System.out.println("Float");
else if(in.hasNextBoolean())
System.out.println("Boolean");
else if(in.hasNext())
System.out.println("String");
}
}
注if...else
文の順序は、ここで非常に重要であることパターンに関する以下の設定関係のために:
hasNext..()
Scanner
クラスのメソッドなどBigInteger
、short
のかなり多くがあります。 、 等々。詳細については、Scannerクラスのドキュメントを参照してください。
単純なアプローチはこのように行くことができるが、これをうまくする方法について無知だとして助けてください。 Xが整数として解析することができた場合は、いくつかの入力文字列 X.
(「解析」とは、Integer.parseInt() ...あなたはXで渡します。そのメソッドが例外をスローしない場合、Xは整数/ intであることがわかります)
しかし、このようなの検出は、有効な入力の定義に大きく依存します。潜在的なマッピングが含まれます。文字列を解釈する方法が数多くあります。それは数字ではないかもしれません。正しい書式文字列を指定すると、タイムスタンプになる可能性があります。
非常に最初のステップ:要件を明確にしてください!サポートしなければならない潜在的な入力フォーマットを理解する。彼らの "マッピング"について考えてみてください。そのタイプを識別するための潜在的なチェックが含まれます。
あなたは文字列を取得し、他のタイプとして、それを解析しようとすることができます:
Scanner s = new Scanner(System.in);//allows user input
input = s.nextLine();//reads user input
try{//java will try to execute the code but will go to the catch block if there's an exception.
int inputInt = Integer.parseInt(input);//try to convert input to int
catch(Exception e){
e.printStackTrace();//this tell you exactly what went wrong. If you get here, then the input isn't an integer.
}
//same with double
文字列からデータを解析します。 – GurV
[入力の種類を確認していますか?](http://stackoverflow.com/questions/5333110/checking-input-type-how) –
[この前の回答] (http://stackoverflow.com/a/40062753/2449857)はこれを行う方法を正確に示しています。 –