i found this snippet of code on stack and i wanted to try it out on my machine but it keeps giving me an error of
Main method not found in class Main, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
can anyone help me figure out what to do?
This is the portion of the code i wanted to try on my machine
public static void main(String[] args) {
}
public int parse(String input) {
Scanner scanner = new Scanner(input);
return consumeLine(scanner);
}
public int consumeLine(Scanner scanner) {
if( scanner.hasNext("(") ) {
return consumeExpression(scanner);
} else if( scanner.hasNext("IF") ) {
return consumeIf(scanner);
}
return 0;
}
public int consumeExpression(Scanner scanner) {
scanner.next("(");
int a = scanner.nextInt();
int b = scanner.nextInt();
String op = scanner.next("[+-/*]");
scanner.next(")");
if( "+".equals(op) ) {
return a + b;
} else if( "-".equals(op) ) {
return a - b;
}
throw new RuntimeException("parsing error");
}
public int consumeIf(Scanner scanner) {
scanner.next("IF");
int exp1 = consumeExpression(scanner);
int exp2 = consumeExpression(scanner);
int exp3 = consumeExpression(scanner);
int exp4 = consumeExpression(scanner);
if( exp1 < 0 ) {
return exp2;
} else if( exp1 == 0 ) {
return exp3;
}
throw new RuntimeException("should not be here (TM)");
}
Try this.
public int parse(String input) {
Scanner scanner = new Scanner(input);
return consumeLine(scanner);
}
public int consumeLine(Scanner scanner) {
if( scanner.hasNext("\\(") ) {
return consumeExpression(scanner);
} else if( scanner.hasNext("IF") ) {
return consumeIf(scanner);
}
return 0;
}
public int consumeExpression(Scanner scanner) {
scanner.next("\\(");
int a = scanner.nextInt();
int b = scanner.nextInt();
String op = scanner.next("[+-/*]");
scanner.next("\\)");
if( "+".equals(op) ) {
return a + b;
} else if( "-".equals(op) ) {
return a - b;
}
throw new RuntimeException("parsing error");
}
public int consumeIf(Scanner scanner) {
scanner.next("IF");
int exp1 = consumeExpression(scanner);
int exp2 = consumeExpression(scanner);
int exp3 = consumeExpression(scanner);
int exp4 = consumeExpression(scanner);
if( exp1 < 0 ) {
return exp2;
} else if( exp1 == 0 ) {
return exp3;
}
throw new RuntimeException("should not be here (TM)");
}
sample output
System.out.println(parse(" IF ( 0 0 - ) ( 1 1 + ) ( 2 2 + ) ( 3 3 + )"));
// -> 4
Related
I have a program grabbing a password from the user, then it checks if the conditions are met or not then outputs "Valid Password" or "Invalid Password". This works, and I was able to turn the verification aspect into a method in the same program and it works, but I want to make it into a class where I can just say if( validate(pw) == true ) ... or at least if( v.getValidation() == true ) ... in any program and it will test my conditions. I've used custom classes before but for some reason everything I try does not work on this one, I've been at it for days.
Here's my method:
public boolean validate( String pw )
{
boolean l = false, u = false, lo = false, d = false, r = true;
if( pw.length() >= 6 )
{ l = true; }
for( int i = 0; i < pw.length(); i++ )
{
if( Character.isUpperCase( pw.charAt(i) ) )
{ u = true; }
if( Character.isLowerCase( pw.charAt(i) ) )
{ lo = true; }
if( Character.isDigit( pw.charAt(i) ) )
{ d = true; }
}
if( l == false || u == false || lo == false || d == false )
{ r = false; }
return r;
}
Edit:
Thank you all for your input, this is what it came out to in the end:
public class Password
{
public static boolean validate( String pw )
{
boolean result = false;
int upper = 0, lower = 0, digit = 0;
if( pw.length() >= 6 )
{
for( int i = 0; i < pw.length(); i++ )
{
if( Character.isUpperCase( pw.charAt(i) ) )
{ upper++; }
if( Character.isLowerCase( pw.charAt(i) ) )
{ lower++; }
if( Character.isDigit( pw.charAt(i) ) )
{ digit++; }
}
}
if( upper >= 1 && lower >= 1 && digit >= 1 )
{ result = true; }
return result;
}
}
You do not need to make a whole class for this. You can do something like:
public static void main(String[] args) {
boolean valid = validate("PassWord22");
}
public static boolean validate( String pw ) {}
Also some notes on your method:
You don't need to do l == true or l == false in your if statement. You can simply do:
if( !l || !u || !lo || !d )
{ r = false; }
In fact you can just return
return l && u && lo && d;
If the length is not 6 or greater, simply return false. This will save checking all the letters in the String
I would come up with better variable names. Single/two letter variable names makes it very hard to tell what they represent, and easy to mix up. (instead of l you could have length and instead of u you could have upper)
Also this can be easier solved with regex and String.matches():
public static boolean validate(String pw) {
String pattern = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).+$";
return (pw.length() > 5 && pw.matches(pattern));
}
I got it working, turned out to be an error in the code that the compiler was not picking up. I wanted to delete the question but they wont let me for some reason. So in case you're curious this is what my class looks like functioning:
public class Password
{
private String pw;
public Password()
{
pw = "";
}
public Password( String pw )
{
this.pw = pw;
}
public boolean getPassword( String pw )
{
boolean l = false, u = false, lo = false, d = false, r = true;
if( pw.length() >= 6 )
{ l = true; }
for( int i = 0; i < pw.length(); i++ )
{
if( Character.isUpperCase( pw.charAt(i) ) )
{ u = true; }
if( Character.isLowerCase( pw.charAt(i) ) )
{ lo = true; }
if( Character.isDigit( pw.charAt(i) ) )
{ d = true; }
}
if( l == false || u == false || lo == false || d == false )
{ r = false; }
return r;
}
I'm trying to implement KMP algorithm. My algorithm works correctly with the following example
Text: 121121
Pattern: 121
Result: 1,4
But when Text is 12121 and pattern is the same as above, result just: 1. I don't know if this is the problem of the algorithm or of my implementation?
Other example:
Text: 1111111111
Pattern: 111
Result: 1,4,7
My code is:
public class KMP {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String text = reader.readLine();
String pattern = reader.readLine();
search(text,pattern);
}
private static void search(String text,String pattern)
{
int[] Pi = Pi(pattern);
for (int i = 0,q=0; i <text.length()&&q<pattern.length() ; i++,q++) {
while (q>=0 && pattern.charAt(q)!=text.charAt(i))
{
q=Pi[q];
}
if(q==pattern.length()-1) {
System.out.println(i-pattern.length()+2);
q=Pi[q];
}
}
}
private static int[] Pi(String p) {
int[] Pi = new int[p.length()];
Pi[0]=-1;
int i=0;
int j=-1;
while (i<p.length()-1) {
while (j>=0 && p.charAt(j)!=p.charAt(i))
{
j=Pi[j];
}
i++;
j++;
if(p.charAt(j)==p.charAt(i)) Pi[i]=Pi[j];
else Pi[i]=j;
}
return Pi;
}
}
Hope help you.
public int strStr(String source, String target) {
if (source == null || target == null){
return -1;
}
if (source.isEmpty() && !target.isEmpty()){
return -1;
}
if (source.isEmpty() && target.isEmpty()){
return 0;
}
if (target.isEmpty()){
return 0;
}
int index = 0;
int compare_index = 0;
int compare_start_index = 0;
int compare_same_length = 0;
List<Integer> answers = new ArrayList<Integer>();
while (true){
if (compare_same_length ==0){
compare_start_index = compare_index;
}
if (source.charAt(compare_index) == target.charAt(index)){
compare_same_length++;
index++;
} else {
if (compare_same_length >0){
compare_index--;
}
compare_same_length = 0;
index = 0;
}
compare_index++;
if (compare_same_length == target.length()){
answers.add(compare_start_index+1);
compare_same_length=0;
index=0;
}
if (compare_index == source.length()){
//here are answers
for (int i = 0; i < answers.size(); i++) {
int value = answers.get(i);
}
return 1;
}
}
}
Here's my code below. I'm new to java. The line in my test is getting an error. The line
x = Response.char At(0); is expecting an identifier?
import java.util.Scanner;
public class CircularQueue {
private int head, tail;
private String [ ] q = new String [ 10 ];
private String name;
int Size;
Scanner input = new Scanner (System.in);
public CircularQueue () {
head = -1;
tail = -1;
}
public void insertQueue () {
if (isQueueFull () )
System.out.println ("Overflow");
else {
name = getName ();
if (isQueueEmpty () )
head = +1;
if (tail==Size-1)
tail=-1;
q [++ tail] = name;
}
}
public void deleteQueue() {
String x;
if ( isQueueEmpty () )
System.out.println("Underflow");
else {
x=q[head];
System.out.println ("Servicing " + x);
if (head==tail) {
head=-1;
tail=-1;
}
else {
head ++;
if (head==Size)
head=0;
}
}
}
public void setSize(int i)
{
Size=i;
}
private String getName () {
System.out.println("Enter name");
return input.nextLine ();
}
public boolean isQueueEmpty () {
return (head==-1);
}
public boolean isQueueFull () {
return ((tail-head+1==0) || (tail-head+1==Size));
}
public void printQueueLogical () {
int next;
if (isQueueEmpty())
System.out.println ("Empty");
else {
next=head;
System.out.println (" q [" + next + "] = " +q[next]);
while (next != tail) {
next ++;
if (next==Size)
next=0;
System.out.println (" q [" + next + "] = " +q[next]);
}
}
}
public void printQueuePhysical () {
for (int J=0; J<Size; J++)
System.out.println (" q [" + J + "]= " + q [J]);
}
}
class TestCircularQueue2 {
public static void main ( String [] args) {
CircularQueue n = new CircularQueue ();
Scanner in = new Scanner (System.in);
String Response;
char x;
System.out.println("Enter command - i/d/l/p/q");
Response = in.next ();
x = Response.char At(0);
x = character.toLowerCase (x);
while (x != 'q' && x != 'Q') {
switch (x) {
case 'i':
n.insertQueue ();
break;
case 'd':
n.deleteQueue();
break;
case 'l':
n.printQueueLogical();
break;
case 'y':
n.printQueuePhysical();
break;
default:
System.out.println ("Illegal Response");
break;
}
System.out.println ("enter command - i/d/l/p/q");
Response = in.next ();
x = Response.char At(0);
x = character.toLowerCase (x);
}
}
}
The method is charAt() not char At(), so you should change the lines
x = Response.char At(0);
to
x = Response.charAt(0);
Also, note that the class is Character not character, so you should use:
Character.toLowerCase(x)
Note: Try to follow Java naming conventions. Use names like someVar for variables/methods and use names like SomeClass for classes.
My code is given below. the problem is that whatever value (0 or 1) I enter in player[xxx].takenSquare[row][col]=true; (where the xxx is ) the method does not set it correctly and as a result the drawSquare method always returns " O " even if the player 1 has taken the square..
static boolean [][]takenSquare= new boolean [3][3];
int [][]playerTable; //gia tin niki
static tictac[] player = {
new tictac( "PlayerName1" ),
new tictac( "PlayerName2" ),
};
static private int row; //<---
static private int col; //""
private static int activePlayer;
public tictac(String name){
this.name=name;
playerTable=new int[3][3];
}
public static boolean isValidMove(int row,int col){
boolean valid=false;
if( ( row >= 0 && row<3 ) && ( col >=0 &&col < 3 ) ) {
if ( takenSquare[ row ][ col ] == false ) {
valid = true;
}
}
return valid;
} //isValidmove
public static void setMove (int nrow, int ncol,int active){
col=ncol-1;
row=nrow-1;
/* StringTokenizer tokenizer=new StringTokenizer(move);
this.row= Integer.parseInt(tokenizer.nextToken());
this.col= Integer.parseInt(tokenizer.nextToken()); */
if (isValidMove(row,col)){
player[xxx].takenSquare[row][col]=true;
player[xxx].playerTable[row][col]=table[row][col];
}
}
public static String drawTable(){
if ( ( row >= 0 && row<3 ) && ( col >=0 &&col < 3 ) ){
String a="";
a+=(drawSquare(0,0)+"|");
a+=(drawSquare(0,1)+"|");
a+=(drawSquare(0,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(1,0)+"|";
a+=drawSquare(1,1)+"|";
a+=(drawSquare(1,2)+'\n');
a+=("-----------")+'\n';
a+=drawSquare(2,0)+"|";
a+=drawSquare(2,1)+"|";
a+=(drawSquare(2,2));
return a;
} else return "error";
}
public static String drawSquare(int x,int y){
if (player[0].isTaken(x,y)) {
return " O ";
} else if (player[1].isTaken(x,y)) return " X ";
else return " ";
}
public boolean isTaken(int x,int y) {
return takenSquare[x][y];
}
player[0].takenSquare[row][col] is the same as player[1].takenSquare[row][col] and the same as ClassName.takenSquare[row][col] where 'player' are objects of class ClassName.
The way you reference a static field is allowed, but it is not what you intend to do with it! Both of your players share that resource, that's why it will be the same for whatever player! Please redo your code, and make sure that you don't use static for non-shared resources to avoid this problem.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i am making a Chutes Ladder program and needed another way to determine if the Cell is a empty space beside the 3 spaces i am using. Is there any other way to determine the Cell is empty beside if the cell have 3 spaces.
Cell.java:
public class Cell {
String text;
int number;
public Cell() {}
public Cell( String r ) {
text = r;
}
public Cell( int m, String r ) {
text = r;
number = m;
}
public String getText() {
return text;
}
public void setText( String x ) {
text = x;
}
public int getNumber() {
return number;
}
public void setText( int x ) {
number = x;
}
public boolean isLadder() {
return (text.equals( "L" ));
}
public boolean isChute() {
return (text.equals( "C" ));
}
public boolean isEmpty() {
return text.equals( " " );
}
public String toString() {
String s = "";
if ( isChute() )
s = s + text + Math.abs( number );
else if ( isLadder() )
s = s + text + number;
else if ( isEmpty() )
s = s + " ";
return s;
}
}
ChutesAndLadders.java
public class ChutesAndLadders {
Cell[] board;
Random ran = new Random();
public ChutesAndLadders() {}
public ChutesAndLadders( int numChutes, int numLadders ) {
board = new Cell[100];
for ( int i = 0; i < board.length; i++ ) {
board[i] = new Cell( " " );
}
chutes( numChutes );
ladders( numLadders );
}
public void setBoard( Cell[] board ) {
this.board = board;
}
public Cell[] getBoard() {
return board;
}
public void makeChutes( int x ) {
for ( int i = 0; i < x; i++ ) {
int temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( -10, "C" );
else
i--;
}
}
public void makeLadders( int y ) {
for ( int i = 0; i < y; i++ ) {
int temp = ran.nextInt( board.length );
if ( temp < 10 )
temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( 10, "L" );
else
i--;
}
}
public void chutes( int x ) {
for ( int i = 0; i < x; i++ ) {
int temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( -10, "C" );
else
i--;
}
}
public void ladders( int y ) {
for ( int i = 0; i < y; i++ ) {
int temp = ran.nextInt( board.length );
if ( temp < 10 )
temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( 10, "L" );
else
i--;
}
}
public int addToMove( String a ) {
if ( a.equals( "C10" ) ) {
int n = Integer.parseInt( a.substring( 1 ) );
return n;
}
if ( a.equals( "L10" ) ) {
int n = Integer.parseInt( a.substring( 1 ) );
return n * -1;
}
else
return 0;
}
public void printBoard() {
int counter = 0;
for ( int i = 0; i < board.length; i++ ) {
counter++;
System.out.print( "|" + board[i] );
if ( counter == 10 ) {
System.out.print( "|" + "\n" );
counter = 0;
}
}
}
}
test.java:
public class test {
public static void main( String[] args ) {
ChutesAndLadders cl = new ChutesAndLadders( 10, 10 );
cl.makeChutes( 5 );
cl.makeLadders( 5 );
int chutes = 0, ladders = 0;
for ( Cell cell : cl.getBoard() ) {
if ( cell.isLadder() )
ladders++;
else if ( cell.isChute() )
chutes++;
}
System.out.println( "Board has " + chutes + " chutes and " + ladders + " ladders" );
cl.printBoard();
}
}
public boolean isEmpty() {
return !(isLadder() && isChute());
}