How to take user input in jshell script? - java-9

Question:
How to take user input in jshell script? or what I'm doing wrong?
Note: I'm NOT looking how to pass arguments to jshell script.
Example:
For example script hello.java:
Scanner in = new Scanner(System.in);
System.out.print("Enter number n1: ");
int n1 = in.nextInt();
System.out.print("Enter number n2: ");
int n2 = in.nextInt();
System.out.println("n1 + n2 = "+ (n1 +n2));
/exit
It works if I type line by line in jshell, but then I run jshell hello.java it doesn't. Throws java.util.NoSuchElementException.
Output I getting:
#myMint ~/Java $ jshell hello.java
Enter number n1: | java.util.NoSuchElementException thrown:
| at Scanner.throwFor (Scanner.java:858)
| at Scanner.next (Scanner.java:1497)
| at Scanner.nextInt (Scanner.java:2161)
| at Scanner.nextInt (Scanner.java:2115)
| at (#3:1)
Enter number n2: | java.util.NoSuchElementException thrown:
| at Scanner.throwFor (Scanner.java:858)
| at Scanner.next (Scanner.java:1497)
| at Scanner.nextInt (Scanner.java:2161)
| at Scanner.nextInt (Scanner.java:2115)
| at (#5:1)
n1 + n2 = 0
My system: Linux Mint 18.2(x64), JShell Version 9.0.1

Per default, jshell delegates execution to a remote VM. If you pass --execution local it uses the same VM process, which provides an instance of System.in as expected. Tailored to your question, the following call should do the trick:
jshell --execution local hello.java
See details via jshell --help-extra or browse the API documentation at https://docs.oracle.com/en/java/javase/11/docs/api/jdk.jshell/module-summary.html

You can solve this issue, but not directly with JShell based code.
There is this project jshell_script_executor: https://github.com/kotari4u/jshell_script_executor
You can download it, and with small modification inside JShellScriptExecutor.java
from
try(JShell jshell = JShell.create()){
to
// This call will map System.in in your main code
// to System.in inside JShell evaluated code
try(JShell jshell =
JShell.builder()
.in(System.in)
.out(System.out)
.err(System.err)
.build()){
and (also) small modification of your code (I know this is not exactly what you are looking for - we don't use Scanner here):
/* Put this code into file.jshell */
import java.io.*;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int n1;
System.out.print("Enter the number: ");
n1 = Integer.parseInt(in.readLine());
int n2;
System.out.print("Enter the number: ");
n2 = Integer.parseInt(in.readLine());
System.out.println("n1 + n2 = " + (n1 + n2));
you can get it running:
> javac src/main/java/com/sai/jshell/extension/JShellScriptExecutor.java
> java -cp src/main/java com.sai.jshell.extension.JShellScriptExecutor ./file.jshell
Enter the number: 1
Enter the number: 2
n1 + n2 = 3
Well ... in fact it will work with your code as well - slightly modified:
/* Put this code into file_scanner.java */
import java.util.Scanner;
Scanner in = new Scanner(System.in);
System.out.print("Enter number n1: ");
int n1 = in.nextInt();
System.out.print("Enter number n2: ");
int n2 = in.nextInt();
System.out.println("n1 + n2 = "+ (n1 +n2));
and give it a try
> java -cp src/main/java com.sai.jshell.extension.JShellScriptExecutor ./file_scanner.java
Enter number n1: 1
Enter number n2: 2
n1 + n2 = 3

From JDK11 you can directly execute java source file:
$java Script.java
See Launch Single-File Source-Code Programs

Related

Android Kotlin replace while with for next loop

We have a HashMap Integer/String and in Java we would iterate over the HashMap and display 3 key value pairs at a time with the click of a button. Java Code Below
hm.put(1, "1");
hm.put(2, "Dwight");
hm.put(3, "Lakeside");
hm.put(4, "2");
hm.put(5, "Billy");
hm.put(6, "Georgia");
hm.put(7, "3");
hm.put(8, "Sam");
hm.put(9, "Canton");
hm.put(10, "4");
hm.put(11, "Linda");
hm.put(12, "North Canton");
hm.put(13, "5");
hm.put(14, "Lisa");
hm.put(15, "Phoenix");
onNEXT(null);
public void onNEXT(View view){
etCity.setText("");
etName.setText("");
etID.setText("");
X = X + 3;
for(int L = 1; L <= X; L++ ){
String id = hm.get(L);
String name = hm.get(L = L + 1);
String city = hm.get(L = L + 1);
etID.setText(id);
etName.setText(name);
etCity.setText(city);
}
if(X == hm.size()){
X = 0;
}
}
We decoded to let Android Studio convert the above Java Code to Kotlin
The converter decide to change the for(int L = 1; L <= X; L++) loop to a while loop which seemed OK at first then we realized the while loop was running for 3 loops with each button click. Also Kotlin complained a lot about these line of code String name = hm.get(L = L + 1); String city = hm.get(L = L + 1);
We will post the Kotlin Code below and ask the question
fun onNEXT(view: View?) {
etCity.setText("")
etName.setText("")
etID.setText("")
X = X + 3
var L = 0
while (L <= X) {
val id = hm[L - 2]
val name = hm.get(L - 1)
val city = hm.get(L)
etID.setText(id)
etName.setText(name)
etCity.setText(city)
L++
}
if (X == hm.size) {
X = 0
}
}
We tried to write a For Next Loop like this for (L in 15 downTo 0 step 1)
it seems you can not count upTo so we thought we would use the hm:size for the value 15 and just use downTo
So the questions are
How do we use the Kotlin For Next Loop syntax and include the hm:size in the construct?
We have L declared as a integer but Kotlin will not let us use
L = L + 1 in the While loop nor the For Next Loop WHY ?
HERE is the strange part notice we can increment X by using X = X + 3
YES X was declared above as internal var X = 0 as was L the same way
Okay, I'll bite.
The following code will print your triples:
val hm = HashMap<Int, String>()
hm[1] = "1"
hm[2] = "Dwight"
hm[3] = "Lakeside"
hm[4] = "2"
hm[5] = "Billy"
hm[6] = "Georgia"
hm[7] = "3"
hm[8] = "Sam"
hm[9] = "Canton"
hm[10] = "4"
hm[11] = "Linda"
hm[12] = "North Canton"
hm[13] = "5"
hm[14] = "Lisa"
hm[15] = "Phoenix"
for (i in 1..hm.size step 3) {
println(Triple(hm[i], hm[i + 1], hm[i + 2]))
}
Now let's convert the same idea into a function:
var count = 0
fun nextTriplet(hm: HashMap<Int, String>): Triple<String?, String?, String?> {
val result = mutableListOf<String?>()
for (i in 1..3) {
result += hm[(count++ % hm.size) + 1]
}
return Triple(result[0], result[1], result[2])
}
We used a far from elegant set of code to accomplish an answer to the question.
We used a CharArray since Grendel seemed OK with that concept of and Array
internal var YY = 0
val CharArray = arrayOf(1, "Dwight", "Lakeside",2,"Billy","Georgia",3,"Sam","Canton")
In the onCreate method we loaded the first set of data with a call to onCO(null)
Here is the working code to iterate over the CharArray that was used
fun onCO(view: View?){
etCity.setText("")
etName.setText("")
etID.setText("")
if(CharArray.size > YY){
val id = CharArray[YY]
val name = CharArray[YY + 1]
val city = CharArray[YY + 2]
etID.setText(id.toString())
etName.setText(name.toString())
etCity.setText(city.toString())
YY = YY + 3
}else{
YY = 0
val id = CharArray[YY]
val name = CharArray[YY + 1]
val city = CharArray[YY + 2]
etID.setText(id.toString())
etName.setText(name.toString())
etCity.setText(city.toString())
YY = YY + 3
}
Simple but not elegant. Seems the code is a better example of a counter than iteration.
Controlling the For Next Look may involve less lines of code. Control of the look seemed like the wrong direction. We might try to use the KEY WORD "when" to apply logic to this question busy at the moment
After some further research here is a partial answer to our question
This code only show how to traverse a hash map indexing this traverse every 3 records needs to be added to make the code complete. This answer is for anyone who stumbles upon the question. The code and a link to the resource is provide below
fun main(args: Array<String>) {
val map = hashMapOf<String, Int>()
map.put("one", 1)
map.put("two", 2)
for ((key, value) in map) {
println("key = $key, value = $value")
}
}
The link will let you try Kotlin code examples in your browser
LINK
We only did moderate research before asking this question. Our Appoligies. If anyone is starting anew with Kotlin this second link may be of greater value. We seldom find understandable answers in the Android Developers pages. The Kotlin and Android pages are beginner friendlier and not as technical in scope. Enjoy the link
Kotlin and Android

Cyclomatic Complexity number - do I have to count every statement separately as node?

I came across different ways of calculating CCN (according to formula CCN = E-N+2P)
One way was to count all the lines in the code separately and the other way is to count a few lines of code as one step; lets have the following example:
1 public class SumAndAverage {
2
3 public static void main (String[] args) {
4 int sum = 0;
5 double average = 0.0;
6 String message = "";
7
8 int num = Integer.parseInt(args[0]);
9
10 if ((num < 1) || (num > 100)) {
11 message = "Invalid number entered.";
12 } else {
13 for (int i = 1; i <= num; i++) {
14 sum += i;
15 }
16 average = (double) sum / num;
17 message = "The sum is " + sum + " and the average is " + average;
18 }
19 System.out.println(message);
20 }
21}
Counting every statement we'd get 12 - 11 + 2x 1 = 3
I was wondering if I "join" lines 4,5,6,8 and count them as one step and do the same with line 16 and 17, would that be correct too? The result would be the same as no of edges would also decrease: 8 - 7 + 2*1 = 3
The right way to calculate complexity is by considering blocks of code. A block of code is where there is no chance of dissecting the execution path.
McCabe's paper mentions the below:
The tool, FLOW, was written in APL to input the source code from Fortran files on disk. FLOW would then break a Fortran job into distinct subroutines and analyze the control structure of each subroutine. It does this by breaking the Fortran subroutines into blocks that are delimited by statements that affect control flow: IF, GOTO ,referenced LABELS, DO, etc.
For other information on complexity, also read through Cyclomatic complexity as a Quality measure

Swapping two numbers using only two variables

How is it performing swapping?
a=a+b
b=a+b
a=b+a
I don't agree that it's swap to a book!!!
The book options include "complements of values of a and b" ,"negate and b".Hope these options aren't satisfying it too???
The correct algorithm should be:
a = a + b
b = a - b
a = a - b
The swap is performed using XOR, which is typically written as a plus within a circle; for example:
a := 5
b := 7
a := a xor b (2)
b := a xor b (5)
a := b xor a (7)
I recently underwent an interview for java fresher, the interviewer asked me to perform swapping of two numbers (but in one line).
Swapping of two numbers can be performed in one line also, without using a temp variable.
The logic is really simple,
x is added with y in the same line, y is assigned as x which is subtracted by their sum.
after performing this one line arithmetics the numbers were swapped. (only in one line)
public class SwapInOneLine {
public static void main(String[] args) {
int x = 10; int y = 20;
System.out.println("Before Swaping: x = " + x + " and y= " + y);
x = x + y - (y = x);
System.out.println("After Swaping: x = " + x + " and y= " + y);
}}
output:
Before Swaping: x = 10 and y= 20
After Swaping: x = 20 and y= 10
We can use XOR (^) for this.
Advantage of XOR : As XOR works on bit level, it takes very less amount of time than any other operations.
If a = 5 and b = 7
then to swap :
a = a ^ b
b = a ^ b
a = a ^ b
Where '^' means XOR.
Result :
a = 7 and b = 5
Actually, it can be done by two ways:
int a = 5, b = 10;
Using Addition(+) and Subtraction(-)
a = a + b;
b = a - b;
a = a - b;
Using Multiple(*) and Division(/)
a = a * b;
b = a / b;
a = a / b;

How to Speed up Computation Time

I have written the following code:
combinationsstring = "List of Combinations"
for a = 0, 65 do
for b = 0, 52 do
for c = 0, 40 do
for d = 0, 28 do
for e = 0, 19 do
for f = 0, 11 do
for g = 0, 4 do
if (((1.15^a)-1)+((20/3)*((1.15^b)-1))
+((100/3)*((1.15^c)-1))+(200*((1.15^d)-1))
+((2000/3)*((1.15^e)-1))+((8000/3)*((1.15^f)-1))
+((40000/3)*((1.15^g)-1))) < 10000 then
combinationsstring = combinationsstring
.."\n"..a..", "..b..", "..c..", "..d
..", "..e..", "..f..", "..g
end
end
end
end
end
end
end
end
local file = io.open("listOfCombinations.txt", "w")
file:write(combinationsstring)
file:close()
I need to find all the sets of data that fit the following equation
(((1.15^a)-1)+((20/3)*((1.15^b)-1))+
((100/3)*((1.15^c)-1))+(200*((1.15^d)-1))+
((2000/3)*((1.15^e)-1))+((8000/3)*((1.15^f)-1))+
((40000/3)*((1.15^g)-1))) < 10000
each variable (a-g) is a real integer. So I calculated the maximum values for each of the 7 (the maximum for each variable will be when all the other values are 0). These maximum's are 65, 52, 40, 28, 19, 11 and 4 respectfully (62 = a, 52 = b and so on)
So I created 7 nested for loops (as shown in the code above) and in the middle block, i tested the 7 values to see if they fit the criteria, if they did, they were added onto a string. At the end of the code, the program would write over a file and put that final string in containing all the possible combinations.
The program is working fine, however there are 3.1 billion computations carried out over the course of this simulation and from some testing, I found my computer to be averaging 3000 computations per second. This means that the total simulation time is about 12 days and 5 hours. I don't have this time whatsoever, so I had spent all morning simplifying the equation to be tested for, removing unnecessary code and this was my final result.
Is this method I have done using the nested for loops the most optimal method here? If it is, are there any other ways I can speed this up, if not, can you tell me another way?
P.S. I am using Lua because it's the language I am the most familiar with, but if you have other suggestions/examples, use it in your language and I can try optimise it for this program.
I don't speak lua, but here are a few suggestions:
Before starting the loop on b, compute and store 1.15^a-1; maybe call it fooa.
Likewise, before starting the loop on c, compute fooa+(20/3)*(1.15^b-1); maybe call it foob.
Do similar things before starting each loop.
If foob, for instance, is at least 10000, break out of the loop; the stuff inside
can only make the result bigger.
This might be useless or worse in lua, but do you really need to accumulate the result in a string? I don't know how lua represents strings and does concatenation, but the concatenation might be hurting you badly. Try using a list or array data structure instead.
I'd also add that the nested loops are a perfectly sensible solution and, with the above modifications, exactly what I would do.
I would recommend a static language for brute-forcing things of this nature. I had a problem (this one) that I was having trouble with using python but the C++ brute force 8-for-loop approach computes the solution in 30 seconds.
Since you also asked for solutions in different languages, here is a quick and dirty program in C++, also incorporating the suggestions by #tmyklebu.
#include <iostream>
#include <fstream>
#include <cmath>
int main()
{
std::ofstream os( "listOfCombinations.txt" );
using std::pow;
for( double a = 0; a <= 65; ++a ) {
double aa = (pow(1.15, a) - 1);
if ( aa > 10000 ) break;
for( double b = 0; b <= 52; ++b ) {
double bb = aa + (20/3) * (pow(1.15, b) - 1);
if ( bb > 10000 ) break;
for( double c = 0; c <= 40; ++c ) {
double cc = bb + (100/3) * (pow(1.15, c) - 1);
if ( cc > 10000 ) break;
// The following line provides some visual feedback for the
// user about the progress (it prints current a, b, and c
// values).
std::cout << a << " " << b << " " << c << std::endl;
for( double d = 0; d <= 28; ++d ) {
double dd = cc + 200 * ( pow(1.15, d) - 1);
if ( dd > 10000 ) break;
for( double e = 0; e <= 19; ++e ) {
double ee = dd + (2000/3) * (pow(1.15, e) - 1);
if ( ee > 10000 ) break;
for( double f = 0; f <= 11; ++f ) {
double ff = ee + (8000/3) * (pow(1.15, f) - 1);
if ( ff > 10000 ) break;
for( double g = 0; g <= 4; ++g ) {
double gg = ff + (40000/3) * (pow(1.15, g) - 1);
if ( gg >= 10000 ) break;
os << a << ", " << b << ", "
<< c << ", " << d << ", "
<< e << ", " << f << ", "
<< g << "\n";
}
}
}
}
}
}
}
return 0;
}
local res={}
combinationsstring = "List of Combinations"
--for a = 0, 65 do
a=0
for b = 0, 52 do
for c = 0, 40 do
for d = 0, 28 do
for e = 0, 19 do
for f = 0, 11 do
for g = 0, 4 do
if (((1.15^a)-1)+((20/3)*((1.15^b)-1))
+((100/3)*((1.15^c)-1))+(200*((1.15^d)-1))
+((2000/3)*((1.15^e)-1))+((8000/3)*((1.15^f)-1))
+((40000/3)*((1.15^g)-1))) < 10000 then
res[#res+1]={a,b,c,d,e,f,g}
end
end
end
end
end
end
end
--end
runs in 30s on my machine and fills around 1 gb of memory. You can't put 66 times that in the 32 bit Lua VM, and in 64 bit LuaVM still the array part of tables is limited to 32 bit integer keys.
I've commented the outermost loop, so you'll need around 30s*66=33min. I'd write that to 66 different files perhaps. The results are held in a table first, which can then be concatenated. Check out:
local res={
{1,2,3,4,5,6,7},
{8,9,10,11,12,13,14}
}
for k,v in ipairs(res) do
-- either concatenate each line and produce a huge string
res[k]=table.concat(v,", ")
-- or write each line to a file in this loop
end
local text=table.concat(res,"\n")
print(text)
printing
1, 2, 3, 4, 5, 6, 7
8, 9, 10, 11, 12, 13, 14

Octave Parallel Code Example

Can anyone provide an example octave code to submit to the cluster assuming the parallel package for octave is installed in the cluster? What I am saying, do I just use parfor as in Matlab parallel computing toolbox, or use something like the code below?
n = 100000000;
s = 0;
% Initialize MPI
MPI_Init;
% Create MPI communicator
comm= MPI_COMM_WORLD;
% Get size and rank
size = MPI_Comm_size(comm);
rank= MPI_Comm_rank(comm);
master = 0;
% Split the for loop into size partitions
m = n / size;
r = mod(n, m);
if ( rank == size-1 )
se = (rank + 1)*m + r;
else
se = (rank + 1)*m;
end
% Each process works on a partition of the loop independently
s1 = s;
for i=(rank * m)+1:se
s1 = s1 + i;
end
% print the partial summation on each process
disp(['Partial summation: ', num2str(s1), ' on process ', num2str(rank)]);
This code is from a tutorial in the link
http://faculty.cs.tamu.edu/wuxf/talks/IAMCS-ParallelProgramming-2013-3.pdf
for matlab with mpi.
Thanks a lot!

Resources