嗨我有一个包含一些2位整数的文本文件。我想找出两位数字中的任何一个是否包含特定的单个数字。文本文件中的示例编号为12。我想测试这些数字中是否有1或3位数:
package algoritmahomework3;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AlgoritmaHomework3 {
private static BufferedReader br = null;
private static String[] split;
private static String fileName = "input.txt";
public static void main(String[] args) throws IOException {
try {
// txt String variable is putting the file's content here.
br = new BufferedReader(new FileReader("C:\\Users\\Alparslan\\Desktop\\input.txt"));
String txt = " ";
String msg = " ";
while((msg = br.readLine()) != null){
txt += msg;
}
for(int i=0; i<txt.length(); i++){
split = txt.split(" ");
// split is a static array to put inside the splitted data which is in txt file.
// This succeed. You can test it using below line of code.
//System.out.println(Arrays.toString(split));
}
printGraph(txt);
} catch (FileNotFoundException ex) {
Logger.getLogger(AlgoritmaHomework3.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void printGraph(java.lang.String txt) {
if(Integer.parseInt(txt)==1){
}
}
}
答案 0 :(得分:0)
如果你有两位数作为字符串,例如&#34; 12&#34;您可以使用.indexOf
方法测试它是否包含另一个字符串。
String s = "12";
if (s.indexOf("1") != -1) {
// it contains "1"
}
if (s.indexOf("2") != -1) {
// it contains "2"
}
答案 1 :(得分:0)
您可以提取数字:
String numberStr = yourStr.replaceAll("[^0-9]", "");
如果你想保持小数点使用:
yourStr.replaceAll("[^\\.0123456789]","");
然后你可以查看个别号码。
在数字之间添加空格:
String numberStr = yourStr.replaceAll("[^0-9]", " ");
仅获取数字,并将它们存储到字符串数组中:
String arr[] = s1.trim().split("[a-zA-Z ]+"); // Please note a space is there after Z
然后将所有数字存储为整数:
for (int i = 0; i < arr.length; i++){
no = Integer.parseInt(arr[i]);
System.out.println(no);
}