elementary java homework?

2014-11-23 6:53 am
hello guys,
well basically i have zero java knowledge, so don't mind me asking such kind of dumbass question( to you but not to me lol)
so, i have a .txt file in which there is a number in such line (for example, 0 and 1)
i want to print out "yes" if all numbers are 0,
print out "no" if all numbers are 1,
and print out nothing if the numbers are not the same, i.e. some are 0 and some are 1.
how can i do it?
thanks

回答 (1)

2014-11-23 9:35 am
import java.io.*;
import java.util.*;
import java.util.regex.*;

public class Sample {
public static void main(String[] args) {
try {
if (args.length != 1) {
System.err.println("Usage: java Sample {filename}");
return;
}
Object[] array = read(args[0]);
for (int i = 0; i < array.length; i++)
doJudge((String)array[i]);
} catch (Exception ex) {
ex.printStackTrace();
}
}

private static void doJudge(String line) {
// http://en.wikipedia.org/wiki/Regular_expression
Pattern p0 = Pattern.compile("^0+$");
Matcher m0 = p0.matcher(line);
Pattern p1 = Pattern.compile("^1+$");
Matcher m1 = p1.matcher(line);

if (m0.find()) {
// i want to print out "yes" if all numbers are 0,
System.out.println("yes");
} else if (m1.find()) {
// print out "no" if all numbers are 1,
System.out.println("no");
} else {
// and print out nothing if the numbers are not the same, i.e. some are 0 and some are 1.
}
}

private static Object[] read(String fileName) throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
ArrayList<String> list = new ArrayList<String>();
String line = reader.readLine();

while (line != null){
list.add(line);
line = reader.readLine();
}
return list.toArray();
}
}


https://www.youtube.com/watch?v=T-zeKJM5_o0


收錄日期: 2021-04-23 22:30:51
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20141122225312AA39Zvm

檢視 Wayback Machine 備份