How do I accept a variable from the console with javascript in Rhino? anything similar to cin or scanf?
console input function for rhino?
Asked Answered
Here's two lines that'll do what you want:
var stdin = new BufferedReader( new InputStreamReader(System['in']) )
var aLine = stdin.readLine();
In that case, how can I write a function that sets a variable to the console input? function getInput(variable){ //code goes here } –
Bellicose
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);
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
}());
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.
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);
Instead of a BufferedReader
, you can use a Console
:
var console = java.lang.System.console()
var name = console.readLine("What is your name? ");
© 2022 - 2024 — McMap. All rights reserved.