此文件包含字符,字符串,整数和浮动数据 类型。写一个具有以下功能的类:在循环中 用户介绍数据类型(其中之一:char,String,int,double),in 响应应用程序打印。控制台所有值对应 文件中存在的类型。
我知道如何打印所有数据类型。但我不知道用户在循环中如何引入数据类型。
我的代码:
package homework_3;
import java.io.*;
import java.util.Scanner;
public class Main2 {
public static void main(String args[]) throws IOException {
int i;
double d;
String str;
char c;
FileWriter fw = new FileWriter("test.txt");
fw.write("Testing Scanner 10 12.2 one c b m");
fw.close();
FileReader fr = new FileReader("test.txt");
Scanner sc = new Scanner(fr);
while(sc.hasNext()) {
if(sc.hasNextInt()) {
System.out.println("int: " + sc.nextInt());
} else if(sc.hasNextDouble()) {
System.out.println("double: " + sc.nextDouble());
} else {
str = sc.next();
if(str.length() == 1) {
System.out.println("char: " + str);
} else {
System.out.println("String: " + str);
}
}
fr.close();
}
}
}
答案 0 :(得分:0)
创建一个数组(或地图)并将布尔值与所有类型相关联。将该数组的所有值初始化为False。 然后读取您的文件,如果找到某种类型的数据,请将boolean关联设置为true。 最后,打印与True值相关联的所有类型
//Initialize your map with the types your looking for
Map<String, Boolean> mapTypePresentInFile = new HashMap<String, Boolean>();
//Set the values to false, because you didn't read your file yet
mapTypePresentInFile.put("String", false);
mapTypePresentInFile.put("Integer", false);
mapTypePresentInFile.put("YourTypeHere", false);
//Read your file and when you detect the use of a type set the type to true
//I leave you the task to detect if a type is present
mapTypePresentInFile.remove("YourTypeHere");
mapTypePresentInFile.put("YourTypeHere", true);
//Then you check in your map if the type has been set to true
for(String type : mapTypePresentInFile.keySet()) {
if(mapTypePresentInFile.get(type) == true) {
System.out.println(type);
}
}