停止扫描程序读取用户输入java? [英] Stop scanner from reading user input java?

查看:306
本文介绍了停止扫描程序读取用户输入java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写此方法,该方法一直向用户读取,直到输入exit字样。我尝试了休息和循环;它不起作用。我正在尝试,但即使输入退出这个词,它也不会停止。任何想法如何解决这一问题?谢谢。

I am trying to write this method, which keeps reading from the user, until the word "exit" is inputted. I tried with a break and for loop; it didn't work. I was trying with while, but it does not stop even when the word "exit" is inputted. Any ideas how to fix this? Thanks.

public void read(Scanner scanner){

while(3<4){
String in = scanner.nextLine();
Scanner scanner_2 = new Scanner(in);

String name = null;

if(scanner_2.hasNext()){
  //create and add the user to the user container class
  name = scanner_2.next();
  System.out.println(name);
}

if(name == exit)
//stop or break the while loop
}
}


推荐答案

name == exit 错误。

你想要

name.equals(exit)

name.equals("exit")

取决于exit是变量还是字符串文字, 分别。在Java中, == 表示引用相等(例如,这两个引用是否指向内存中的相同地址),而。等于表示对象等效,开发人员在类中通常覆盖

depending on whether exit is a variable or a string literal, respectively. In Java, == means reference equality (e.g Are these two references pointing to the same address in memory), whereas .equals means object equivalence, which is typically overriden in the class by the developer.

这篇关于停止扫描程序读取用户输入java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