Sunday, July 6, 2008

[News] My Latest Java

I wrote my first Java program today.
Besides the fact that it's Java, it rocks.

package vk_root;

import java.io.InputStreamReader;
import java.io.BufferedReader;

/*
* This program can find the root of any positive real integer
* at any given (positive real) base.
* It's my first Java program, so please don't laugh at the lameness
* of the code.
*
* raise will *raise* an integer to a given power.
* root will return 0 on failure.
* disp is there because typing out System.out.println() sucks.
* pass makes me (a Python-er) feel at home here.
* stupid is helpful.
* shell interacts with the user.
* main is straight-forward.
*
* This program is command-line aware, e.g;
* $ java -jar vk_java_app.jar 16 2
* 4
* $
*
* I have to stick this in;
* #!/usr/bin/env python
* def root(num, base):
for x in range(2, num/base+1):
if x**base == num:
return x
* >>> root(16, 2)
* 4
*
* *sigh*
*/

public class Main {
public static int raise (int num, int base) {
int copy = num;
for (int pos=1; pos!=base; pos++) {
num = copy*num;
}
return num;
}
public static int root (int num, int base) {
int cap = num/base+1;
int[] range = new int[cap];
for (int start=0; start<=(num/base); start++) {
range[start] = start;
}
for (int pos=0; pos
if (raise(range[pos], base) == num) {
return range[pos];
}
}
return 0;
}
public static void disp(int msg) {
System.out.println(msg);
}
public static int pass() {
return 0;
}
public static void stupid() {
System.out.println("Stop being a dummy.");
}
public static int shell() {
InputStreamReader isr = new InputStreamReader( System.in );
BufferedReader stdin = new BufferedReader( isr );
try {
System.out.println("Enter a number: ");
String in_num = stdin.readLine();
if (in_num.equals("exit")) {
return 1;
}
System.out.println("Enter a base: ");
String in_base = stdin.readLine();
if (in_base.equals("exit")) {
return 1;
}
System.out.println("The root:");
disp(root(Integer.parseInt(in_num), Integer.parseInt(in_base)));
}
catch (java.io.IOException e) {
stupid();
return 0;
}
catch (java.lang.NumberFormatException e) {
stupid();
return 0;
}
catch (java.lang.NegativeArraySizeException e) {
stupid();
return 0;
}
return 0;
}
public static void main(String[] args) {
/*
disp(root(16, 2));
disp(root(49, 2));
disp(root(1000, 3));
disp(root(16,4));
disp(root(625, 5));
*/
try {
disp(root(Integer.parseInt(args[0]), Integer.parseInt(args[1])));
if (args[2].equals("quiet")) {
// UGLY!!!
System.exit(0);
}
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// System.out.println(e);
pass();
}
System.out.println("(Type exit at any time to stop the application.)");
for (;;) {
if (shell() != 0) {
break;
}
}
}
}

2 comments:

Anonymous said...

Good for people to know.

tehD3M0L1$H3® said...

you died?