Search Results

Search found 461 results on 19 pages for 'parseint'.

Page 8/19 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Socket Programming : Inputstream Stuck in loop - read() always return 0

    - by Atom Skaa ska Hic
    Server side code public static boolean sendFile() { int start = Integer.parseInt(startAndEnd[0]) - 1; int end = Integer.parseInt(startAndEnd[1]) - 1; int size = (end - start) + 1; try { bos = new BufferedOutputStream(initSocket.getOutputStream()); bos.write(byteArr,start,size); bos.flush(); bos.close(); initSocket.close(); System.out.println("Send file to : " + initSocket); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); disconnected(); return false; } return true; } Client Side public boolean receiveFile() { int current = 0; try { int bytesRead = bis.read(byteArr,0,byteArr.length); System.out.println("Receive file from : " + client); current = bytesRead; do { bytesRead = bis.read(byteArr, current, (byteArr.length-current)); if(bytesRead >= 0) current += bytesRead; } while(bytesRead != -1); bis.close(); bos.write(byteArr, 0 , current); bos.flush(); bos.close(); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); disconnected(); return false; } return true; } Client side is multithreading,server side not use multithreading. I just paste some code that made problem if you want see all code please tell me. After I debug the code, I found that if I set max thread to any and then the first thread always stuck in this loop. That bis.read(....) always return 0. Although, server had close stream and it not get out of the loop. I don't know why ... But another threads are work correctly. do { bytesRead = bis.read(byteArr, current, (byteArr.length-current)); if(bytesRead >= 0) current += bytesRead; } while(bytesRead != -1);

    Read the article

  • JavaScript Coding for Finding Shipping Total

    - by user2913279
    I am having a very hard time with this code. I have been working on it for days and cannot seem to figure it out. Please help!! Here are the specific I need for the code: Many companies normally charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box. Here is the code I have: <!DOCTYPE> <head> <title>Calculate Shipping</title> <script type="text/javascript"> function parseInt() { var salesPrice = document.salesForm.Price.value; var minCharge = salesPrice + 1.50; var shipping = salesPrice * 10/100; if (salesPrice <= 25) window.alert('Your sales total including shipping is $' + minCharge); else window.alert('Your sales total including shipping is $' + salesPrice + shipping); } </script> </head> <body> <form name="salesForm"> <div > <p>Enter Your Purchase Price</p> <input type="text" name="Price" /><br /><br /> <input type="button" name="Calculate" value="Calculate Shipping" onclick="parseInt ()" /> </div> </form> </body> </html> Everything works except for the math in the alert box. It will show an incorrect total...

    Read the article

  • Problem displaying contents of a class in Java

    - by LuckySlevin
    My problem is i have a class and in it there is a list of elements of another class. public class Branch { private ArrayList<Player> players = new ArrayList<Player>(); String brName; public Branch() {} public void setBr(String brName){this.brName = brName;} public String getBr(){return brName;} public ArrayList<Player> getPlayers() { return players; } public void setPlayers(ArrayList<Player> players) { this.players =new ArrayList<Player>(players); } } public class Player { private String name; private String pos; private Integer salary; private Integer number; public Player(String name, String pos, Integer salary, Integer number) { this.name = name; this.pos = pos; this.salary = salary; this.number = number; } public Player(){} public String getName() { return name; } public String getPos() { return pos; } public Integer getSalary() { return salary; } public Integer getNumber() { return number; } public void setName(String name) { this.name = name; } public void setPos(String pos) { this.pos = pos; } public void setSalary(Integer salary) { this.salary = salary; } public void setNumber(Integer number) { this.number = number; } } My problem is to print the players of a Branch with their name,pos,salary,number. For this i tried this simply : String p1,p2; int a1,a2; p1 = input.readLine(); p2 = input.readLine(); a1 = Integer.parseInt(input.readLine()); a2 = Integer.parseInt(input.readLine()); players[0].setName(p1); players[0].setPos(p2); players[0].setSalary(a1); players[0].setNumber(a2); ptmp.add(players[0]); myBranch[0].setPlayers(ptmp); System.out.println(myBranch[0].brName + " " + myBranch[0].getPlayers()); I wrote this just to try how to display. I created an array of Players, and Branches so they already defined. The problem is getPlayers() doesn't give me any result. What is the way to do this?

    Read the article

  • Tips on how to refactor this unwieldy upvote/downvote code

    - by bob_cobb
    Basically this code is for an upvote/downvote system and I'm basically Incrementing the count by 1 when voting up Decrementing the count by 1 when voting down If the number of downvotes upvotes, we'll assume it's a negative score, so the count stays 0 Reverting the count back to what it originally was when clicking upvote twice or downvote twice Never go below 0 (by showing negative numbers); Basically it's the same scoring scheme reddit uses, and I tried to get some ideas from the source which was minified and kind of hard to grok: a.fn.vote = function(b, c, e, j) { if (reddit.logged && a(this).hasClass("arrow")) { var k = a(this).hasClass("up") ? 1 : a(this).hasClass("down") ? -1 : 0, v = a(this).all_things_by_id(), p = v.children().not(".child").find(".arrow"), q = k == 1 ? "up" : "upmod"; p.filter("." + q).removeClass(q).addClass(k == 1 ? "upmod" : "up"); q = k == -1 ? "down" : "downmod"; p.filter("." + q).removeClass(q).addClass(k == -1 ? "downmod" : "down"); reddit.logged && (v.each(function() { var b = a(this).find(".entry:first, .midcol:first"); k > 0 ? b.addClass("likes").removeClass("dislikes unvoted") : k < 0 ? b.addClass("dislikes").removeClass("likes unvoted") : b.addClass("unvoted").removeClass("likes dislikes") }), a.defined(j) || (j = v.filter(":first").thing_id(), b += e ? "" : "-" + j, a.request("vote", {id: j,dir: k,vh: b}))); c && c(v, k) } }; I'm trying to look for a pattern, but there are a bunch of edge cases that I've been adding in, and it's still a little off. My code (and fiddle): $(function() { var down = $('.vote-down'); var up = $('.vote-up'); var direction = up.add(down); var largeCount = $('#js-large-count'); var totalUp = $('#js-total-up'); var totalDown = $('#js-total-down'); var totalUpCount = parseInt(totalUp.text(), 10); var totalDownCount = parseInt(totalDown.text(), 10); var castVote = function(submissionId, voteType) { /* var postURL = '/vote'; $.post(postURL, { submissionId : submissionId, voteType : voteType } , function (data){ if (data.response === 'success') { totalDown.text(data.downvotes); totalUp.text(data.upvotes); } }, 'json'); */ alert('voted!'); }; $(direction).on('click', direction, function () { // The submission ID var $that = $(this), submissionId = $that.attr('id'), voteType = $that.attr('dir'), // what direction was voted? [up or down] isDown = $that.hasClass('down'), isUp = $that.hasClass('up'), curVotes = parseInt($that.parent().find('div.count').text(), 10); // current vote castVote(submissionId, voteType); // Voted up on submission if (voteType === 'up') { var alreadyVotedUp = $that.hasClass('likes'), upCount = $that.next('div.count'), dislikes = $that.nextAll('a').first(); // next anchor attr if (alreadyVotedUp) { // Clicked the up arrow and previously voted up $that.toggleClass('likes up'); if (totalUpCount > totalDownCount) { upCount.text(curVotes - 1); largeCount.text(curVotes - 1); } else { upCount.text(0); largeCount.text(0); } upCount.css('color', '#555').hide().fadeIn(); largeCount.hide().fadeIn(); } else if (dislikes.hasClass('dislikes')) { // Voted down now are voting up if (totalDownCount > totalUpCount) { upCount.text(0); largeCount.text(0); } else if (totalUpCount > totalDownCount) { console.log(totalDownCount); console.log(totalUpCount); if (totalDownCount === 0) { upCount.text(curVotes + 1); largeCount.text(curVotes + 1); } else { upCount.text(curVotes + 2); largeCount.text(curVotes + 2); } } else { upCount.text(curVotes + 1); largeCount.text(curVotes + 1); } dislikes.toggleClass('down dislikes'); upCount.css('color', '#296394').hide().fadeIn(200); largeCount.hide().fadeIn(); } else { if (totalDownCount > totalUpCount) { upCount.text(0); largeCount.text(0); } else { // They clicked the up arrow and haven't voted up yet upCount.text(curVotes + 1); largeCount.text(curVotes + 1).hide().fadeIn(200); upCount.css('color', '#296394').hide().fadeIn(200); } } // Change arrow to dark blue if (isUp) { $that.toggleClass('up likes'); } } // Voted down on submission if (voteType === 'down') { var alreadyVotedDown = $that.hasClass('dislikes'), downCount = $that.prev('div.count'); // Get previous anchor attribute var likes = $that.prevAll('a').first(); if (alreadyVotedDown) { if (curVotes === 0) { if (totalDownCount > totalUp) { downCount.text(curVotes); largeCount.text(curVotes); } else { if (totalUpCount < totalDownCount || totalUpCount == totalDownCount) { downCount.text(0); largeCount.text(0); } else { downCount.text((totalUpCount - totalUpCount) + 1); largeCount.text((totalUpCount - totalUpCount) + 1); } } } else { downCount.text(curVotes + 1); largeCount.text(curVotes + 1); } $that.toggleClass('down dislikes'); downCount.css('color', '#555').hide().fadeIn(200); largeCount.hide().fadeIn(); } else if (likes.hasClass('likes')) { // They voted up from 0, and now are voting down if (curVotes <= 1) { downCount.text(0); largeCount.text(0); } else { // They voted up, now they are voting down (from a number > 0) downCount.text(curVotes - 2); largeCount.text(curVotes - 2); } likes.toggleClass('up likes'); downCount.css('color', '#ba2a2a').hide().fadeIn(200); largeCount.hide().fadeIn(200); } else { if (curVotes > 0) { downCount.text(curVotes - 1); largeCount.text(curVotes - 1); } else { downCount.text(curVotes); largeCount.text(curVotes); } downCount.css('color', '#ba2a2a').hide().fadeIn(200); largeCount.hide().fadeIn(200); } // Change the arrow to red if (isDown) { $that.toggleClass('down dislikes'); } } return false; }); });? Pretty convoluted, right? Is there a way to do something similar but in about 1/3 of the code I've written? After attempting to re-write it, I find myself doing the same thing so I just gave up halfway through and decided to ask for some help (fiddle of most recent).

    Read the article

  • Accessing variables in other classes (Java)

    - by George
    Why doesn't the following program return 0, since I am accessing p from a new A(), which has not had main called on it? public class A { public int p = 0; public static void main(String[] args) { p = Integer.parseInt(args[0]); new B().go(); } } class B { public void go() { System.out.println(new A().p); } }

    Read the article

  • Android: NullPointerException error in getting data in database

    - by Gil Viernes Marcelo
    This what happens in the system. 1. Admin login this is in other activity but i will not post it coz it has nothing to do with this (no problem) 2. Register user in system (using database no problem) 3. Click add user button (where existing user who register must display its name in ListView) Problem: When I click adduser to see if the system registered the user, it force close. CurrentUser.java package com.example.istronggyminstructor; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.example.istronggyminstructor.registeredUserList.Users; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; public class CurrentUsers extends Activity { private Button register; private Button adduser; EditText getusertext, getpass, getweight, textdisp; View popupview, popupview2; public static ArrayList<String> ArrayofName = new ArrayList<String>(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_current_users); register = (Button) findViewById(R.id.regbut); adduser = (Button) findViewById(R.id.addbut); register.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { LayoutInflater inflator = (LayoutInflater) getBaseContext() .getSystemService(LAYOUT_INFLATER_SERVICE); popupview = inflator.inflate(R.layout.popup, null); final PopupWindow popupWindow = new PopupWindow(popupview, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); popupWindow.showAtLocation(popupview, Gravity.CENTER, 0, 0); popupWindow.setFocusable(true); popupWindow.update(); Button dismissbtn = (Button) popupview.findViewById(R.id.close); dismissbtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { popupWindow.dismiss(); } }); popupWindow.showAsDropDown(register, 50, -30); } }); //Thread.setDefaultUncaughtExceptionHandler(new forceclose(this)); } public void registerUser(View v) { EditText username = (EditText) popupview.findViewById(R.id.usertext); EditText password = (EditText) popupview .findViewById(R.id.passwordtext); EditText weight = (EditText) popupview.findViewById(R.id.weight); String getUsername = username.getText().toString(); String getPassword = password.getText().toString(); String getWeight = weight.getText().toString(); dataHandler dbHandler = new dataHandler(this, null, null, 1); Users user = new Users(getUsername, getPassword, Integer.parseInt(getWeight)); dbHandler.addUsers(user); Toast.makeText(getApplicationContext(), "Registering...", Toast.LENGTH_SHORT).show(); } public void onClick_addUser(View v) { LayoutInflater inflator = (LayoutInflater) getBaseContext() .getSystemService(LAYOUT_INFLATER_SERVICE); popupview2 = inflator.inflate(R.layout.popup2, null); final PopupWindow popupWindow = new PopupWindow(popupview2, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); popupWindow.showAtLocation(popupview2, Gravity.CENTER, 0, -10); popupWindow.setFocusable(true); popupWindow.update(); Button dismissbtn = (Button) popupview2.findViewById(R.id.close2); dismissbtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { popupWindow.dismiss(); } }); popupWindow.showAsDropDown(register, 50, -30); dataHandler dbHandler = new dataHandler(this, null, null, 1); dbHandler.getAllUsers(); ListView list = (ListView)findViewById(R.layout.popup2); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ArrayofName); list.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.current_users, menu); return true; } } registeredUserList.java package com.example.istronggyminstructor; public class registeredUserList { public static class Users { private static int _id; private static String _users; private static String _password; private static int _weight; private static String[] _workoutlists; private static int _score; public Users() { } public Users(String username, String password, int weight) { _users = username; _password = password; _weight = weight; } public int getId() { return _id; } public static void setId(int id) { _id = id; } public String getUsers() { return _users; } public static void setUsers(String users) { _users = users; } public String getPassword(){ return _password; } public void setPassword(String password){ _password = password; } public int getWeight(){ return _weight; } public static void setWeight(int weight){ _weight = weight; } public String[] getWorkoutLists(){ return _workoutlists; } public void setWorkoutLists(String[] workoutlists){ _workoutlists = workoutlists; } public int score(){ return _score; } public void score(int score){ _score = score; } } } dataHandler.java package com.example.istronggyminstructor; import java.util.ArrayList; import java.util.List; import com.example.istronggyminstructor.registeredUserList.Users; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class dataHandler extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "userInfo.db"; public static final String TABLE_USERINFO = "user"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_USERNAME = "username"; public static final String COLUMN_PASSWORD = "password"; public static final String COLUMN_WEIGHT = "weight"; public dataHandler(Context context, String name, CursorFactory factory, int version) { super(context, DATABASE_NAME, factory, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERINFO + " (" + COLUMN_ID + " INTEGER PRIMARY KEY, " + COLUMN_USERNAME + " TEXT," + COLUMN_PASSWORD + " TEXT, " + COLUMN_WEIGHT + " INTEGER " + ");"; db.execSQL(CREATE_USER_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERINFO); onCreate(db); } public void addUsers(Users user) { ContentValues values = new ContentValues(); values.put(COLUMN_USERNAME, user.getUsers()); values.put(COLUMN_PASSWORD, user.getPassword()); values.put(COLUMN_WEIGHT, user.getWeight()); SQLiteDatabase db = this.getWritableDatabase(); db.insert(TABLE_USERINFO, null, values); db.close(); } public Users findUsers(String username) { String query = "Select * FROM " + TABLE_USERINFO + " WHERE " + COLUMN_USERNAME + " = \"" + username + "\""; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query, null); Users user = new Users(); if (cursor.moveToFirst()) { cursor.moveToFirst(); Users.setUsers(cursor.getString(1)); //Users.setWeight(Integer.parseInt(cursor.getString(3))); not yet needed cursor.close(); } else { user = null; } db.close(); return user; } public List<Users> getAllUsers(){ List<Users> user = new ArrayList(); String selectQuery = "SELECT * FROM " + TABLE_USERINFO; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { Users users = new Users(); users.setUsers(cursor.getString(1)); String name = cursor.getString(1); CurrentUsers.ArrayofName.add(name); // Adding contact to list user.add(users); } while (cursor.moveToNext()); } // return user list return user; } public boolean deleteUsers(String username) { boolean result = false; String query = "Select * FROM " + TABLE_USERINFO + " WHERE " + COLUMN_USERNAME + " = \"" + username + "\""; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query, null); Users user = new Users(); if (cursor.moveToFirst()) { Users.setId(Integer.parseInt(cursor.getString(0))); db.delete(TABLE_USERINFO, COLUMN_ID + " = ?", new String[] { String.valueOf(user.getId()) }); cursor.close(); result = true; } db.close(); return result; } } Logcat 08-20 03:23:23.293: E/AndroidRuntime(16363): FATAL EXCEPTION: main 08-20 03:23:23.293: E/AndroidRuntime(16363): java.lang.IllegalStateException: Could not execute method of the activity 08-20 03:23:23.293: E/AndroidRuntime(16363): at android.view.View$1.onClick(View.java:3599) 08-20 03:23:23.293: E/AndroidRuntime(16363): at android.view.View.performClick(View.java:4204) 08-20 03:23:23.293: E/AndroidRuntime(16363): at android.view.View$PerformClick.run(View.java:17355) 08-20 03:23:23.293: E/AndroidRuntime(16363): at android.os.Handler.handleCallback(Handler.java:725) 08-20 03:23:23.293: E/AndroidRuntime(16363): at android.os.Handler.dispatchMessage(Handler.java:92) 08-20 03:23:23.293: E/AndroidRuntime(16363): at android.os.Looper.loop(Looper.java:137) 08-20 03:23:23.293: E/AndroidRuntime(16363): at android.app.ActivityThread.main(ActivityThread.java:5041) 08-20 03:23:23.293: E/AndroidRuntime(16363): at java.lang.reflect.Method.invokeNative(Native Method) 08-20 03:23:23.293: E/AndroidRuntime(16363): at java.lang.reflect.Method.invoke(Method.java:511) 08-20 03:23:23.293: E/AndroidRuntime(16363): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 08-20 03:23:23.293: E/AndroidRuntime(16363): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 08-20 03:23:23.293: E/AndroidRuntime(16363): at dalvik.system.NativeStart.main(Native Method) 08-20 03:23:23.293: E/AndroidRuntime(16363): Caused by: java.lang.reflect.InvocationTargetException 08-20 03:23:23.293: E/AndroidRuntime(16363): at java.lang.reflect.Method.invokeNative(Native Method) 08-20 03:23:23.293: E/AndroidRuntime(16363): at java.lang.reflect.Method.invoke(Method.java:511) 08-20 03:23:23.293: E/AndroidRuntime(16363): at android.view.View$1.onClick(View.java:3594) 08-20 03:23:23.293: E/AndroidRuntime(16363): ... 11 more 08-20 03:23:23.293: E/AndroidRuntime(16363): Caused by: java.lang.NullPointerException 08-20 03:23:23.293: E/AndroidRuntime(16363): at com.example.istronggyminstructor.CurrentUsers.onClick_addUser(CurrentUsers.java:118) 08-20 03:23:23.293: E/AndroidRuntime(16363): ... 14 more

    Read the article

  • select for update problem in jdbc

    - by kartiku
    I'm having a problem with select for update in jdbc. The table i'm trying to update is the smalldb table, i'm having problems-- i'm using select for update which does a lock on the selected row the update statement is -- String updateQ = "UPDATE libra.smalldb SET hIx = ? WHERE name = ?"; the select statement is -- rs = stmt1.executeQuery("SELECT hIx FROM libra.smalldb for update"); rs0 = stmt2.executeQuery("SELECT name,aff FROM libra.smalldb"); the second statement is because i need those fields as well. Here is the complete code -- import java.sql.*; import java.util.ArrayList; import java.util.Collections; public class Jdbcexample1 { /** * @param args */ public static void main(String[] args) { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection("jdbc:mysql:///test", "root", "*****"); //String url = "jdbc:msql://200.210.220.1:1114/Demo"; //Connection conn = DriverManager.getConnection(url,"",""); Statement stmt1 = con.createStatement(); Statement stmt2 = con.createStatement(); Statement stmt3 = con.createStatement(); Statement stmt4 = con.createStatement(); ResultSet rs0; ResultSet rs; ResultSet rs1; ResultSet rs2; String name; String hIx; int hIxInt; StringBuffer sb = new StringBuffer(); String affiliationSmall; ArrayList<String> affiliation = new ArrayList<String>(); ArrayList<Float> matchValues = new ArrayList<Float>(); ArrayList<Integer> hixValues = new ArrayList<Integer>(); ArrayList<Integer> idValues = new ArrayList<Integer>(); boolean moreFlag = false; String queryString; int tmpIdx; String name1; //get the hix at that index where the similarity is maximum int tmpHidx = 0; int tmpHix = 0; int id = 0; int count; int tmpidIdx = 0; //rs = stmt.executeQuery("SELECT id FROM libra.researchint WHERE id = 910887"); // Get name, affiliation , hIx from smalldb //rs = stmt1.executeQuery("SELECT name,aff,hIx FROM libra.smalldb"); // String cursorName = "OUR_CURSOR"; // stmt1.setCursorName(cursorName); //rs = stmt1.executeQuery("SELECT name,aff,hIx FROM libra.smalldb for update"); rs = stmt1.executeQuery("SELECT hIx FROM libra.smalldb for update"); rs0 = stmt2.executeQuery("SELECT name,aff FROM libra.smalldb"); while ( rs.next() && rs0.next() ) { //String lastName = rs.getString("id"); hIx = rs.getString("hIx"); hIxInt = Integer.parseInt(hIx); //if hIx if (hIxInt==-1) continue; //name = rs.getString("name"); name = rs0.getString("name"); name1 = new String(name); System.out.println(name); //affiliationSmall = rs.getString("aff"); affiliationSmall = rs0.getString("aff"); //name = "\"" +name+ "\""; // Get matching names from large faculty table //String queryString = "SELECT id,name,hIx FROM libra.faculty WHERE name = " +name; //name = does not work names are similar but not same (in faculty and // smalldb) String query = "SELECT id,name,hIx FROM libra.faculty WHERE name like ?"; //String query = "SELECT id,name,hIx FROM libra.faculty for update of hIx WHERE name like ?"; PreparedStatement prepStmt = con.prepareStatement(query); String[] nameArr = name.split(" "); StringBuffer tmpSb = new StringBuffer(); for(int idx = 0;idx<nameArr.length;idx++) { tmpSb.append(nameArr[idx] + "%"); } name = tmpSb.toString(); prepStmt.setString(1, name); rs1 = prepStmt.executeQuery(); //Try to get matching names from faculty big db //Execute the query on faculty table //rs1 = stmt2.executeQuery(queryString); if(rs1.isClosed()) continue; count = 0; matchValues.clear(); affiliation.clear(); while(rs1.next()) { //name = rs1.getString("name"); id = Integer.parseInt(rs1.getString("id")); //idValues.add(id); tmpHix = Integer.parseInt(rs1.getString("hIx")); queryString = "SELECT aff FROM libra.affiliation WHERE id = "+id; rs2 = stmt3.executeQuery(queryString); //affiliation = rs1.getString("aff"); sb.delete(0, sb.length()); while (rs2.next()) { //Concatenate it to the same string using a stringbuffer sb.append(rs2.getString("aff")); //affiliation.add(rs2.getString("aff")); } affiliation.add(sb.toString()); count++; // if(count1) // { // moreFlag = true; // //Call fuzzy match function, store the distance values and select the // //affiliation that has the minimum distance from affiliationSmall // // //problem is here, affiliation.get Index: 2, Size: 2 // // matchValues.add(fuzzyMatch(affiliationSmall,affiliation.get(count))); // hixValues.add(tmpHix); // idValues.add(id); // } }//end of while rs1 -> faculty rs1.close(); int idx = 0; if(count>1) { moreFlag = true; //Call fuzzy match function, store the distance values and select the //affiliation that has the minimum distance from affiliationSmall //problem is here, affiliation.get Index: 2, Size: 2 matchValues.add(fuzzyMatch(affiliationSmall,affiliation.get(idx))); hixValues.add(tmpHix); idValues.add(id); idx++; } if(moreFlag) { Object obj = Collections.max(matchValues); float maxVal = Float.parseFloat(obj.toString()); //int tmpIdx = matchValues.indexOf(new Float(maxVal)); //get the index at which similarity between affiliation strings is maximum, //as returned by fuzzyMatch //int tmpIdx = matchValues.indexOf(maxVal); tmpIdx = matchValues.indexOf(maxVal); //get the hix at that index where the similarity is maximum //int tmpHidx = hixValues.get(tmpIdx); tmpHidx = hixValues.get(tmpIdx); tmpidIdx = idValues.get(tmpIdx); //update the smalldb table String updateQ = "UPDATE libra.smalldb SET hIx = ? WHERE name = ?"; //String updateQ = "UPDATE libra.smalldb SET hIx = ? WHERE current of "+cursorName; //PreparedStatement prepStmt1 = con.prepareStatement("UPDATE libra.smalldb SET hIx = ? WHERE current of "+cursorName); PreparedStatement prepStmt1 = con.prepareStatement(updateQ); //PreparedStatement prepStmt1 = con.prepareStatement(updateQ); prepStmt1.setString(2, name1); prepStmt1.setString(1, Integer.toString(tmpHidx)); prepStmt1.executeUpdate(updateQ); //prepStmt1.execute(); //stmt4.executeUpdate(updateQ); }//end of if //For matching names get the affiliation based on id from affiliation table //con.close(); //System.out.println(lastName); System.out.println(name); }//end of while rs -> smalldb rs.close(); // String updateQ = "UPDATE libra.smalldb1 SET hIx = "+Integer.toString(tmpHidx)+ "WHERE id = "+Integer.toString(tmpidIdx); // stmt4.executeUpdate(updateQ); con.close(); } catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); e.printStackTrace(); } } public static float fuzzyMatch(String affiliationSmall, String affiliation) { //float distance = 0; String[] temp = null; temp = affiliationSmall.split(" "); int index; //int index1 = affiliation.indexOf(affiliationSmall); int matchCount = 0; for (int idx = 0;idx<temp.length; idx++) { index = affiliation.indexOf(temp[idx]); if (index!=-1) { matchCount++; } } float tmpFloat = matchCount/temp.length; //int[] aff1= new int[affiliation1.length()]; //int[] aff2 = new int[affiliation2.length()]; return tmpFloat; } } i think it is because of the second select statement (rs0) Here is the error- Got an exception! You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) at com.mysql.jdbc.Util.getInstance(Util.java:384) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3562) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3494) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1960) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2114) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2690) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1648) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1567) at Jdbcexample1.main(Jdbcexample1.java:184)

    Read the article

  • Check on every page to ensure user has validated as being over 18

    - by liquilife
    Hi Guys and Girls. I'm working on a website (tobacco related) that requires all visitors to validate they are over 18 before they can view the site. I have a form in place that validates the age but I'm at a dead end. How can I use this to store a cookie that they've passed the test and do a check on all pages to see if this check has already been passed or not? Any suggestions and help would be hugely appreciated! Below is my validation form: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Validate</title> <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script> <script language="javascript"> function checkAge() { var min_age = 18; var year = parseInt(document.forms["age_form"]["year"].value); var month = parseInt(document.forms["age_form"]["month"].value) - 1; var day = parseInt(document.forms["age_form"]["day"].value); var theirDate = new Date((year + min_age), month, day); var today = new Date; if ( (today.getTime() - theirDate.getTime()) < 0) { alert("You are too young to enter this site!"); return false; } else { return true; } } </script> </head> <body> <form action="index.html" name="age_form" method="get" id="age_form"> <select name="day" id="day"> <option value="0" selected>DAY</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="month" id="month"> <option value="0" selected>MONTH</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="year" id="year"> <option value="0" selected>YEAR</option> <option value="1920">1920</option> <option value="1921">1921</option> <option value="1922">1922</option> <option value="1923">1923</option> <option value="1924">1924</option> <option value="1925">1925</option> <option value="1926">1926</option> <option value="1927">1927</option> <option value="1928">1928</option> <option value="1929">1929</option> <option value="1930">1930</option> <option value="1931">1931</option> <option value="1932">1932</option> <option value="1933">1933</option> <option value="1934">1934</option> <option value="1935">1935</option> <option value="1936">1936</option> <option value="1937">1937</option> <option value="1938">1938</option> <option value="1939">1939</option> <option value="1940">1940</option> <option value="1941">1941</option> <option value="1942">1942</option> <option value="1943">1943</option> <option value="1944">1944</option> <option value="1945">1945</option> <option value="1946">1946</option> <option value="1947">1947</option> <option value="1948">1948</option> <option value="1949">1949</option> <option value="1950">1950</option> <option value="1951">1951</option> <option value="1952">1952</option> <option value="1953">1953</option> <option value="1954">1954</option> <option value="1955">1955</option> <option value="1956">1956</option> <option value="1957">1957</option> <option value="1958">1958</option> <option value="1959">1959</option> <option value="1960">1960</option> <option value="1961">1961</option> <option value="1962">1962</option> <option value="1963">1963</option> <option value="1964">1964</option> <option value="1965">1965</option> <option value="1966">1966</option> <option value="1967">1967</option> <option value="1968">1968</option> <option value="1969">1969</option> <option value="1970">1970</option> <option value="1971">1971</option> <option value="1972">1972</option> <option value="1973">1973</option> <option value="1974">1974</option> <option value="1975">1975</option> <option value="1976">1976</option> <option value="1977">1977</option> <option value="1978">1978</option> <option value="1979">1979</option> <option value="1980">1980</option> <option value="1981">1981</option> <option value="1982">1982</option> <option value="1983">1983</option> <option value="1984">1984</option> <option value="1985">1985</option> <option value="1986">1986</option> <option value="1987">1987</option> <option value="1988">1988</option> <option value="1989">1989</option> <option value="1990">1990</option> <option value="1991">1991</option> <option value="1992">1992</option> <option value="1993">1993</option> <option value="1994">1994</option> <option value="1995">1995</option> <option value="1996">1996</option> <option value="1997">1997</option> <option value="1998">1998</option> <option value="1999">1999</option> </select> </form> </body> </html>

    Read the article

  • MapReduce

    - by kaleidoscope
    MapReduce is a programming model and an associated implementation for processing and generating large data sets. Users specify a map function that processes a key/value pair to generate a set of  intermediate key/value pairs, and a reduce function that merges all intermediate values associated with the same intermediate key. Many real world tasks are expressible in this model, as shown in the paper. Programs written in this functional style are automatically parallelized and executed on a large cluster of commodity machines. The run-time system takes care of the details of partitioning the input data,  scheduling the program's execution across a set of machines, handling machine failures, and managing the required inter-machine communication. This allows programmers without any experience with parallel and distributed systems to easily utilize the resources of a large distributed system. Example: A process to count the appearances of each different word in a set of documents void map(String name, String document):   // name: document name   // document: document contents   for each word w in document:     EmitIntermediate(w, 1); void reduce(String word, Iterator partialCounts):   // word: a word   // partialCounts: a list of aggregated partial counts   int result = 0;   for each pc in partialCounts:     result += ParseInt(pc);   Emit(result); Here, each document is split in words, and each word is counted initially with a "1" value by the Map function, using the word as the result key. The framework puts together all the pairs with the same key and feeds them to the same call to Reduce, thus this function just needs to sum all of its input values to find the total appearances of that word.   Sarang, K

    Read the article

  • Model View Control Issue: Null Pointer Initialization Question

    - by David Dimalanta
    Good morning again. This is David. Please, I need an urgent help regarding control model view where I making a code that uniquely separating into groups: An Activity Java Class to Display the Interface A View and Function Java Class for Drawing Cards and Display it on the Activity Class The problem is that the result returns a Null Pointer Exception. I have initialize for the ID for Text View and Image View. Under this class "draw_deck.java". Please help me. Here's my code for draw_deck.java: package com.bodapps.inbetween.model; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bodapps.inbetween.R; public class draw_deck extends View { public TextView count_label; public ImageView draw_card; private int count; public draw_deck(Context context) { super(context); // TODO Auto-generated constructor stub //I have initialized two widgets for ID. I still don't get it why I got forced closed by Null Pointer Exception thing. draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); } public void draw(int s, int c, String strSuit, String strValue, Pile pile, Context context) { //super(context); //Just printing the card drawn from pile int suit, value = 1; draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); Card card; if(!pile.isEmpty()) //Setting it to IF statement displays the card one by one. { card = pile.drawFromPile(); //Need to check first if card is null. if (card != null) { //draws an extra if (card != null) { //Get suit of card to print out. suit = card.getSuit(); switch (suit) { case CardInfo.DIAMOND: strSuit = "DIAMOND"; s=0; break; case CardInfo.HEART: strSuit = "HEART"; s=1; break; case CardInfo.SPADE: strSuit = "SPADE"; s=2; break; case CardInfo.CLUB: strSuit = "CLUB"; s=3; break; } //Get value of card to print out. value = card.getValue(); switch (value) { case CardInfo.ACE: strValue = "ACE"; c=0; break; case CardInfo.TWO: c=1; break; case CardInfo.THREE: strValue = "THREE"; c=2; break; case CardInfo.FOUR: strValue = "FOUR"; c=3; break; case CardInfo.FIVE: strValue = "FIVE"; c=4; break; case CardInfo.SIX: strValue = "SIX"; c=4; break; case CardInfo.SEVEN: strValue = "SEVEN"; c=4; break; case CardInfo.EIGHT: strValue = "EIGHT"; c=4; break; case CardInfo.NINE: strValue = "NINE"; c=4; break; case CardInfo.TEN: strValue = "TEN"; c=4; break; case CardInfo.JACK: strValue = "JACK"; c=4; break; case CardInfo.QUEEN: strValue = "QUEEN"; c=4; break; case CardInfo.KING: strValue = "KING"; c=4; break; } } } }// //Below two lines of code, this is where issued the Null Pointer Exception. draw_card.setImageResource(deck[s][c]); count_label.setText(new StringBuilder(strValue).append(" of ").append(strSuit).append(String.valueOf(" " + count++)).toString()); } //Choice of Suits in a Deck public Integer[][] deck = { //Array Group 1 is [0][0] (No. of Cards: 4 - DIAMOND) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 2 is [1][0] (No. of Cards: 4 - HEART) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 3 is [2][0] (No. of Cards: 4 - SPADE) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 4 is [3][0] (No. of Cards: 4 - CLUB) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, }; } And this one of the activity class, Player_Mode_2.java: package com.bodapps.inbetween; import java.util.Random; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bodapps.inbetween.model.Card; import com.bodapps.inbetween.model.Pile; import com.bodapps.inbetween.model.draw_deck; /* * * Public class for Two-Player mode. * */ public class Player_Mode_2 extends Activity { //Image Views private ImageView draw_card; private ImageView player_1; private ImageView player_2; private ImageView icon; //Buttons private Button set_deck; //Edit Texts private EditText enter_no_of_decks; //text Views private TextView count_label; //Integer Data Types private int no_of_cards, count; private int card_multiplier; //Contexts final Context context = this; //Pile Model public Pile pile; //Card Model public Card card; //create View @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.play_2_player_mode); //-----[ Search for Views ]----- //Initialize for Image View draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); player_1 = (ImageView) findViewById(R.id.IV_Player_1_Card); player_2 = (ImageView) findViewById(R.id.IV_Player_2_Card); //Initialize for Text view or Label count_label = (TextView) findViewById(R.id.Text_View_Count_Card); //-----[ Adding Values ]----- //Integer Values count = 0; no_of_cards = 0; //-----[ Adding Dialog ]----- //Initializing Dialog final Dialog deck_dialog = new Dialog(context); deck_dialog.setContentView(R.layout.dialog); deck_dialog.setTitle("Deck Dialog"); //-----[ Initializing Views for Dialog's Contents ]----- //Initialize for Edit Text enter_no_of_decks = (EditText) deck_dialog.findViewById(R.id.Edit_Text_Set_Number_of_Decks); //Initialize for Button set_deck = (Button) deck_dialog.findViewById(R.id.Button_Deck); //-----[ Setting onClickListener() ]----- //Set Event Listener for Image view draw_card.setOnClickListener(new Draw_Card_Model()); //Set Event Listener for Setting the Deck set_deck.setOnClickListener(new OnClickListener() { public void onClick(View v) { if(card_multiplier <= 8) { //Use "Integer.parseInt()" method to instantly convert from String to int value. card_multiplier = Integer.parseInt(enter_no_of_decks.getText().toString()); //Shuffling cards... pile = new Pile(card_multiplier); //Multiply no. of decks //Dismiss or close the dialog. deck_dialog.dismiss(); } else { Toast.makeText(getApplicationContext(), "Please choose a number from 1 to 8.", Toast.LENGTH_SHORT).show(); } } }); //Show dialog. deck_dialog.show(); } //Shuffling the Array public void Shuffle_Cards(Integer[][] Shuffle_Deck) { Random random = new Random(); for(int i = Shuffle_Deck[no_of_cards].length - 1; i >=0; i--) { int Index = random.nextInt(i + 1); //Simple Swapping Integer swap = Shuffle_Deck[card_multiplier-1][Index]; Shuffle_Deck[card_multiplier-1][Index] = Shuffle_Deck[card_multiplier-1][i]; Shuffle_Deck[card_multiplier-1][i] = swap; } } //Private Class for Random Card Draw private class Draw_Card_Model implements OnClickListener { public void onClick(View v) { //Just printing the card drawn from pile int suit = 0, value = 0; String strSuit = "", strValue = ""; draw_deck draw = new draw_deck(context); //This line is where issued the Null Pointer Exception. if (count == card_multiplier*52) { // A message shows up when all cards are draw out. Toast.makeText(getApplicationContext(), "All cards have been used up.", Toast.LENGTH_SHORT).show(); draw_card.setEnabled(false); } else { draw.draw(suit, value, strSuit, strValue, pile, context); count_label.setText(count); //This is where I got force closed error, although "int count" have initialized the number. This was supposed to accept in the setText() method. count++; } } } } Take note that the issues on Null Pointer Exception is the Image View and the Edit Text. I got to test it. Thanks. If you have any info about my question, let me know it frankly.

    Read the article

  • QapTcha error issue. Works locally, not on live server [migrated]

    - by BlassFemur
    I am adding QapTcha (http://demos.myjqueryplugins.com/qaptcha/) to a website that I am working on and I'm getting the error "Uncaught TypeError: Cannot read property 'error' of null". What's weird to me is everything is working perfectly locally. No errors or anything. Once I uploaded via ftp to the live server, I get the above error. Below is the block of code that seems to be generating the error: Slider.draggable({ revert: function(){ if(opts.autoRevert) { if(parseInt(Slider.css("left")) (bgSlider.width()-Slider.width()-10)) return false; else return true; } }, containment: bgSlider, axis:'x', stop: function(event,ui){ if(ui.position.left (bgSlider.width()-Slider.width()-10)) { // set the SESSION iQaptcha in PHP file $.post(opts.PHPfile,{ action : 'qaptcha', qaptcha_key : inputQapTcha.attr('name') }, function(data) { if(!data.error) Uncaught TypeError: Cannot read property 'error' of null { Slider.draggable('disable').css('cursor','default'); inputQapTcha.val(''); TxtStatus.text(opts.txtUnlock).addClass('dropSuccess').removeClass('dropError'); form.find('input[type=\'submit\']').removeAttr('disabled'); if(opts.autoSubmit) form.find('input[type=\'submit\']').trigger('click'); } },'json'); } } }); I'm not really sure what's going on as to why it works locally and not on the server. Any help/ suggestions would be appreciated. Thanks

    Read the article

  • Model View Control Issue: Null Pointer Initialization Question [closed]

    - by David Dimalanta
    Good morning again. This is David. Please, I need an urgent help regarding control model view where I making a code that uniquely separating into groups: An Activity Java Class to Display the Interface A View and Function Java Class for Drawing Cards and Display it on the Activity Class The problem is that the result returns a Null Pointer Exception. I have initialize for the ID for Text View and Image View. Under this class "draw_deck.java". Please help me. Here's my code for draw_deck.java: package com.bodapps.inbetween.model; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bodapps.inbetween.R; public class draw_deck extends View { public TextView count_label; public ImageView draw_card; private int count; public draw_deck(Context context) { super(context); // TODO Auto-generated constructor stub //I have initialized two widgets for ID. I still don't get it why I got forced closed by Null Pointer Exception thing. draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); } public void draw(int s, int c, String strSuit, String strValue, Pile pile, Context context) { //super(context); //Just printing the card drawn from pile int suit, value = 1; draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); Card card; if(!pile.isEmpty()) //Setting it to IF statement displays the card one by one. { card = pile.drawFromPile(); //Need to check first if card is null. if (card != null) { //draws an extra if (card != null) { //Get suit of card to print out. suit = card.getSuit(); switch (suit) { case CardInfo.DIAMOND: strSuit = "DIAMOND"; s=0; break; case CardInfo.HEART: strSuit = "HEART"; s=1; break; case CardInfo.SPADE: strSuit = "SPADE"; s=2; break; case CardInfo.CLUB: strSuit = "CLUB"; s=3; break; } //Get value of card to print out. value = card.getValue(); switch (value) { case CardInfo.ACE: strValue = "ACE"; c=0; break; case CardInfo.TWO: c=1; break; case CardInfo.THREE: strValue = "THREE"; c=2; break; case CardInfo.FOUR: strValue = "FOUR"; c=3; break; case CardInfo.FIVE: strValue = "FIVE"; c=4; break; case CardInfo.SIX: strValue = "SIX"; c=4; break; case CardInfo.SEVEN: strValue = "SEVEN"; c=4; break; case CardInfo.EIGHT: strValue = "EIGHT"; c=4; break; case CardInfo.NINE: strValue = "NINE"; c=4; break; case CardInfo.TEN: strValue = "TEN"; c=4; break; case CardInfo.JACK: strValue = "JACK"; c=4; break; case CardInfo.QUEEN: strValue = "QUEEN"; c=4; break; case CardInfo.KING: strValue = "KING"; c=4; break; } } } }// //Below two lines of code, this is where issued the Null Pointer Exception. draw_card.setImageResource(deck[s][c]); count_label.setText(new StringBuilder(strValue).append(" of ").append(strSuit).append(String.valueOf(" " + count++)).toString()); } //Choice of Suits in a Deck public Integer[][] deck = { //Array Group 1 is [0][0] (No. of Cards: 4 - DIAMOND) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 2 is [1][0] (No. of Cards: 4 - HEART) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 3 is [2][0] (No. of Cards: 4 - SPADE) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 4 is [3][0] (No. of Cards: 4 - CLUB) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, }; } And this one of the activity class, Player_Mode_2.java: package com.bodapps.inbetween; import java.util.Random; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bodapps.inbetween.model.Card; import com.bodapps.inbetween.model.Pile; import com.bodapps.inbetween.model.draw_deck; /* * * Public class for Two-Player mode. * */ public class Player_Mode_2 extends Activity { //Image Views private ImageView draw_card; private ImageView player_1; private ImageView player_2; private ImageView icon; //Buttons private Button set_deck; //Edit Texts private EditText enter_no_of_decks; //text Views private TextView count_label; //Integer Data Types private int no_of_cards, count; private int card_multiplier; //Contexts final Context context = this; //Pile Model public Pile pile; //Card Model public Card card; //create View @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.play_2_player_mode); //-----[ Search for Views ]----- //Initialize for Image View draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); player_1 = (ImageView) findViewById(R.id.IV_Player_1_Card); player_2 = (ImageView) findViewById(R.id.IV_Player_2_Card); //Initialize for Text view or Label count_label = (TextView) findViewById(R.id.Text_View_Count_Card); //-----[ Adding Values ]----- //Integer Values count = 0; no_of_cards = 0; //-----[ Adding Dialog ]----- //Initializing Dialog final Dialog deck_dialog = new Dialog(context); deck_dialog.setContentView(R.layout.dialog); deck_dialog.setTitle("Deck Dialog"); //-----[ Initializing Views for Dialog's Contents ]----- //Initialize for Edit Text enter_no_of_decks = (EditText) deck_dialog.findViewById(R.id.Edit_Text_Set_Number_of_Decks); //Initialize for Button set_deck = (Button) deck_dialog.findViewById(R.id.Button_Deck); //-----[ Setting onClickListener() ]----- //Set Event Listener for Image view draw_card.setOnClickListener(new Draw_Card_Model()); //Set Event Listener for Setting the Deck set_deck.setOnClickListener(new OnClickListener() { public void onClick(View v) { if(card_multiplier <= 8) { //Use "Integer.parseInt()" method to instantly convert from String to int value. card_multiplier = Integer.parseInt(enter_no_of_decks.getText().toString()); //Shuffling cards... pile = new Pile(card_multiplier); //Multiply no. of decks //Dismiss or close the dialog. deck_dialog.dismiss(); } else { Toast.makeText(getApplicationContext(), "Please choose a number from 1 to 8.", Toast.LENGTH_SHORT).show(); } } }); //Show dialog. deck_dialog.show(); } //Shuffling the Array public void Shuffle_Cards(Integer[][] Shuffle_Deck) { Random random = new Random(); for(int i = Shuffle_Deck[no_of_cards].length - 1; i >=0; i--) { int Index = random.nextInt(i + 1); //Simple Swapping Integer swap = Shuffle_Deck[card_multiplier-1][Index]; Shuffle_Deck[card_multiplier-1][Index] = Shuffle_Deck[card_multiplier-1][i]; Shuffle_Deck[card_multiplier-1][i] = swap; } } //Private Class for Random Card Draw private class Draw_Card_Model implements OnClickListener { public void onClick(View v) { //Just printing the card drawn from pile int suit = 0, value = 0; String strSuit = "", strValue = ""; draw_deck draw = new draw_deck(context); //This line is where issued the Null Pointer Exception. if (count == card_multiplier*52) { // A message shows up when all cards are draw out. Toast.makeText(getApplicationContext(), "All cards have been used up.", Toast.LENGTH_SHORT).show(); draw_card.setEnabled(false); } else { draw.draw(suit, value, strSuit, strValue, pile, context); count_label.setText(count); //This is where I got force closed error, although "int count" have initialized the number. This was supposed to accept in the setText() method. count++; } } } } Take note that the issues on Null Pointer Exception is the Image View and the Edit Text. I got to test it. Thanks. If you have any info about my question, let me know it frankly.

    Read the article

  • MultiSelectChoice: How to get underlying values selected

    - by Vijay Mohan
    Let's say you include a multiselectchoice component in your jspx/jsff page, which has <f;selectItem> or <af:forEach> binded to a VO iterator to populate the multiselectchoice and the value property of which is binded to a List attribute binding.When the user selects some items in that choice List then u want the actual values to be posted.You can check the valuepassthrough flag to true , but many a times it doesn't help and you end up getting the indexes of multiselect values.Here is a way to get the actual values..Lets say in the bean u have a utility method to achieve this as follows..You can associate a valueChangeListener for the multiselectchoice as follows..public void onValueChangeOfLOV(ValueChangeEvent valueChangeEvent) { //get array of indexes of selected items in master list List valueIndexes = (List)valueChangeEvent.getNewValue(); String concatCodes = returnSelectmanyChoiceValues(valueIndexes,"YourIterator", "YourAttribute"); } public String returnSelectmanyChoiceValues(List valueIndexes,String iterName, String idAttrName){ DCBindingContainer dc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry(); DCIteratorBinding iter = dc.findIteratorBinding(iterName); ViewObject vo = iter.getViewObject(); String codes = ""; for(Object index : valueIndexes){ String iIndex = (String)index; Row row = vo.getRowAtRangeIndex(Integer.parseInt(iIndex)); codes = codes +(String)row.getAttribute(idAttrName)+","; } //remove last "," if(codes.endsWith(",")) codes = codes.substring(0,codes.lastIndexOf(",")); return codes; }This will return u a comma separated values of the selected items. if you want thenYou can store it in a List.

    Read the article

  • Throwing and catching exceptions in the same function/method

    - by usr
    I've written a function that asks a user for input until user enters a positive integer (a natural number). Somebody said I shouldn't throw and catch exceptions in my function and should let the caller of my function handle them. I wonder what other developers think about this. I'm also probably misusing exceptions in the function. Here's the code in Java: private static int sideInput() { int side = 0; String input; Scanner scanner = new Scanner(System.in); do { System.out.print("Side length: "); input = scanner.nextLine(); try { side = Integer.parseInt(input); if (side <= 0) { // probably a misuse of exceptions throw new NumberFormatException(); } } catch (NumberFormatException numFormExc) { System.out.println("Invalid input. Enter a natural number."); } } while (side <= 0); return side; } I'm interested in two things: Should I let the caller worry about exceptions? The point of the function is that it nags the user until the user enters a natural number. Is the point of the function bad? I'm not talking about UI (user not being able to get out of the loop without proper input), but about looped input with exceptions handled. Would you say the throw statement (in this case) is a misuse of exceptions? I could easily create a flag for checking validity of the number and output the warning message based on that flag. But that would add more lines to the code and I think it's perfectly readable as it is. The thing is I often write a separate input function. If user has to input a number multiple times, I create a separate function for input that handles all formatting exceptions and limitations.

    Read the article

  • Jquery calculator

    - by Nemanja
    I want to make calculator for summation. I have this jquery code: <script type="text/javascript"> $(document).ready(function() { $("#calculate").click(function() { if ($("#input").val() != '' && $("#input").val() != undefined) { $("#result").html("Result is: " + parseInt($("#input").val()) * 30 ); } else { $("#result").html("Please enter some value"); } }); }); </script> <div id="calculator"> <br /> <input type="text" style="left:20px;" id="input" /> <div id="result"></div> <input type="button" id="calculate" value="calculate" style="left:20px;" /> </div> I want something like this: I write number 5, then input + from keyboard and write another value. Then to click on summation button and to get value. Can anyone help me with this? Thank you very much!

    Read the article

  • How to optimize this JSON/JQuery/Javascript function in IE7/IE8?

    - by melaos
    hi guys, i'm using this function to parse this json data but i find the function to be really slow in IE7 and slightly slow in IE8. basically the first listbox generate the main product list, and upon selection of the main list, it will populate the second list. this is my data: [{"ProductCategoryId":209,"ProductCategoryName":"X-Fi","ProductSubCategoryId":668,"ProductSubCategoryName":"External Solutions","ProductId":15913,"ProductName":"Creative Xmod","ProductServiceLifeId":1},{"ProductCategoryId":209,"ProductCategoryName":"X-Fi","ProductSubCategoryId":668,"ProductSubCategoryName":"External Solutions","ProductId":15913,"ProductName":"Creative Xmod","ProductServiceLifeId":1},{"ProductCategoryId":209,"ProductCategoryName":"X-Fi","ProductSubCategoryId":668,"ProductSubCategoryName":"External Solutions","ProductId":18094,"ProductName":"Sound Blaster Wireless Receiver","ProductServiceLifeId":1},{"ProductCategoryId":209,"ProductCategoryName":"X-Fi","ProductSubCategoryId":668,"ProductSubCategoryName":"External Solutions","ProductId":16185,"ProductName":"Xdock Wireless","ProductServiceLifeId":1},{"ProductCategoryId":209,"ProductCategoryName":"X-Fi","ProductSubCategoryId":668,"ProductSubCategoryName":"External Solutions","ProductId":16186,"ProductName":"Xmod Wireless","ProductServiceLifeId":1}] and these are the functions that i'm using: //Three Product Panes function function populateMainPane() { $.getJSON('/Home/ThreePaneProductData/', function(data) { products = data; alert(JSON.stringify(products)); var prodCategory = {}; for (i = 0; i < products.length; i++) { prodCategory[products[i].ProductCategoryId] = products[i].ProductCategoryName; } //end for //take only unique product category to be used var id = 0; for (id in prodCategory) { if (prodCategory.hasOwnProperty(id)) { $(".LBox1").append("<option value='" + id + "'>" + prodCategory[id] + "</option>"); //alert(prodCategory[id]); } } var url = document.location.href; var parms = url.substring(url.indexOf("?") + 1).split("&"); for (var i = 0; i < parms.length; i++) { var parm = parms[i].split("="); if (parm[0].toLowerCase() == "pid") { $(".PanelProductReg").show(); var nProductIds = parm[1].split(","); for (var k = 0; k < nProductIds.length; k++) { var nProductId = parseInt(nProductIds[k], 10); for (var j = 0; j < products.length; j++) { if (nProductId == parseInt(products[j].ProductId, 10)) { addProductRow(nProductId, products[j].ProductName); j = products.length; } } //end for } } } }); } //end function function populateSubCategoryPane() { var subCategory = {}; for (var i = 0; i < products.length; i++) { if (products[i].ProductCategoryId == $('.LBox1').val()) subCategory[products[i].ProductSubCategoryId] = products[i].ProductSubCategoryName; } //end for //clear off the list box first $(".LBox2").html(""); var id = 0; for (id in subCategory) { if (subCategory.hasOwnProperty(id)) { $(".LBox2").append("<option value='" + id + "'>" + subCategory[id] + "</option>"); //alert(prodCategory[id]); } } } //end function is there anything i can do to optimize this or is this a known browser issue?

    Read the article

  • Working on a jQuery plugin : viewport simulator

    - by pixelboy
    Hi community, i'm working on a jQuery plugin that's aiming to simulate one axis camera movements. The first step to achieving this is simple : use conventional, clean markup, and get the prototype to work. Heres how to initiate the plugin : $('#wrapper').fluidGrids({exclude: '.exclude'}); Here's a working demo of the WIP thing : http://sandbox.test.everestconseil.com/protoCitroen/home.html Where am I having issues : Is there a fast way to detect if parent of each target (clickable animated element) is a href link, and if so to save this url ? My clone uses the original background image to then animate it.fade it to black/white. But when you clik on an element, image url is found, but doesn't seem to be injected. Do you see anything ? Finally, about animation of elements : as you can see in source code, I'm using the container $('#wrapper') to position all animated children. What would be the perfect properties to apply to make this cross browser proof ? Here's the source code for the plugin, fully commented. (function($){ $.fn.extend({ //plugin name - fluidGrids fluidGrids: function(options) { //List and default values for available options var defaults = { //The target that we're going to use to handle click event hitTarget: '.animateMe', exclude: '.exclude', animateSpeed: 1000 }; var options = $.extend(defaults, options); return this.each(function() { var o = options; //Assign current element to variable var obj = $(this); //We assign default width height and positions to each object in order to get them back when necessary var objPosition = obj.position(); //Get all ready to animate targets in innerViewport var items = $(o.hitTarget, obj); //Final coords of innerViewport var innerViewport = new Object(); innerViewport.top = parseInt(objPosition.top); innerViewport.left = parseInt(objPosition.left); innerViewport.bottom = obj.height(); innerViewport.right = obj.width(); items.each(function(e){ //Assign a pointer cursor to each clickable element $(this).css("cursor","pointer"); //To load distant url at last, we look for it in Title Attribute if ($(this).attr('title').length){ var targetUrl = $(this).attr('title'); } //We assign default width height and positions to each object in order to get them back when necessary var itemPosition = $(this).position(); var itemTop = itemPosition.top; var itemLeft = itemPosition.left; var itemWidth = $(this).width(); var itemHeight = $(this).height(); //Both the original and it's animated clone var original = $(this); //To give the if (original.css('background-image')){ var urlImageOriginal = original.css('background-image').replace(/^url|[("")]/g, ''); var imageToInsert = "<img src="+urlImageOriginal+"/>" } var clone = $(this).clone(); original.click(function() { $(clone).append(imageToInsert); $(clone).attr("id","clone"); $(clone).attr('top',itemTop); $(clone).attr('left',itemLeft); $(clone).css("position","absolute"); $(clone).insertAfter(this); $(this).hide(); $(clone).animate({ top: innerViewport.top, left: innerViewport.left, width: innerViewport.bottom, height: innerViewport.right }, obj.animateSpeed); $("*",obj).not("#clone, #clone * , a , "+ o.exclude).fadeOut('fast'); //Si l'objet du click est un lien return false; }); }); }); } }); })(jQuery);

    Read the article

  • nextSibling issues...

    - by SoLoGHoST
    Ok, this has been killing me all night, I mean I've been working on this code for atleast 8 hours now. What is the problem with this, argggg. I am trying to update all <span id="column_[some number]"> to increment it by one after the next id="row_" tr element, but for some god knows what reason, it gives me issues. It's updating the same <span> tag 2x, and this changes it from the desired value to 1 more than it should be... argggg. Here's my code someone please help me here... // Reorder all columns, if any, in the other rows after this 1. if (aRowId != 0 && lId.indexOf("tr_" + aRowId) == 0 && rowComplete != aRowId) { var tempTr = lTable.childNodes[i].childNodes[p]; while(tempTr.nodeType == 1 && tempTr.nextSibling != null) { var tempId = tempTr.getAttribute("id"); if (!tempId) continue; if (tempId.indexOf("row_") == 0) { // All done this row, set it to completed! rowComplete = aRowId; break; } if (tempTr.hasChildNodes) { var doneChilds = false; // grab the id where tdcolumn_{aRowId}.indexOf = 0. for (fcTd = 0; fcTd<tempTr.childNodes.length; fcTd++) { if (tempTr.childNodes[fcTd].nodeName == '#text') continue; var tempfcId = tempTr.childNodes[fcTd].getAttribute("id"); if (!tempfcId) continue; if (tempfcId.indexOf("tdcolumn_" + aRowId) != 0) continue; // looping through the children in the <td> element here. if (tempTr.childNodes[fcTd].hasChildNodes) { for (x = tempTr.childNodes[fcTd].childNodes.length-1; x>0; x--) { if (tempTr.childNodes[fcTd].childNodes[x].nodeName == '#text') continue; var tempSpanId = tempTr.childNodes[fcTd].childNodes[x].getAttribute("id"); if (!tempSpanId) continue; if (tempSpanId.indexOf("column_") != 0) continue; // alert(tempSpanId); alert(tempTr.childNodes[fcTd].childNodes[x].nodeName); var tSpanId = new Array(); tSpanId = tempSpanId.split("_"); if (currColumnId == 0) { currColumnId = parseInt(tSpanId[1]); var incCol = currColumnId; } incCol++; // alert("currColumnId = " + currColumnId + "\n\ntSpanId[1] = " + tSpanId[1] + "\n\nincCol = " + incCol); // Set the new Id's and Text, after which we can exit the for loop. tempTr.childNodes[fcTd].childNodes[x].setAttribute("id", "column_" + incCol); tempTr.childNodes[fcTd].childNodes[x].setAttribute("class", "dp_edit_column"); tempTr.childNodes[fcTd].childNodes[x].innerHTML = oColumnText + " " + incCol; // tempTr.childNodes[fcTd].setAttribute("id", "tdcolumn_" + aRowId + "_" + (parseInt(tSpanId[1])+1) + "_" + tSpanId[3]); doneChilds = true; break; } } else continue; if (doneChilds = true) continue; } } else continue; tempTr = tempTr.nextSibling; } } Please help me, thanks.

    Read the article

  • Generics and Performance question.

    - by Tarmon
    Hey Everyone, I was wondering if anyone could look over a class I wrote, I am receiving generic warnings in Eclipse and I am just wondering if it could be cleaned up at all. All of the warnings I received are surrounded in ** in my code below. The class takes a list of strings in the form of (hh:mm AM/PM) and converts them into HourMinute objects in order to find the first time in the list that comes after the current time. I am also curious about if there are more efficient ways to do this. This works fine but the student in me just wants to find out how I could do this better. public class FindTime { private String[] hourMinuteStringArray; public FindTime(String[] hourMinuteStringArray){ this.hourMinuteStringArray = hourMinuteStringArray; } public int findTime(){ HourMinuteList hourMinuteList = convertHMStringArrayToHMArray(hourMinuteStringArray); Calendar calendar = new GregorianCalendar(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); HourMinute now = new HourMinute(hour,minute); int nearestTimeIndex = findNearestTimeIndex(hourMinuteList, now); return nearestTimeIndex; } private int findNearestTimeIndex(HourMinuteList hourMinuteList, HourMinute now){ HourMinute current; int position = 0; Iterator<HourMinute> iterator = **hourMinuteList.iterator()**; while(iterator.hasNext()){ current = (HourMinute) iterator.next(); if(now.compareTo(current) == -1){ return position; } position++; } return position; } private static HourMinuteList convertHMStringArrayToHMArray(String[] times){ FindTime s = new FindTime(new String[1]); HourMinuteList list = s.new HourMinuteList(); String[] splitTime = new String[3]; for(String time : times ){ String[] tempFirst = time.split(":"); String[] tempSecond = tempFirst[1].split(" "); splitTime[0] = tempFirst[0]; splitTime[1] = tempSecond[0]; splitTime[2] = tempSecond[1]; int hour = Integer.parseInt(splitTime[0]); int minute = Integer.parseInt(splitTime[1]); HourMinute hm; if(splitTime[2] == "AM"){ hm = s.new HourMinute(hour,minute); } else if((splitTime[2].equals("PM")) && (hour < 12)){ hm = s.new HourMinute(hour + 12,minute); } else{ hm = s.new HourMinute(hour,minute); } **list.add(hm);** } return list; } class **HourMinuteList** extends **ArrayList** implements RandomAccess{ } class HourMinute implements **Comparable** { int hour; int minute; public HourMinute(int hour, int minute) { setHour(hour); setMinute(minute); } int getMinute() { return this.minute; } String getMinuteString(){ if(this.minute < 10){ return "0" + this.minute; }else{ return "" + this.minute; } } int getHour() { return this.hour; } void setHour(int hour) { this.hour = hour; } void setMinute(int minute) { this.minute = minute; } @Override public int compareTo(Object aThat) { if (aThat instanceof HourMinute) { HourMinute that = (HourMinute) aThat; if (this.getHour() == that.getHour()) { if (this.getMinute() > that.getMinute()) { return 1; } else if (this.getMinute() < that.getMinute()) { return -1; } else { return 0; } } else if (this.getHour() > that.getHour()) { return 1; } else if (this.getHour() < that.getHour()) { return -1; } else { return 0; } } return 0; } } If you have any questions let me know. Thanks, Rob

    Read the article

  • Doing a roll-in/roll-out slideshow in jQuery

    - by erizias
    I am trying to create a roll-in / roll-out slideshow in jQuery/JavaScript. My problem is, that it needs to be repeated. And right now when it's starting over, the pictures doesnt come from the right side anymore :( The reason for which I have created the slideLeft function, is that afterwards I need to create 2 functions, where the user can interrupt the slideshow manually pressing a left or right button. This is what I've got: <script class="jsbin" src="http://code.jquery.com/jquery-1.7.2.min.js"></script> <div style='background: #c4c4c4; border: 1px solid #7b7b7b; height: 220px; overflow: hidden; padding: 5px; position: absolute; width: 590px;'> <div id='slider-image-1' style='left: 5px; background: red; height: 216px; padding: 2px; position: absolute; top: 5px; width: 586px;'></div> <div id='slider-image-2' style='left: 600px; background: yellow; height: 216px; padding: 2px; position: absolute; top: 5px; width: 586px;'></div> <div id='slider-image-3' style='left: 600px; background: green; height: 216px; padding: 2px; position: absolute; top: 5px; width: 586px;'></div> <div id='slider-image-4' style='left: 600px; background: blue; height: 216px; padding: 2px; position: absolute; top: 5px; width: 586px;'></div> </div> <script type='text/javascript'> $(document).ready(function() { var amount = 0; var nextamount = 1; setInterval(function() { amount++; nextamount++; if (nextamount === 5) nextamount = 1; if (amount === 5) amount = 1; slideLeft(amount, nextamount); }, 2000); }); function slideLeft(i, j) { var $theItem = $('#slider-image-' + i); $theItem.animate({ left: parseInt($theItem.css('left'), 10) == 5 ? -$theItem.outerWidth() : 5 }, 500); var $theItem = $('#slider-image-' + j); $theItem.animate({ left: parseInt($theItem.css('left'), 10) == 5 ? $theItem.outerWidth() + 10 : 5 }, 500); }; </script>

    Read the article

  • How can I modify my Shunting-Yard Algorithm so it accepts unary operators?

    - by KingNestor
    I've been working on implementing the Shunting-Yard Algorithm in JavaScript for class. Here is my work so far: var userInput = prompt("Enter in a mathematical expression:"); var postFix = InfixToPostfix(userInput); var result = EvaluateExpression(postFix); document.write("Infix: " + userInput + "<br/>"); document.write("Postfix (RPN): " + postFix + "<br/>"); document.write("Result: " + result + "<br/>"); function EvaluateExpression(expression) { var tokens = expression.split(/([0-9]+|[*+-\/()])/); var evalStack = []; while (tokens.length != 0) { var currentToken = tokens.shift(); if (isNumber(currentToken)) { evalStack.push(currentToken); } else if (isOperator(currentToken)) { var operand1 = evalStack.pop(); var operand2 = evalStack.pop(); var result = PerformOperation(parseInt(operand1), parseInt(operand2), currentToken); evalStack.push(result); } } return evalStack.pop(); } function PerformOperation(operand1, operand2, operator) { switch(operator) { case '+': return operand1 + operand2; case '-': return operand1 - operand2; case '*': return operand1 * operand2; case '/': return operand1 / operand2; default: return; } } function InfixToPostfix(expression) { var tokens = expression.split(/([0-9]+|[*+-\/()])/); var outputQueue = []; var operatorStack = []; while (tokens.length != 0) { var currentToken = tokens.shift(); if (isNumber(currentToken)) { outputQueue.push(currentToken); } else if (isOperator(currentToken)) { while ((getAssociativity(currentToken) == 'left' && getPrecedence(currentToken) <= getPrecedence(operatorStack[operatorStack.length-1])) || (getAssociativity(currentToken) == 'right' && getPrecedence(currentToken) < getPrecedence(operatorStack[operatorStack.length-1]))) { outputQueue.push(operatorStack.pop()) } operatorStack.push(currentToken); } else if (currentToken == '(') { operatorStack.push(currentToken); } else if (currentToken == ')') { while (operatorStack[operatorStack.length-1] != '(') { if (operatorStack.length == 0) throw("Parenthesis balancing error! Shame on you!"); outputQueue.push(operatorStack.pop()); } operatorStack.pop(); } } while (operatorStack.length != 0) { if (!operatorStack[operatorStack.length-1].match(/([()])/)) outputQueue.push(operatorStack.pop()); else throw("Parenthesis balancing error! Shame on you!"); } return outputQueue.join(" "); } function isOperator(token) { if (!token.match(/([*+-\/])/)) return false; else return true; } function isNumber(token) { if (!token.match(/([0-9]+)/)) return false; else return true; } function getPrecedence(token) { switch (token) { case '^': return 9; case '*': case '/': case '%': return 8; case '+': case '-': return 6; default: return -1; } } function getAssociativity(token) { switch(token) { case '+': case '-': case '*': case '/': return 'left'; case '^': return 'right'; } } It works fine so far. If I give it: ((5+3) * 8) It will output: Infix: ((5+3) * 8) Postfix (RPN): 5 3 + 8 * Result: 64 However, I'm struggling with implementing the unary operators so I could do something like: ((-5+3) * 8) What would be the best way to implement unary operators (negation, etc)? Also, does anyone have any suggestions for handling floating point numbers as well? One last thing, if anyone sees me doing anything weird in JavaScript let me know. This is my first JavaScript program and I'm not used to it yet.

    Read the article

  • GroupLayout: JScrollPane in TextArea is not working

    - by Dozent
    i'm new in java and recently started to develop an simple application. For the moment i have a problem with JScrollPanne, it's not able to scroll down (or up) when the text in textarea more than size of area. I have looked to some solutions, but all of them were for FlowLayot (GridLayout and BoxLayout), but not for GroupLayout. Here is the code: JPanel conent_p = new JPanel(); conent_p.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null)); JLabel lblItemName = new JLabel("Item name:"); itemField = new JTextField(); itemField.setColumns(10); JLabel lblMxPrice = new JLabel("Max price:"); mpriceField = new JTextField(); mpriceField.setColumns(10); JLabel lblQuantity = new JLabel("Quantity:"); quanField = new JTextField(); quanField.setColumns(10); JLabel lblDelivery = new JLabel("Delivery:"); delivField = new JTextField(); delivField.setColumns(10); JLabel lblLogcat = new JLabel("LogCat:"); final JTextArea txtConsole = new JTextArea(); txtConsole.setEditable(false); txtConsole.setLineWrap(true); txtConsole.setWrapStyleWord(true); sbrText = new JScrollPane(txtConsole); sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // Now create a new TextAreaOutputStream to write to our JTextArea control and wrap a // PrintStream around it to support the println/printf methods. PrintStream out = new PrintStream(new TextAreaOutputStream(txtConsole)); // redirect standard output stream to the TextAreaOutputStream System.setOut(out); // redirect standard error stream to the TextAreaOutputStream System.setErr(out); GroupLayout gl_conent_p = new GroupLayout(conent_p); gl_conent_p.setHorizontalGroup( gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addContainerGap() .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addComponent(lblMxPrice, Alignment.TRAILING) .addComponent(lblItemName, Alignment.TRAILING) .addComponent(lblLogcat, Alignment.TRAILING)) .addGap(18) .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING, false) .addComponent(itemField, GroupLayout.PREFERRED_SIZE, 365, GroupLayout.PREFERRED_SIZE) .addGroup(gl_conent_p.createSequentialGroup() .addComponent(mpriceField, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(lblQuantity) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(quanField, 0, 0, Short.MAX_VALUE) .addGap(18) .addComponent(lblDelivery) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(delivField, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED))) .addGap(100)) .addGroup(gl_conent_p.createSequentialGroup() .addComponent(txtConsole, GroupLayout.PREFERRED_SIZE, 345, GroupLayout.PREFERRED_SIZE) .addComponent(sbrText) .addContainerGap()))) ); gl_conent_p.setVerticalGroup( gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addContainerGap() .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblItemName) .addComponent(itemField, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)) .addGap(20) .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblDelivery) .addComponent(delivField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblMxPrice) .addComponent(mpriceField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblQuantity) .addComponent(quanField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGap(55) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblLogcat) .addComponent(txtConsole, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE) .addComponent(sbrText)) .addContainerGap()) ); conent_p.setLayout(gl_conent_p); getContentPane().add(conent_p, BorderLayout.NORTH); JButton btnBuy = new JButton("Buy"); btnBuy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { try { String title = itemField.getText().trim(); String mprice = mpriceField.getText().trim(); String quantity = quanField.getText().trim(); String deliver = delivField.getText().trim(); Item_CONCEPT item = new Item_CONCEPT(); item.setName(title); item.setDelivery(Integer.parseInt(deliver)); item.setStartPrice(0); item.setMaxPrice(Integer.parseInt(mprice)); myAgent.existsSeller(item); Date date = new Date(); DateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm"); System.out.println(df.format(date)+": Buyer orders an item: "+item.getName()); //Clearing all fields itemField.setText(""); quanField.setText(""); delivField.setText(""); //txtConsole.setText(""); mpriceField.setText(""); } catch (Exception e) { JOptionPane.showMessageDialog(BuyerGUI.this, "A field is filled incorrectly. "+e.getMessage()+" is invalid.", "Error", JOptionPane.ERROR_MESSAGE); } } } );![enter image description here][1]

    Read the article

  • jsp error plz check this code why are not insert my data into database

    - by lekhni
    <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <%@ page import="java.sql.*" %> <%@ page import="java.io.*"%> <%@ page import="java.io.File"%> <%@ page import="java.util.*"%> <%@ page import="java.sql.*"%> <%@ page import="java.sql.Blob"%> <%@ page import="java.sql.PreparedStatement"%> <%@ page import="java.sql.BatchUpdateException"%> <%@ page import="javax.servlet.*"%> <%@ page import="javax.servlet.http.*"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'p.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% int activityId = Integer.parseInt(request.getParameter("activityId")); String name = request.getParameter("name"); String activityType = request.getParameter("activityType"); int parentId = Integer.parseInt(request.getParameter("parentId")); String description = request.getParameter("description"); %> <% Connection conn=null; PreparedStatement pstatement = null; try{ Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/pol","root","1234"); Statement st=conn.createStatement(); String queryString = "INSERT INTO activity(activityId,name,activityType,parentId,description)" + " VALUES (?, ?, ?, ?, ?)"; pstatement = conn.prepareStatement(queryString); pstatement.setInt(1, activityId); pstatement.setString(2, name); pstatement.setString(3, activityType); pstatement.setInt(4, parentId); pstatement.setString(5, description); } catch (Exception ex) { out.println("Unable to connect to batabase."); } finally { pstatement.close(); conn.close(); } %> </body> </html>

    Read the article

  • reading a random access file

    - by user1067332
    The file I create has text in it, but when i try to read it, the output is null. here is the file the creates the text file, it creates the file and puts it in the right postion import java.util.*; import java.io.*; public class CreateCustomerFile { public static void main(String[] args) throws IOException { int pos; RandomAccessFile it = new RandomAccessFile("CustomerFile.txt", "rw"); Scanner input = new Scanner(System.in); int id; String name; int zip; final int RECORDSIZE = 100; final int NUMRECORDS = 1000; final int STOP = 99; try { for(int x = 0; x < NUMRECORDS; ++x) { it.writeInt(0); it.writeUTF(""); it.writeInt(0); } } catch(IOException e) { System.out.println("Error: " + e.getMessage()); } finally { it.close(); } it = new RandomAccessFile("CustomerFile.txt","rw"); try { System.out.print("Enter ID number" + " or " + STOP + " to quit "); id = input.nextInt(); while(id != STOP) { input.nextLine(); System.out.print("Enter last name"); name = input.nextLine(); System.out.print("Enter zipcode "); zip = input.nextInt(); pos = id - 1; it.seek(pos * RECORDSIZE); it.writeInt(id); it.writeUTF(name); it.writeInt(zip); System.out.print("Enter ID number" + " or " + STOP + " to quit "); id = input.nextInt(); } } catch(IOException e) { System.out.println("Error: " + e.getMessage()); } finally { it.close(); } } } Here is the file to read, the pos is correct but ouput always goes to the error: null. import javax.swing.*; import java.io.*; public class CustomerItemOrder { public static void main(String[] args) throws IOException { int pos; RandomAccessFile it = new RandomAccessFile("CustomerFile.txt","rw"); String inputString; int id, zip; String name; final int RECORDSIZE = 100; final int STOP = 99; inputString = JOptionPane.showInputDialog(null, "Enter id or "+ STOP + " to quit"); id = Integer.parseInt(inputString); try { while(id != STOP) { pos = id -1 ; it.seek(pos * RECORDSIZE ); id = it.readInt(); name = it.readLine(); zip = it.readInt(); JOptionPane.showMessageDialog(null, "ID:" + id + " last name is " + name + " and zipcode is " + zip); inputString = JOptionPane.showInputDialog(null, "Enter id or " + STOP + " to quit"); id = Integer.parseInt(inputString); } } catch(IOException e) { System.out.println("Error: " + e.getMessage()); } finally { it.close(); } } }

    Read the article

  • When I try to redefine a variable, I get an index out of bounds error

    - by user2770254
    I'm building a program to act as a calculator with memory, so you can give variables and their values. Whenever I'm trying to redefine a variable, a = 5, to a = 6, I get an index out of bounds error. public static void main(String args[]) { LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>(); Scanner scan = new Scanner(System.in); ArrayList<Integer> values = new ArrayList<>(); ArrayList<String> variables = new ArrayList<>(); while(scan.hasNextLine()) { String line = scan.nextLine(); String[] tokens = line.split(" "); if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var")) { int value = 0; for(int i=0; i<tokens.length; i++) { if(tokens.length==3) { value = Integer.parseInt(tokens[2]); System.out.printf("%5d\n",value); if(map.containsKey(tokens[0])) { values.set(values.indexOf(tokens[0]), value); variables.set(variables.indexOf(tokens[0]), tokens[0]); } else { values.add(value); } break; } else if(tokens[i].charAt(0) == '+') { value = addition(tokens, value); System.out.printf("%5d\n",value); variables.add(tokens[0]); if(map.containsKey(tokens[0])) { values.set(values.indexOf(tokens[0]), value); variables.set(variables.indexOf(tokens[0]), tokens[0]); } else { values.add(value); } break; } else if(i==tokens.length-1 && tokens.length != 3) { System.out.println("No operation"); break; } } map.put(tokens[0], value); } if(Character.isDigit(tokens[0].charAt(0))) { int value = 0; if(tokens.length==1) { System.out.printf("%5s\n", tokens[0]); } else { value = addition(tokens, value); System.out.printf("%5d\n", value); } } if(line.equals("clear")) { clear(map); } if(line.equals("var")) { variableList(variables, values); } } } public static int addition(String[] a, int b) { for(String item : a) { if(Character.isDigit(item.charAt(0))) { int add = Integer.parseInt(item); b = b + add; } } return b; } public static void clear(LinkedHashMap<String,Integer> b) { b.clear(); } public static void variableList(ArrayList<String> a, ArrayList<Integer> b) { for(int i=0; i<a.size(); i++) { System.out.printf("%5s: %d\n", a.get(i), b.get(i)); } } I included the whole code because I'm not sure where the error is arising from.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >