Creating a Lexer that implements Iterator<Lexeme> - java

I'm new to programming and I have an assignment that asks us to make a Lexer that implements Iterator (in java). We are given Strings of equations with variable white spaces and we have to produce Lexemes for a variety of types. This is what I have so far but when I run it, I get an OutOfMemoryError: Java heap space. I have no idea what is causing this error or if I am even on the right track with my code. Any suggestions?
Thanks
public enum LexemeType {
LEFT_PAREN, RIGHT_PAREN, OPERATOR, NUMBER, VARIABLE, EQUALS, SEMICOLON, USER_INPUT;
}
import java.io.*;
import java.util.*;
public class Lexer implements Iterator<Lexeme> {
Lexeme token = null; // last token recognized
boolean eof = false; // reached end of file
private Reader reader = null; // input stream
private int lookahead = 0; // lookahead, if any
private int[] buffer = new int[100]; // lexeme buffer
private int index = 0; // length of lexeme
public Lexer(String toLex) {
this.reader = new StringReader(toLex);
}
// Extract lexeme from buffer
public String getLexeme() {
return new String(buffer,0,index);
}
// Reset state to begin new token
private void reset() throws IOException {
if (eof)
throw new IllegalStateException();
index = 0;
token = null;
if (lookahead==0)
read();
}
// Read one more char.
// Add previous char, if any, to the buffer.
private void read() throws IOException {
if (eof)
throw new IllegalStateException();
if (lookahead != 0) {
buffer[index] = lookahead;
index++;
}
lookahead = reader.read();
}
// Recognize a token
public void lex() throws IOException {
reset();
// Skip whitespace
while (Character.isWhitespace(lookahead)) {
read();
}
reset();
// Recognize (
if (lookahead == '(') {
token = new Lexeme(LexemeType.LEFT_PAREN, "(");
read();
return;
}
// Recognize )
if (lookahead == ')') {
token = new Lexeme(LexemeType.RIGHT_PAREN, "(");
read();
return;
}
// Recognize ;
if (lookahead == ';') {
token = new Lexeme(LexemeType.SEMICOLON, ";");
read();
return;
}
// Recognize =
if (lookahead == '=') {
token = new Lexeme(LexemeType.EQUALS, "=");
read();
return;
}
// Recognize ?
if (lookahead == '?') {
token = new Lexeme(LexemeType.USER_INPUT, "?");
read();
return;
}
// Recognize float
if (Character.isDigit(lookahead)) {
do {
read();
} while (Character.isDigit(lookahead));
if (lookahead=='.') {
read();
while (Character.isDigit(lookahead))
read();
}
token = new Lexeme(LexemeType.NUMBER, ("-?[0-9]+"));
return;
}
// Recognize string
if (lookahead=='"') {
do {
read();
} while (lookahead!='"');
read();
token = new Lexeme(LexemeType.VARIABLE, ("^[a-zA-Z]*$"));
return;
}
}
#Override
public boolean hasNext() {
if (token!=null)
return true;
if (eof)
return false;
try {
lex();
} catch (IOException e) {
}
return true;
}
#Override
public Lexeme next() {
if (hasNext()) {
Lexeme result = token;
token = null;
return result;
}
else
throw new IllegalStateException();
}
}

Related

Get() method returns the right value the first time while the second time returns null

