Reading System.in from the Console using Intellij and JUnit

久未见 提交于 2020-01-11 11:27:06

问题


The following code works nicely when running the code through a main in Idea

System.in.read()

However the same code inside a junit method is not working

public void testConsoleRead()
{
  System.in.read();
}

Any idea how to make this work, or something similar ?


回答1:


You need to start the IDE with -Deditable.java.test.console=true (e.g. via "Help" > "Edit Custom VM Options..."), see this comment.




回答2:


You need to use the Scanner class.

First import it:

import java.util.Scanner

Now to use it:

Scanner scanner = new Scanner(System.in);
String text = scanner.next();
scanner.close();

There are more methods like scanner.nextLine(); that you should look at.

Also you might need to handle some Exceptions here but that's not difficult to figure out.



来源:https://stackoverflow.com/questions/38482844/reading-system-in-from-the-console-using-intellij-and-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!