简体   繁体   中英

Reading System.in from the Console using Intellij and JUnit

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 ?

您需要使用-Deditable.java.test.console=true启动IDE(例如,通过“帮助”>“编辑自定义VM选项...”),请参见此注释

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM