hashset输入java
我正在研究下面的问题,我很接近,但在第19行和第32行,我得到了以下错误,无法找出它 foreach不适用于表达式类型 用于(字符串位置:s) 问题:hashset输入java,java,hashset,Java,Hashset,我正在研究下面的问题,我很接近,但在第19行和第32行,我得到了以下错误,无法找出它 foreach不适用于表达式类型 用于(字符串位置:s) 问题: class Dodgy { public static void main(String[] args) { HashSet<String> hs = new HashSet<String>(); Scanner sc1 = null; try {sc1 = new Scanner(new File(
class Dodgy {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<String>();
Scanner sc1 = null;
try {sc1 = new Scanner(new File("taxpayers.txt"));}
catch(FileNotFoundException e){};
while (sc1.hasNextLine()) {
String line = sc1.nextLine();
String s = line;
for (String place: s) {
if((hs.contains(place))==true){
System.out.println(place + " is a dodgy character.");
hs.add(place);}
}
}
Scanner sc2 = null;
try {sc2 = new Scanner(new File("unemployed.txt"));}
catch(FileNotFoundException e){};
while (sc2.hasNextLine()) {
String line = sc2.nextLine();
String s = line;
for (String place: s) {
if((hs.contains(place))==true){
System.out.println(place + " is a dodgy character.");
hs.add(place);}
}
}
}
}
税务稽查员可以使用两个文本文件,分别称为unemployee.txt和damporters.txt。每个文件包含一组名称,每行一个名称。检查员认为这两个文件中出现的任何人都是狡猾的人物。编写一个程序,打印出不可靠字符的名称。充分利用Java对集合的支持
我的代码:
class Dodgy {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<String>();
Scanner sc1 = null;
try {sc1 = new Scanner(new File("taxpayers.txt"));}
catch(FileNotFoundException e){};
while (sc1.hasNextLine()) {
String line = sc1.nextLine();
String s = line;
for (String place: s) {
if((hs.contains(place))==true){
System.out.println(place + " is a dodgy character.");
hs.add(place);}
}
}
Scanner sc2 = null;
try {sc2 = new Scanner(new File("unemployed.txt"));}
catch(FileNotFoundException e){};
while (sc2.hasNextLine()) {
String line = sc2.nextLine();
String s = line;
for (String place: s) {
if((hs.contains(place))==true){
System.out.println(place + " is a dodgy character.");
hs.add(place);}
}
}
}
}
class-dodge{
公共静态void main(字符串[]args){
HashSet hs=新的HashSet();
扫描仪sc1=空;
试试{sc1=newscanner(新文件(“纳税人.txt”);}
catch(filenotfounde){};
while(sc1.hasNextLine()){
String line=sc1.nextLine();
字符串s=行;
用于(字符串位置:s){
如果((hs.contains(place))==true){
System.out.println(place+“是一个狡猾的字符。”);
hs.add(place);}
}
}
扫描仪sc2=空;
试试{sc2=newscanner(新文件(“unemployee.txt”);}
catch(filenotfounde){};
while(sc2.hasNextLine()){
String line=sc2.nextLine();
字符串s=行;
用于(字符串位置:s){
如果((hs.contains(place))==true){
System.out.println(place+“是一个狡猾的字符。”);
hs.add(place);}
}
}
}
}
Foreach仅适用于类型。因为字符串不是,所以错误也是
如果您打算迭代字符串中的字符,那么将该“s”替换为“s.tocharray()”,它返回一个数组,该数组是
java.lang.Iterable
您试图迭代“字符串中的每个字符串”-这到底是什么意思
感觉您只需要在每个文件中的每一行上迭代。。。您不需要在一行内迭代
第二,在第一个循环中,您只查看第一个文件,那么您怎么可能检测到不可靠的字符呢
我想把这个问题抽象为:
- 编写一个方法来读取文件并填充哈希集
- 调用该方法两次以创建两个集合,然后找到交点