I am using a hash-map to store key value pairs. When I use the get method to retrieve an Identifier object key called "Ape", it correctly returns the Set object value "1,2,3,4" yet when I try to retrieve the same object the value returns "".
I have already tried making sure I wasn't somehow removing the value key pairs and checking if I am creating a new hashmap every time. When I print out the hashmap to string method, the Identifier object "Ape" is not longer in the map along with it's value.
Sorry for the large amounts of code! I wasn't sure whether to add it all or not.
package nl.vu.labs.phoenix.ap;
import java.math.BigInteger;
import java.util.*;
import java.util.regex.Pattern;
import java.io.*;
/**
* A set interpreter for sets of elements of type T
*/
public class Interpreter<T extends SetInterface<BigInteger>> implements InterpreterInterface<T> {
HashMap<IdentifierInterface, T> hm = new HashMap<IdentifierInterface, T>();
#Override
public T getMemory(String v) {
IdentifierInterface i = new Identifier();
i.appendIdentifier(v);
if(hm.containsKey(i)){
return hm.get(i);
}else{
return null;
}
}
#Override
public T eval(String s) {
System.out.println("HASHMAP:"+hm.toString());
Scanner in;
try {
in = format(s);
} catch (APException e1) {
in=new Scanner(s);
}
in.useDelimiter("");
try {
readStatement(in);
}
catch(Exception e) {
return null;
}
return null;
}
char nextChar(Scanner in) {
return in.next().charAt(0);
}
boolean nextCharIs(Scanner in, char c) {
boolean IsMatch = in.hasNext(Pattern.quote(c+""));
return IsMatch;
}
boolean nextCharIsDigit (Scanner in) {
return in.hasNext("[0-9]");
}
boolean nextCharIsLetter (Scanner in) {
return in.hasNext("[a-zA-Z]");
}
void eraseSpace(Scanner in) {
while (nextCharIs(in, ' ')) {
nextChar(in);
}
}
private void checkChar (String in, char a) throws APException {
Scanner token = new Scanner(in);
if (! nextCharIs(token, a)) {
throw new APException("Missing token: " + a);
}
}
private String SetToString(SetInterface<BigInteger> set){
StringBuilder output = new StringBuilder();
if(set.first()){
output.append(set.get());
while(set.next()){
output.append(" ");
output.append(set.get());
}
}
return output.toString();
}
private Scanner format(String statement) throws APException {
Scanner in = new Scanner(statement);
in.useDelimiter("");
StringBuilder line = new StringBuilder();
while (in.hasNext()) {
if (nextCharIs(in, '/')) {
line.append(in.nextLine());
return new Scanner(line.toString());
} else if (nextCharIsLetter(in) || nextCharIsDigit(in)) {
line.append(in.next());
while (nextCharIs(in, ' ')) {
checkChar(in.next(), ' ');
if (nextCharIsLetter(in) || nextCharIsDigit(in)) {
throw new APException("Identifier error: spaces inside identifier not allowed");
}
}
} else if (nextCharIs(in, ' ')) {
checkChar(in.next(), ' ');
} else {
line.append(in.next());
}
}
String formated = line.toString();
for (int i = 0; i < formated.length(); i++) {
if (formated.charAt(i) == ',') {
try {
if (!Character.isDigit(formated.charAt(i - 1)) || !Character.isDigit(formated.charAt(i + 1))) {
throw new APException("no number in set");
}
} catch (Exception e) {
throw new APException("no number in set");
}
} else if (formated.charAt(i) == '0') {
if (!Character.isDigit(formated.charAt(i - 1)) && Character.isDigit(formated.charAt(i + 1))) {
throw new APException("Invalid number");
}
}
}
return new Scanner(line.toString());
}
void readStatement(Scanner in)throws APException{
if (nextCharIsLetter(in)) {
readAssignment(in);
} else if (nextCharIs(in, '?')) {
readPrint_statement(in);
} else if (! nextCharIs(in, '/')){
throw new APException("Invalid statement, please read the documentation");
}
}
void readAssignment(Scanner in) throws APException{
//handle end of line
in.useDelimiter("=");
IdentifierInterface i;
SetInterface<BigInteger> set;
i=readIdentifier(in);
set = readExpression(new Scanner(in.next()));
this.hm.put(i,(T)set);
}
void readPrint_statement(Scanner in)throws APException{
in.useDelimiter("");
if(nextCharIs(in,'(')||nextCharIs(in,'{')||nextCharIsLetter(in)||nextCharIsDigit(in)){
readExpression(in);
}else if (! nextCharIs(in, ';')){
throw new APException("Invalid statement, please read the documentation");
}
}
IdentifierInterface readIdentifier(Scanner in)throws APException{
IdentifierInterface i = new Identifier();
String ident="";
if(in.hasNext()) {
ident+=in.next();
}
System.out.println("readident:"+ident);
i.appendIdentifier(ident);
if(i.hasCorrectIdentifierFormat(i.toString())){
return i;
}else{
throw new APException("Invalid Identifier foramt");
}
}
SetInterface<BigInteger> readExpression(Scanner in)throws APException{
in.useDelimiter("");
SetInterface<BigInteger> term = null;
StringBuilder terms = new StringBuilder();
while (in.hasNext()) {
while(nextCharIs(in, ' ')) {
in.next();
}
//System.out.println("HRE:"+in.next());
if (nextCharIs(in, '+') || nextCharIs(in, '-') || nextCharIs(in, '|')) {
String addOp = in.next();
if (term == null) {
term = readTerm(new Scanner(terms.toString()));
}
terms.setLength(0);
while (in.hasNext()) {
if ((nextCharIs(in, '+') || nextCharIs(in, '-') || nextCharIs(in, '|'))) {
term = addOps(term, readTerm(new Scanner(terms.toString())), addOp);
terms.setLength(0);
break;
} else {
terms.append(in.next());
}
}
if (terms != null) {
term = addOps(term, readTerm(new Scanner(terms.toString())), addOp);
}
} else {
terms.append(in.next());
}
}
if (term == null) {
term = readTerm(new Scanner(terms.toString()));
}
return term;
}
SetInterface<BigInteger> addOps(SetInterface<BigInteger> set1, SetInterface<BigInteger> set2, String op){
System.out.print("addops");
SetInterface<BigInteger> set = new Set<>();
if(op=="+"){
set = set1.union(set2);
}else if(op=="-"){
set = set1.difference(set2);
}else{
set = set1.symmetricDifference(set2);
}
return set;
}
SetInterface<BigInteger> readTerm(Scanner in)throws APException{
in.useDelimiter("");
SetInterface<BigInteger> factor;
StringBuilder factors = new StringBuilder();
while (in.hasNext()) {
if (nextCharIs(in, '*')) {
checkChar(in.next(), '*');
factor = readFactor(new Scanner(factors.toString())).intersection(readTerm(new Scanner(in.nextLine())));
return factor;
} else {
factors.append(in.next());
}
}
factor = readFactor(new Scanner(factors.toString()));
return factor;
}
SetInterface<BigInteger> readFactor(Scanner in)throws APException{
in.useDelimiter("");
SetInterface<BigInteger> resultset = new Set<>();
int complexFactors = 0;
StringBuilder sets = new StringBuilder();
while(in.hasNext()) {
if(nextCharIs(in,' ')){
in.next();
}
if (nextCharIs(in, '(')) {
checkChar(in.next(), '(');
complexFactors += 1;
while (in.hasNext() && complexFactors != 0) {
if (nextCharIs(in, '(')) {
complexFactors += 1;
sets.append(in.next());
} else if (nextCharIs(in, ')')) {
complexFactors -= 1;
sets.append(in.next());
if (complexFactors == 0) {
if (nextCharIs(in,')')) {
throw new APException("Invalid token detected");
}
} else {
if(!in.hasNext()&&complexFactors!=0){
throw new APException("Invalid token detected");
}
else{
sets.append(in.next());
}
}
}else {
sets.append(in.next());
}
}
resultset = readExpression(new Scanner(sets.toString()));
} else if (nextCharIsLetter(in)) {
sets.append(in.next());
while (nextCharIsLetter(in)|| nextCharIsDigit(in)) {
sets.append(in.next());
}
IdentifierInterface i = new Identifier();
i.appendIdentifier(sets.toString());
if (hm.containsKey(i)) {
resultset = hm.get(i);
return resultset;
} else {
throw new APException("Identifier \\\""+ sets.toString() +"\\\" does not correspond to a sets");
}
}
if (nextCharIs(in,'{')) {
checkChar(in.next(), '{');
if (nextCharIs(in,',')) {
throw new APException("no number");
}
while (!nextCharIs(in,'}') && in.hasNext()) {
sets.append(in.next());
}
if (in.hasNext()) {
checkChar(in.next(), '}');
} else {
throw new APException("Invalid token");
}
if (in.hasNext()) {
throw new APException("Operator or end of line missing");
}
resultset = readSet(sets.toString());
} else {
throw new APException("Invalid statement detected");
}
}
if (complexFactors != 0) {
throw new APException("Missing parenthesis detected");
}
return resultset;
}
SetInterface<BigInteger> readSet(String nums)throws APException{
SetInterface<BigInteger> set = new Set<>();
Scanner in = new Scanner(nums);
in.useDelimiter(",");
while (in.hasNext()) {
try {
set.add(in.nextBigInteger());
} catch (Exception e) {
throw new APException("Invalid number detected in a set");
}
}
in.close();
//set.fixDoubles();
return set;
}
}
public void parenthesisBalanceTests() {
InterpreterInterface<Set<BigInteger>> interpreter = new Interpreter<Set<BigInteger>>();
interpreter.eval("Ape = {1, 2, 3, 4, 5, 6, 7, 8, 9}");
// missing closing parenthesis test
interpreter.eval("Ape = (({1, 2, 3})");
SetInterface<BigInteger> actual = interpreter.getMemory("Ape");
System.out.print("ACTRUAL:"+actual);
ArrayList<BigInteger> expected = convertExpectedList("1 2 3 4 5 6 7 8 9");
assertTrue("missing closing parenthesis' should result in an exception", compareSets(actual, expected));
// missing opening parenthesis test
interpreter.eval("Ape = ({1, 2, 3}))");
actual = interpreter.getMemory("Ape");
assertTrue("missing opening parenthesis' should result in an exception", compareSets(actual, expected));
}
These are the tests I am supposed to pass in parenthesisBalcenceTest(). Missing closing parenthesis test passes because actual returns "1 2 3 4 5 6 7 8 9", but missing opening parenthesis fails because actual is "".

