Execute Brain****/Java: Difference between revisions

m
Fixed syntax highlighting.
m (Missed a space)
m (Fixed syntax highlighting.)
 
(18 intermediate revisions by 6 users not shown)
Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}
In this implementation of [[Brainf***]] in [[Java]], the code is read in all at once and checked for uneven brackets (unequal amounts of [ and ] commands). If that error occurs, the code will obviously not be run. Under the hood, the program memory is an ArrayList of Integers which expands only to the right. So, if the pointer moves past zero to the left, the program will exit. Due to the BufferedReader input class, return characters (ASCII 10 and 13) are ignored on input (the , command).
 
Under the hood, the program memory is an <tt>ArrayList</tt> of Integers which expands "infinitely" (limited by your system's memory) to the right (still [http://en.wikipedia.org/wiki/Turing_completeness Turing complete]). So, if the pointer moves past zero to the left, the program will exit and a "Pointer out of range" error message will be displayed.
import java.io.BufferedReader;
 
import java.io.FileNotFoundException;
Due to the <tt>BufferedReader</tt> input class, return characters ([http://www.asciitable.com ASCII] 10 and 13) are ignored on input (the , command), but are not ignored on output (the . command). In order to input anything, you'll need to append a new line.
import java.io.FileReader;
 
import java.io.IOException;
Loops are handled in the <tt>jumpForward</tt> and <tt>jumpBack</tt> methods. In each method, the bracket that the code pointer is on is counted as 1 (the counter is initialized to 1). The method then moves the code pointer forward or back and counts other brackets along the way. If it finds a bracket of the same type, 1 is added to the counter; if it finds a bracket of the other type, 1 is subtracted from the counter. The search continues until the counter reaches 0. For jumping forward, the code pointer must be allowed to skip the ending bracket, or else it will jump back on the next execution iteration. For jumping back, the pointer can remain at the starting bracket. So, <tt>jumpBack</tt> offsets the next code pointer increment to make sure the check for 0 happens.
import java.io.InputStreamReader;
 
import java.util.ArrayList;
More detailed information about the rest of the code can be found in the comments throughout it.<br clear=all>
{{works with|Java|1.5+}}
/**
<syntaxhighlight lang="java5">import java.io.BufferedReader;
* Interprets Brainf**k source from std in or a file.
import java.io.FileNotFoundException;
*
import java.io.FileReader;
* @author Mike Neurohr
import java.io.IOException;
*/
import java.io.InputStreamReader;
public class BF{
import java.util.ArrayList;
private static int pointer;//memory pointer
 
private static int codeIndex;//instruction number
/**
private static final int INITIAL_SIZE= 1000;//initial size of memory
* Interprets Brainf**k source from std in or a file.
private static final String instChars= "[]<>,.+-";//valid code characters
*
* @author Mike Neurohr
/**
*/
* The main program. Holds the input loop and error-handling.
public class BF{
*
private static int pointer;//memory pointer
* @param args 0: Source file others: ignored
private static int codeIndex;//instruction number
*/
private static final int INITIAL_SIZE= 1000;//initial size of memory
public static void main(String[] args){
private static final String instChars= "[]<>,.+-";//valid code characters
BufferedReader source;
 
try{
/**
if(args.length == 0){//if no file specified
* The main program. Holds the input loop and error-handling.
source= new BufferedReader(new InputStreamReader(System.in));
*
}else{
* @param args 0: Source file others: ignored
source= new BufferedReader(new FileReader(args[0]));
*/
}
public static void main(String[] args){
char instruction;
BufferedReader source;
StringBuilder code= new StringBuilder();
try{
if(args.length == 0){//if no file specified
//counts for loop syntax errors
source= new BufferedReader(new InputStreamReader(System.in));
int bCnt= 0;
}else{
source= new BufferedReader(new FileReader(args[0]));
//read whole source in
}
for(instruction= (char)source.read(); source.ready(); instruction=
(char)source.read()){ instruction;
 
//remove extra characters
//holds the cleaned up code
if(instChars.contains(instruction + "")){
StringBuilder code= new StringBuilder();
//add the instruction to the clean code
 
code.append(instruction);
//count for loop syntax errors
if(instruction == '[') bCnt++;
int bCnt= 0;
if(instruction == ']') bCnt--;
 
}
//read whole source in
}
for(instruction= (char)source.read(); source.ready(); instruction=
if(bCnt != 0){//if there is a bracket with no match
(char)source.read()){
System.err.println("Error: Uneven brackets.");
//remove extra characters
return;
if(instChars.contains(instruction + "")){
}
//add the instruction to the clean code
code.append(instruction);
//set up input for ,
if(instruction == '[') bCnt++;
BufferedReader input=
if(instruction == ']') bCnt--;
new BufferedReader(new InputStreamReader(System.in));
}
//set up memory
}
ArrayList<Integer> memory= new ArrayList<Integer>(INITIAL_SIZE);
if(bCnt != 0){//if there is a bracket with no match
memory.add(new Integer(0));
System.err.println("Error: Uneven brackets.");
return;
pointer= 0; //initialize pointer
}
//loop through the cleaned up code and execute
 
for(codeIndex= 0;codeIndex < code.length();codeIndex++){
//set up input for ,
instruction= code.charAt(codeIndex);
BufferedReader input=
switch(instruction){
new BufferedReader(new InputStreamReader(System.in));
case '+':
memory.//set(pointer, up memory.get(pointer) + 1);
ArrayList<Integer> memory= new ArrayList<Integer>(INITIAL_SIZE);
break;
memory.add(new Integer(0));
case '-':
memory.set(pointer, memory.get(pointer) - 1);
pointer= 0; //initialize pointer
break;
//loop through the cleaned up code and execute
case '.':
for(codeIndex= 0;codeIndex < code.length();codeIndex++){
System.out.print((char)memory.get(pointer).intValue());
instruction= code.charAt(codeIndex);
//no errors possible here
switch(instruction){
break;
case ',+':
input(memory.set(pointer, inputmemory.get(pointer) + 1);
break;
//no errors possible here
break;case '-':
memory.set(pointer, memory.get(pointer) - 1);
case '[':
break;
if(memory.get(pointer) == 0){
case '.':
//skip the code inside the loop
System.out.print((char)memory.get(pointer).intValue());
jumpForward(code);
}break;
case ',':
//if the loop can continue...
input(memory, input);
//we don't need to check other things
break;
case '][':
if(memory.get(pointer) == 0){
//go back to the corresponding [ to check
jumpBack( //skip the code); inside the loop
break jumpForward(code);
case '>': }
//if the loop can continue...
pointer++;
//we don't need to check other things
while(pointer + 1 > memory.size()) memory.add(0);
break;
case '<]':
if(memory.get(pointer) =!= 0){
//go back to the corresponding [ to check
System.err.println("Pointer out of range (negative).");
returnjumpBack(code);
}
//if the loop should stop...
pointer--;
//we don't need to check other things
break;
default: break;
}case '>':
pointer++;
}
//gets rid of NullPointerExceptions
}catch(FileNotFoundException e){
while(pointer + 1 > memory.size()) memory.add(0);
System.err.println("Error opening file.");
break;
}catch(IOException e){
case '<':
System.err.println("Error on input.");
if(--pointer < 0){
}
//can't do it
}
System.err.println("Pointer out of range (negative).");
return;
public static void jumpBack(StringBuilder code){
}
//read back with pointer
default:
//count brackets until the corresponding [
//No other characters left after the cleaning
int bracketCnt= 1;
}
while(codeIndex >= 0 && bracketCnt != 0){
}
codeIndex--;
}catch(FileNotFoundException e){
char inst= code.charAt(codeIndex);
System.err.println("Error opening file: " + args[0] + ".");
if(inst == '[') bracketCnt--;
}catch(IOException e){
if(inst == ']') bracketCnt++;
System.err.println("Error on input.");
}
}
//"- 1" to offset the next "codeIndex++".
}
codeIndex= codeIndex - 1;
 
}
public static void jumpBack(StringBuilder code){
//initial count for the bracket we're on
public static void jumpForward(StringBuilder code){
int bracketCnt= 1;
//read back with code pointer
//count brackets until the corresponding ][
intwhile(codeIndex >= 0 && bracketCnt != 1;0){
codeIndex--;
while(codeIndex < code.length() && bracketCnt != 0){
char inst= code.charAt(codeIndex++);
char if(inst == code.charAt(codeIndex'[') bracketCnt--;
if(inst == ']') bracketCnt--++;
}
if(inst == '[') bracketCnt++;
//"- 1" to offset the next "codeIndex++".
}
codeIndex= codeIndex - 1;
}
}
 
public static void input(ArrayList<Integer> mem, BufferedReader input)
public static void jumpForward(StringBuilder code){
throws IOException{
//initial count for the bracket we're on
int val;
int bracketCnt= 1;
//read until something comes in other than return chars
//count brackets until the corresponding ]
for(val= input.read(); val == 10 || val == 13; val= input.read());
while(codeIndex < code.length() && bracketCnt != 0){
mem.set(pointer, new Integer(val));
codeIndex++;
char inst= code.charAt(codeIndex);
if(inst == ']') bracketCnt--;
if(inst == '[') bracketCnt++;
}
}
 
public static void input(ArrayList<Integer> mem, BufferedReader input)
throws IOException{
int val;
//read until something comes in other than return chars
for(val= input.read(); val == 10 || val == 13; val= input.read());
mem.set(pointer, new Integer(val));
}
}</syntaxhighlight>
}
9,476

edits