我长时间困扰这样的问题: 任务是" blah blah ..然后,您将获得一个未知数量的名称来查询您的电话簿..." 就像我说的标题我在使用这个条件" hasNext"。如何在没有明确结束输入知识的情况下打破这个循环,将在控制台中写入什么以及输入的内容?我在想虽然while循环会帮助我,但仍然没有预期的结果:(。
感谢您的任何答案,如果对于衣着如此明显感到抱歉 - 我正在寻找类似的问题/回答,但没有一个有效:(
编辑(完成任务在这里:https://www.hackerrank.com/challenges/30-dictionaries-and-maps):
public class Test {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int k = 0; k < a; k++) {
String name = sc.next();
int numer = sc.nextInt();
map.put(name, numer);
}
while(sc.hasNext()){
String name=sc.next();
sc.nextLine();
list.add(name);
}
sc.close();
for (String k : list) {
if (map.containsKey(k)) {
System.out.println(k + "=" + map.get(k));
} else {
System.out.println("Not found");
}
}
}
}
答案 0 :(得分:0)
我想你可能正在寻找break
。
while(scanner.hasNext()){
String next = scanner.nextLine();
if(next.equals("quit")){
//you will exit the loop here
break;
}
System.out.println(next);
//more code here
}
答案 1 :(得分:0)
它已经解决了,但未来可能会有所帮助:D
public class Test {
public static void main(String[] args) {
HashMap<String,Integer> mapa = new HashMap<>();
ArrayList<String> lista = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
boolean condition = true;
for(int k = 0; k < a; k++) {
String imie = sc.next();
int numer = sc.nextInt();
mapa.put(imie, numer);
}
while(condition == true) {
try {
String line;
while(!(line = sc.nextLine()).isEmpty()) {
lista.add(line);
}
}
catch(NoSuchElementException exception) {
condition=false;
}
}
sc.close();
for(String k: lista) {
if(mapa.containsKey(k))
System.out.println(k + "=" + mapa.get(k));
else
System.out.println("Not found");
}
}
}
答案 2 :(得分:0)
您问题的可能解决方案:
public static void main(String[] args) throws IOException
{
HashMap<String, Integer> map = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int k = 0; k < a; k++) {
String name = sc.next();
int numer = sc.nextInt();
map.put(name, numer);
}
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String name;
while ((name = in.readLine()) != null && name.length() != 0)
{
list.add(name);
}
for (int i = 0; i < list.size(); i++)
{
if (map.containsKey(list.get(i)))
{
System.out.println(list.get(i) + "=" + map.get(list.get(i)));
} else
{
System.out.println("Not found");
}
}
sc.close();
}