How to discard unwanted tokens

I made this token iterator class that scans an input line by each character and creates Strings. I am able to make the class read all the tokens and separate them, but I cannot get it to remove all the invalid/unwanted tokens in an input.
I tried doing something with character.toString(counter) so those characters are made into a string and then wrote if statements that when the token is not "not", "true" , "false" or "and" then discard it and go on to the next token.
import java.util.Iterator;
public class Tokiter implements Iterator<String>{
private char counter = 0;
//input line to be tokenized
private String line;
// the next Token, null if no next Token
private String nextToken;
// implement
public TokIter(String line){
this.line = line;
}
#Override
// implement
public boolean hasNext() {
if (counter >= line.length())
return false;
else if (line.charAt(counter) == ' ')
{
counter++;
return hasNext();
}
else
return true;
}
#Override
//implement
public String next() {
String s = "";
if (!hasNext())
{
// System.out.println("Null");
return null;
}
else if( line.charAt(counter) == ('('))
{
// System.out.println("Token");
s += line.charAt(counter);
counter++;
return s;
}
else if( line.charAt(counter) == (')'))
{
// System.out.println("Token");
s += line.charAt(counter);
counter++;
return s;
}
else
s += line.charAt(counter);
counter++;
if (counter >= line.length()){
return s;
}
while (Character.isLetter(line.charAt(counter)))
{
s += line.charAt(counter);
counter++;
if (counter >= line.length()){
return s;
}
}
return s;
}
#Override
public void remove() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
// provided
public static void main(String[] args){
String line;
// you can play with other inputs on the command line
if(args.length>0)
line = args[0];
// or do the standard test
else
line = " not random (true or false) ** whatever ";
System.out.println("line: [" + line + "]");
Tokiter tokIt = new Tokiter(line);
while(tokIt.hasNext()){
System.out.println("next token: [" + tokIt.next() + "]");
}
}
}
So for example when the program runs the input line not random (true or false) ** whatever the output will be:
line: [ not random (true or false) ** whatever ]
next token: [not]
next token: [(]
next token: [true]
next token: [or]
next token: [false]
next token: [)]

