How to manage ENTER key in JAVA

How to manage ENTER key in JAVA

by Mi Po -
Number of replies: 2

Hello everybody,

I'm trying to test a kind of code like this one:

import java.util.Scanner;
public class Demo {
 public static void main(String[] args){
     Scanner sc = new Scanner(System.in);
     System.out.print("number 1 :");
     int n1= sc.nextInt();
     System.out.print("number 2 :");
     int n2= sc.nextInt();
     int s = n1+n2;
     System.out.println(s);
 }
When i execute it in a console , with for example 3 and 4 for number 1 and number 2, i get :
number 1 :3
number 2 :4
7

But with code runner, i have to write for expected output :
number 1 :number 2 :7

All in the same line.

with standard input :
 3
 4

I think that it's because ENTER key is not managed by code runner as in console mode.
 Is it possible to tell him that the user has pressed the ENTER key to get the same display as in console mode ?
Thank you for your help.
Michel
In reply to Mi Po

Re: How to manage ENTER key in JAVA

by Richard Lobb -

When reading from the console, each key press is echoed to the display but when reading from a file no such echoing takes place. When a question that does console I/O is tested in CodeRunner, the data supplied in the test case as input is being read from a file, so there is no input echoing of the ENTER key or any other characters.

In the python3_w_input question type, we replace Python's input() function, which reads from the console, with one that prints to stdout the input data, as it is consumed. But that approach isn't an option in Java, AFAIK, if students are using the built-in Java input functions.

The only three solutions that I know of are:

  1. Spend some extra time in the course explaining console keyboard echoing and why this doesn't happen when stdin is redirected to a file. Hence, why the CodeRunner output isn't what they first expect.
  2. Provide students with a custom readline() function that reads input from the console. Require that they use that in all their programs. Then, in the CodeRunner question type, replace that function with a version that does keyboard input echoing.
  3. Don't set questions involving interactive console I/O!
In reply to Richard Lobb

Re: How to manage ENTER key in JAVA

by Mi Po -
Thank you very much for your reply.
I'm going to try the second solution.