console input function for rhino?
Asked Answered
P

6

8

How do I accept a variable from the console with javascript in Rhino? anything similar to cin or scanf?

Pricecutting answered 22/12, 2010 at 11:52 Comment(0)
P
9

Here's two lines that'll do what you want:

var stdin = new BufferedReader( new InputStreamReader(System['in']) )
var aLine = stdin.readLine();
Photomultiplier answered 27/2, 2011 at 2:28 Comment(1)
In that case, how can I write a function that sets a variable to the console input? function getInput(variable){ //code goes here }Bellicose
H
2

I hope this will help you:

Simple function that reads a line from console

function readline()
{
    var ist = new java.io.InputStreamReader(java.lang.System.in); 
    var bre = new java.io.BufferedReader(ist); 
    var line = bre.readLine();
    return line;
}
print("Name? ");
var name=readline();
print("Your name is: "+name);
Harbour answered 26/6, 2015 at 18:1 Comment(0)
G
1

In Rhino you have to remember to import Java packages before you can use them. Also, Java String differs from JavaScript native String, so you may want to cast it.

Here is a quick-and-dirty readln() that works the same in both SpiderMonkey and Rhino:

 var readln = (typeof readline === 'function') ? (readline) : (function() {
     importPackage(java.io);
     importPackage(java.lang);
     var stdin = new BufferedReader(new InputStreamReader(System['in']));

     return function() {
         return String(stdin.readLine());  // Read line, 
     };                                    // force to JavaScript String
 }());
Geanticline answered 15/3, 2011 at 20:35 Comment(0)
A
0

Just use the Java class library. I think this will work:

var stdin = java.lang.System.in;
var line = stdin.readLine();

At that point it's easy to convert the line to whatever type you like, or to break it into pieces using a RegExp.

This could garble Unicode input, but I'm not sure there's a good way around that, cross-platform.

Array answered 22/12, 2010 at 13:18 Comment(0)
U
0
var ins = java.lang.System.in;
var newLine = java.lang.System.getProperty("line.separator");
var is = new java.io.InputStreamReader(ins);
var sb=new java.lang.StringBuilder();
var br = new java.io.BufferedReader(is);
var line = br.readLine();
while(line != null) {
    sb.append(line);
    sb.append(newLine);
    line = br.readLine();
}
var stdin = ""+sb.toString();//java string != javascript string
console.log("stdin:"+stdin);
Unparalleled answered 7/5, 2014 at 16:51 Comment(0)
V
0

Instead of a BufferedReader, you can use a Console:

var console = java.lang.System.console() 
var name = console.readLine("What is your name? ");
Vulcanize answered 11/11, 2023 at 16:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.