Comparing stack pop and queue dequeue in Java (palindromes)

Full disclosure: this is for an assignment, so please don't post actual code solutions!
I have an assignment that requires me to take a string from the user and pass it into a stack and a queue, then use those two to compare the chars to determine if the string is a palindrome. I have the program written, but there appears to be some logic error somewhere. Here's the relevant code:
public static void main(String[] args) {
UserInterface ui = new UserInterface();
Stack stack = new Stack();
Queue queue = new Queue();
String cleaned = new String();
boolean palindrome = true;
ui.setString("Please give me a palindrome.");
cleaned = ui.cleanString(ui.getString());
for (int i = 0; i < cleaned.length(); ++i) {
stack.push(cleaned.charAt(i));
queue.enqueue(cleaned.charAt(i));
}
while (!stack.isEmpty() && !queue.isEmpty()) {
if (stack.pop() != queue.dequeue()) {
palindrome = false;
}
}
if (palindrome) {
System.out.printf("%s is a palindrome!", ui.getString());
} else
System.out.printf("%s is not a palindrome :(", ui.getString());
stack.dump();
queue.clear();
}
public class Stack {
public void push(char c) {
c = Character.toUpperCase(c);
Node oldNode = header;
header = new Node();
header.setData(c);
header.setNext(oldNode);
}
public char pop() {
Node temp = new Node();
char data;
if (isEmpty()) {
System.out.printf("Stack Underflow (pop)\n");
System.exit(0);
}
temp = header;
data = temp.getData();
header = header.getNext();
return data;
}
}
public class Queue {
public void enqueue(char c) {
c = Character.toUpperCase(c);
Node n = last;
last = new Node();
last.setData(c);
last.setNext(null);
if (isEmpty()) {
first = last;
} else n.setNext(last);
}
public char dequeue() {
char data;
data = first.getData();
first = first.getNext();
return data;
}
}
public String cleanString(String s) {
return s.replaceAll("[^A-Za-z0-9]", "");
}
Basically, when running my code through the debugger in Eclipse, my pop and dequeue methods appear to only select certain alphanumerics. I am using replaceAll("[^A-Za-z0-9]", "") to "clean" the user's string of any nonalphanumeric chars (!, ?, &, etc.). When I say it only selects certain chars, there doesn't seem to be any pattern that I can discern. Any ideas?
Your general algorithm works properly, assuming your queue and stack are correct (i tried this using the Deque implementations found in the jdk). Since your assignment involves the datastructures, i've pretty much just took your main logic and replaced the datastructures with ArrayDequeue, so I don't feel like i'm answering this for you.
String word = "ooffoo";
word = word.replaceAll("[^A-Za-z0-9]", "");
Deque<Character> stack = new ArrayDeque<Character>(word.length());
Deque<Character> queue = new ArrayDeque<Character>(word.length());
for (char c : word.toCharArray()) {
stack.push(c);
queue.add(c);
}
boolean pal = true;
while (! stack.isEmpty() && pal == true) {
if (! stack.pop().equals(queue.remove())) {
pal = false;
}
}
System.out.println(pal);
I'd recommend using a debugger to see exactly what was being compared, or at the very least spit out some print lines:
while (!stack.isEmpty() && !queue.isEmpty()) {
Character sc = stack.pop();
Character qc = queue.dequeue();
System.out.println(sc + ":" + qc);
if (sc != qc) {
palindrome = false;
}
}

Populating a binary search tree with a text file

I'm trying to fill in a binary search tree with a text file, but i'm having alot of trouble implementing my insert function. Am i reading the input correctly or is it my code?
Code for reading file:
import java.io.*;
import java.util.Scanner;
public class Driver {
public static void main(String[]args) throws IOException
{
//Checks if there is a correct number of arguments passed through the command line.
if (args.length != 1)
{
quitError("Tree command word arguments expected");
}
String inputFile = args[0];
BST btree = new BST();
try
{
BufferedReader input = new BufferedReader(new FileReader(inputFile));
//Scans each word from the input and prints it out
String word = input.readLine();
while (word != null)
{
btree.insert(word);
word = input.readLine();
}
return;
} catch(FileNotFoundException filenotfoundexception) //Catches file not found exception
{
System.out.println("File not found.");
}
catch(IOException ioexception) //Catches input/output exception
{
System.out.println("File input error occured!");
}
}
//Displays an error message, program exits
public static void quitError(String msg)
{
System.out.println(msg);
System.out.println("Program will now quit.");
System.exit(0);
}
}
Code for the binary search tree node:
public class BSTNode {
protected String data;
protected BSTNode left, right;
public BSTNode()
{
left = null;
right = null;
}
public BSTNode(String data)
{
this(data,null,null);
}
public BSTNode(String data, BSTNode lt, BSTNode rt)
{
this.data = data;
left = lt;
right = rt;
}
}
Code for the binary search tree:
public class BST {
protected BSTNode root = null;
public BST(){}
public void clear()
{
root = null;
}
public boolean isEmpty()
{
return root == null;
}
public void insert(String data)
{
BSTNode p = root, prev = null;
while (p != null) {
prev = p;
if (p.data.compareTo(data) < 0)
p = p.right;
else p = p.left;
}
if (root == null)
root = new BSTNode(data);
else if (prev.data.compareTo(data) < 0)
prev.right = new BSTNode(data);
else prev.left = new BSTNode(data);
}
public void inorder()
{
inorder(root);
}
private void inorder(BSTNode p)
{
if (p != null)
{
inorder(p.left);
System.out.print(p.data + " ");
inorder(p.right);
}
}
public void breadthFirst()
{
BSTNode p = root;
Queue queue = new Queue();
if (p != null)
{
queue.enqueue(p);
while (!queue.isEmpty())
{
p = (BSTNode) queue.dequeue();
System.out.print(p.data + " ");
if (p.left != null)
queue.enqueue(p.left);
if (p.right != null)
queue.enqueue(p.right);
}
}
}
}
Unless the file has one word per line, you're going to have trouble. The buffered reader is giving you the entire line. Is it a word or a sentence?
Your insert() method is empty. Nothing will happen without that. Put some code into it and you may have better luck.
So it seems to me you have two problems:
Your input is incorrect unless it's one word per line. If each line is a sentence, you'll have to tokenize it into words.
Your insert method does nothing. No wonder your tree isn't working.
Replace this code
String word = input.readLine();
with
String word = input.read();
This should work

Can someone post a program template for submitting a solution in Java in Codeforces programming competitions?

Yes I want to start programming competitions so I dont know how to submit in Java?
Answers very apreciated
bye
i have been in a lot of contests:
/** #team=civilian */
import java.io.*;
import java.math.*;
import java.util.*;
public class _template {
static BufferedReader input;
static StringTokenizer _stk;
static String readln() throws IOException {
String l = input.readLine();
if (l != null)
_stk = new StringTokenizer(l, " ");
return l;
}
static String next() {
return _stk.nextToken();
}
static int nextInt() {
return Integer.parseInt(next());
}
static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static PrintWriter output = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
input = new BufferedReader(new InputStreamReader(System.in));
// input = new BufferedReader(new FileReader("_template"));
// output.print("ja");
// output.close();// Be sure to close the output at the end
//or maybe he does not print everything.
}
}
Some think is best to compite in c++:
//
#include <bits/stdc++.h>
#define D(x) cout << #x << " = " << (x) << endl;
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define FOREACH(it,v) for(__typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it)
#define ALL(v) (v).begin(), (v).end()
using namespace std;
typedef long long int64;
const int INF = (int)(1e9);
const int64 INFLL = (int64)(1e18);
const double EPS = 1e-13;
int main() {
#ifdef LOCAL
freopen(".in.txt", "r", stdin);
freopen(".out.txt", "w", stdout);
#else
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#endif
}
and this help when you are practicing:
#createfiles.sh
function createfiles {
cp path/_template.cpp ./"$1.cpp";
touch "$1.in.txt";
touch "$1.out.txt";
sed "s/.in.txt/$1.in.txt/" < "$1.cpp" > "tmp";
sed "s/.out.txt/$1.out.txt/" < "tmp" > "$1.cpp" ;
rm tmp;
}
createfiles $1
runing test:
#compile_cpp.sh
function compile_cpp {
g++ -o "${1::-4}_exe" -DLOCAL "$1";
./"${1::-4}_exe";
}
compile_cpp $1
and you run it like this:
$ bash createfiles.sh uva12520
# you program an awesome solution
# and you test it
$ bash compile_ccp.sh uva12520.cpp
i think is best to create an alias in your .bash like
alias compile_cpp_maraton='function fun() { bash /path/my_commands/compile_cpp_maraton.sh "$1"; }; fun'
Sorry for the long post.
Here is a template mentioned in FlatFoot Codeforces user blog http://codeforces.com/blog/entry/7018
public class Main{
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
// Start writing your solution here. -------------------------------------
/*
int n = sc.nextInt(); // read input as integer
long k = sc.nextLong(); // read input as long
double d = sc.nextDouble(); // read input as double
String str = sc.next(); // read input as String
String s = sc.nextLine(); // read whole line as String
int result = 3*n;
out.println(result); // print via PrintWriter
*/
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
I do not know about CF but you can try this at SPOJ. Have a look at examples here
Have a look at it,you might find your answer here :
http://rgpv.ac.in/Campus/CodeForce%20Tutorial.pdf
Java syntax :
import java.util.*;
public class Prime {
public static void main(String args[]) {
int i;
Scanner in = new Scanner(System.in);
i = in.nextInt();
/* Take input from standard input */
if (isprime(i)) {
System.out.println("YES");
/*
* Print outp ut on standard output
*/
} else {
System.out.println("NO");
/* Print output on standard output */
}
}
public static boolean isprime(int a) {
for (int i = 2; i < a; i++) {
if (a % i == 0)
return false;
}
return true;
}
}
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
/**
* Author: o_panda_o
* Email: emailofpanda#yahoo.com
*/
public class Main{
static class ProblemSolver{
public void solveTheProblem(InputReader in,OutputWriter out){
/**
* This template is used by many coders for fast IO
*
* This portion acts as the main method we use. Everything we need to code...
* ...can be written here without even touching the main method.
*
* Following are the examples for IO and for more information have a look...
* ...on the classes InputReader(for Fast Input) and OutputWriter(for Fast...
* ...Output). The methods there are self explanatory
*/
/**
* How to take inputs:
* - Taking input is just nearly similar to the way we take input using scanner in Java.
* - e.g. int n=in.nextInt(); long n=in.nextLong();
*/
/**
* How to print output:
* - It is just like we use PrintWriter. Instead of using System.out, we can...
* ...only use out in that place.
* - e.g. out.print(), out.println() etc.
*/
}
//You can add necessary methods here also. Uncomment the code and test it above
//public int add(int a,int b){
// return a+b;
//}
}
//Everything below you see is a template for every code. You don't need to change them most of the time.
//As you go on coding, in the time of need you will realise what you need to change when. Just trust me on this.
public static void main(String[] args){
InputStream inputStream=System.in;
OutputStream outputStream=System.out;
InputReader in=new InputReader(inputStream);
OutputWriter out=new OutputWriter(outputStream);
ProblemSolver problemSolver=new ProblemSolver();
problemSolver.solveTheProblem(in,out);
out.flush();
out.close();
}
}
class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n){
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextSortedIntArray(int n){
int array[]=nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n){
int[] array=new int[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextLongArray(int n){
long[] array=new long[n];
for(int i=0;i<n;++i)array[i]=nextLong();
return array;
}
public long[] nextSumLongArray(int n){
long[] array=new long[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextSortedLongArray(int n){
long array[]=nextLongArray(n);
Arrays.sort(array);
return array;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(char[] array) {
writer.print(array);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(double[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void println(int[] array) {
print(array);
writer.println();
}
public void println(double[] array) {
print(array);
writer.println();
}
public void println(long[] array) {
print(array);
writer.println();
}
public void println() {
writer.println();
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void println(char i) {
writer.println(i);
}
public void println(char[] array) {
writer.println(array);
}
public void printf(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void println(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void println(int i) {
writer.println(i);
}
public void separateLines(int[] array) {
for (int i : array) {
println(i);
}
}
}

Categories