Finding length

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Feb 2006
Posts: 21
Reputation: webmasts is an unknown quantity at this point 
Solved Threads: 0
webmasts webmasts is offline Offline
Newbie Poster

Finding length

 
0
  #1
Mar 28th, 2006
Hi,

I'm creating a palindrome program. So far, I got that part. Now, I need to find out if the length of the integer (string) is less than 5 digits. If the length is less than 5, then don't proceed with the program. Please give your suggestions. Basically, what I'm doing is converting the Int to String and then finding the length. Thanks!

I tried the following:

if ( s.length() >= 5 ) {
// Proceed
}

and got this:


Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at _uesJavaRun.main(_uesJavaRun.java:29)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:558)
at palindrome.main(palindrome.java:26)
... 5 more

This is my code so far:


import java.util.Scanner;

public class palindrome
{
public static void main (String args[])
{

Scanner input = new Scanner (System.in );
int number;
String len, size;

System.out.print( "Enter a 5-digit integer: " );
number = input.nextInt();

len = number + "";

// print error message if the length is less than 5 digits

System.out.println ("Your input is not a 5-digit long. Try again.");

}
}
Reply With Quote Quick reply to this message  
Join Date: Feb 2006
Posts: 2,467
Reputation: masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of 
Solved Threads: 267
Moderator
masijade's Avatar
masijade masijade is offline Offline
Nearly a Posting Maven

Re: Finding length

 
0
  #2
Mar 28th, 2006
try this

  1. if (Math.abs(number / 10) < 1000) {
  2. error message
  3. }

since a five digit number will be at least 10000 or -10000

probably a little quicker than converting to string and evaluating
its length as well.
Java Programmer and Sun Systems Administrator

----------------------------------------------

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 5,273
Reputation: iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold 
Solved Threads: 378
Featured Poster
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Posting Expert

Re: Finding length

 
0
  #3
Mar 28th, 2006
I don't have that scanner thing. I use these two classes to handle input from the command line.

Pedantic.java
  1. public class Pedantic
  2. {
  3. public static void main (String args[])
  4. {
  5.  
  6. //Scanner input = new Scanner (System.in );
  7.  
  8. String input;
  9. System.out.println("Please enter a five-digit integer");
  10. input = TextIO.getWord();
  11.  
  12. if(input.length()>=5)
  13. {
  14. System.out.println("woot woot tis ok");
  15. }
  16. else
  17.  
  18. System.out.println ("Your input is not a 5-digit long. Try again.");
  19.  
  20. }
  21. }

TextIO.java
  1. /*
  2.   The file defines a class TextIO, which provides a simple interface
  3.   to Java's standard console input and output. This class defines
  4.   several static methhods for reading and writing
  5.   values of various type.
  6.  
  7.   This class will only work with standard, interactive applications.
  8.   When it is used in such an application, System.out and System.in
  9.   should not be used directly, since the TextIO class thinks it has
  10.   exclusive control of System.out and System.in. (Actually, using
  11.   System.out will probably not cause any problems, but don't use
  12.   System.in.)
  13.  
  14.   To use this class in your program, simply include the compiled class
  15.   file TextIO.class in the same directory with the class file for your
  16.   main program. (If you are using a development environment such as
  17.   CodeWarrior or Visual J++, you can include the source file,
  18.   TextIO.java in your project.) You can then use all the public static methods
  19.   from the TextIO class in your program. (In your programs, the names
  20.   of the methods must be prefaced with "TextIO." For example, you should
  21.   use the name TextIO.getln() rather than simply getln().)
  22.  
  23.   (This class is for use with my on-line introductory java textbook,
  24.   which is available at http://math.hws.edu/eck/cs124/notes/index.html.)
  25.  
  26.   Written by: David Eck
  27.   Department of Mathematics and Computer Science
  28.   Hobart and William Smith Colleges
  29.   Geneva, NY 14456
  30.   Email: eck@hws.edu
  31.   WWW: http://math.hws.edu/eck/
  32.  
  33.   July 16, 1998
  34.  
  35.   Modified February, 2000; getChar() now skips blanks and CR's, and getAnyChar()
  36.   can be used to read the next char even if it's a blank or CR.
  37.  
  38. */
  39.  
  40. import java.io.*;
  41.  
  42. public class TextIO {
  43.  
  44. // *************************** I/O Methods *********************************
  45.  
  46. // Methods for writing the primitive types, plus type String,
  47. // to the console, with no extra spaces.
  48. //
  49. // Note that the real-number data types, float
  50. // and double, a rounded version is output that will
  51. // use at most 10 or 11 characters. If you want to
  52. // output a real number with full accuracy, use
  53. // "TextIO.put(String.valueOf(x))", for example.
  54.  
  55. public static void put(int x) { put(x,0); } // Note: also handles byte and short!
  56. public static void put(long x) { put(x,0); }
  57. public static void put(double x) { put(x,0); } // Also handles float.
  58. public static void put(char x) { put(x,0); }
  59. public static void put(boolean x) { put(x,0); }
  60. public static void put(String x) { put(x,0); }
  61.  
  62.  
  63. // Methods for writing the primitive types, plus type String,
  64. // to the console,followed by a carriage return, with
  65. // no extra spaces.
  66.  
  67. public static void putln(int x) { put(x,0); newLine(); } // Note: also handles byte and short!
  68. public static void putln(long x) { put(x,0); newLine(); }
  69. public static void putln(double x) { put(x,0); newLine(); } // Also handles float.
  70. public static void putln(char x) { put(x,0); newLine(); }
  71. public static void putln(boolean x) { put(x,0); newLine(); }
  72. public static void putln(String x) { put(x,0); newLine(); }
  73.  
  74.  
  75. // Methods for writing the primitive types, plus type String,
  76. // to the console, with a minimum field width of w,
  77. // and followed by a carriage return.
  78. // If output value is less than w characters, it is padded
  79. // with extra spaces in front of the value.
  80.  
  81. public static void putln(int x, int w) { put(x,w); newLine(); } // Note: also handles byte and short!
  82. public static void putln(long x, int w) { put(x,w); newLine(); }
  83. public static void putln(double x, int w) { put(x,w); newLine(); } // Also handles float.
  84. public static void putln(char x, int w) { put(x,w); newLine(); }
  85. public static void putln(boolean x, int w) { put(x,w); newLine(); }
  86. public static void putln(String x, int w) { put(x,w); newLine(); }
  87.  
  88.  
  89. // Method for outputting a carriage return
  90.  
  91. public static void putln() { newLine(); }
  92.  
  93.  
  94. // Methods for writing the primitive types, plus type String,
  95. // to the console, with minimum field width w.
  96.  
  97. public static void put(int x, int w) { dumpString(String.valueOf(x), w); } // Note: also handles byte and short!
  98. public static void put(long x, int w) { dumpString(String.valueOf(x), w); }
  99. public static void put(double x, int w) { dumpString(realToString(x), w); } // Also handles float.
  100. public static void put(char x, int w) { dumpString(String.valueOf(x), w); }
  101. public static void put(boolean x, int w) { dumpString(String.valueOf(x), w); }
  102. public static void put(String x, int w) { dumpString(x, w); }
  103.  
  104.  
  105. // Methods for reading in the primitive types, plus "words" and "lines".
  106. // The "getln..." methods discard any extra input, up to and including
  107. // the next carriage return.
  108. // A "word" read by getlnWord() is any sequence of non-blank characters.
  109. // A "line" read by getlnString() or getln() is everything up to next CR;
  110. // the carriage return is not part of the returned value, but it is
  111. // read and discarded.
  112. // Note that all input methods except getAnyChar(), peek(), the ones for lines
  113. // skip past any blanks and carriage returns to find a non-blank value.
  114. // getln() can return an empty string; getChar() and getlnChar() can
  115. // return a space or a linefeed ('\n') character.
  116. // peek() allows you to look at the next character in input, without
  117. // removing it from the input stream. (Note that using this
  118. // routine might force the user to enter a line, in order to
  119. // check what the next character is.)
  120. // Acceptable boolean values are the "words": true, false, t, f, yes,
  121. // no, y, n, 0, or 1; uppercase letters are OK.
  122. // None of these can produce an error; if an error is found in input,
  123. // the user is forced to re-enter.
  124. // Available input routines are:
  125. //
  126. // getByte() getlnByte() getShort() getlnShort()
  127. // getInt() getlnInt() getLong() getlnLong()
  128. // getFloat() getlnFloat() getDouble() getlnDouble()
  129. // getChar() getlnChar() peek() getAnyChar()
  130. // getWord() getlnWord() getln() getString() getlnString()
  131. //
  132. // (getlnString is the same as getln and is onlyprovided for consistency.)
  133.  
  134. public static byte getlnByte() { byte x=getByte(); emptyBuffer(); return x; }
  135. public static short getlnShort() { short x=getShort(); emptyBuffer(); return x; }
  136. public static int getlnInt() { int x=getInt(); emptyBuffer(); return x; }
  137. public static long getlnLong() { long x=getLong(); emptyBuffer(); return x; }
  138. public static float getlnFloat() { float x=getFloat(); emptyBuffer(); return x; }
  139. public static double getlnDouble() { double x=getDouble(); emptyBuffer(); return x; }
  140. public static char getlnChar() { char x=getChar(); emptyBuffer(); return x; }
  141. public static boolean getlnBoolean() { boolean x=getBoolean(); emptyBuffer(); return x; }
  142. public static String getlnWord() { String x=getWord(); emptyBuffer(); return x; }
  143. public static String getlnString() { return getln(); } // same as getln()
  144. public static String getln() {
  145. StringBuffer s = new StringBuffer(100);
  146. char ch = readChar();
  147. while (ch != '\n') {
  148. s.append(ch);
  149. ch = readChar();
  150. }
  151. return s.toString();
  152. }
  153.  
  154.  
  155. public static byte getByte() { return (byte)readInteger(-128L,127L); }
  156. public static short getShort() { return (short)readInteger(-32768L,32767L); }
  157. public static int getInt() { return (int)readInteger((long)Integer.MIN_VALUE, (long)Integer.MAX_VALUE); }
  158. public static long getLong() { return readInteger(Long.MIN_VALUE, Long.MAX_VALUE); }
  159.  
  160. public static char getAnyChar(){ return readChar(); }
  161. public static char peek() { return lookChar(); }
  162.  
  163. public static char getChar() { // skip spaces & cr's, then return next char
  164. char ch = lookChar();
  165. while (ch == ' ' || ch == '\n') {
  166. readChar();
  167. if (ch == '\n')
  168. dumpString("? ",0);
  169. ch = lookChar();
  170. }
  171. return readChar();
  172. }
  173.  
  174. public static float getFloat() {
  175. float x = 0.0F;
  176. while (true) {
  177. String str = readRealString();
  178. if (str.equals("")) {
  179. errorMessage("Illegal floating point input.",
  180. "Real number in the range " + Float.MIN_VALUE + " to " + Float.MAX_VALUE);
  181. }
  182. else {
  183. Float f = null;
  184. try { f = Float.valueOf(str); }
  185. catch (NumberFormatException e) {
  186. errorMessage("Illegal floating point input.",
  187. "Real number in the range " + Float.MIN_VALUE + " to " + Float.MAX_VALUE);
  188. continue;
  189. }
  190. if (f.isInfinite()) {
  191. errorMessage("Floating point input outside of legal range.",
  192. "Real number in the range " + Float.MIN_VALUE + " to " + Float.MAX_VALUE);
  193. continue;
  194. }
  195. x = f.floatValue();
  196. break;
  197. }
  198. }
  199. return x;
  200. }
  201.  
  202. public static double getDouble() {
  203. double x = 0.0;
  204. while (true) {
  205. String str = readRealString();
  206. if (str.equals("")) {
  207. errorMessage("Illegal floating point input",
  208. "Real number in the range " + Double.MIN_VALUE + " to " + Double.MAX_VALUE);
  209. }
  210. else {
  211. Double f = null;
  212. try { f = Double.valueOf(str); }
  213. catch (NumberFormatException e) {
  214. errorMessage("Illegal floating point input",
  215. "Real number in the range " + Double.MIN_VALUE + " to " + Double.MAX_VALUE);
  216. continue;
  217. }
  218. if (f.isInfinite()) {
  219. errorMessage("Floating point input outside of legal range.",
  220. "Real number in the range " + Double.MIN_VALUE + " to " + Double.MAX_VALUE);
  221. continue;
  222. }
  223. x = f.doubleValue();
  224. break;
  225. }
  226. }
  227. return x;
  228. }
  229.  
  230. public static String getWord() {
  231. char ch = lookChar();
  232. while (ch == ' ' || ch == '\n') {
  233. readChar();
  234. if (ch == '\n')
  235. dumpString("? ",0);
  236. ch = lookChar();
  237. }
  238. StringBuffer str = new StringBuffer(50);
  239. while (ch != ' ' && ch != '\n') {
  240. str.append(readChar());
  241. ch = lookChar();
  242. }
  243. return str.toString();
  244. }
  245.  
  246. public static boolean getBoolean() {
  247. boolean ans = false;
  248. while (true) {
  249. String s = getWord();
  250. if ( s.equalsIgnoreCase("true") || s.equalsIgnoreCase("t") ||
  251. s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("y") ||
  252. s.equals("1") ) {
  253. ans = true;
  254. break;
  255. }
  256. else if ( s.equalsIgnoreCase("false") || s.equalsIgnoreCase("f") ||
  257. s.equalsIgnoreCase("no") || s.equalsIgnoreCase("n") ||
  258. s.equals("0") ) {
  259. ans = false;
  260. break;
  261. }
  262. else
  263. errorMessage("Illegal boolean input value.",
  264. "one of: true, false, t, f, yes, no, y, n, 0, or 1");
  265. }
  266. return ans;
  267. }
  268.  
  269. // ***************** Everything beyond this point is private *******************
  270.  
  271. // ********************** Utility routines for input/output ********************
  272.  
  273. private static InputStream in = System.in; // rename standard input stream
  274. private static PrintStream out = System.out; // rename standard output stream
  275.  
  276. private static String buffer = null; // one line read from input
  277. private static int pos = 0; // position of next char in input line that has
  278. // not yet been processed
  279.  
  280.  
  281. private static String readRealString() { // read chars from input following syntax of real numbers
  282. StringBuffer s=new StringBuffer(50);
  283. char ch=lookChar();
  284. while (ch == ' ' || ch == '\n') {
  285. readChar();
  286. if (ch == '\n')
  287. dumpString("? ",0);
  288. ch = lookChar();
  289. }
  290. if (ch == '-' || ch == '+') {
  291. s.append(readChar());
  292. ch = lookChar();
  293. while (ch == ' ') {
  294. readChar();
  295. ch = lookChar();
  296. }
  297. }
  298. while (ch >= '0' && ch <= '9') {
  299. s.append(readChar());
  300. ch = lookChar();
  301. }
  302. if (ch == '.') {
  303. s.append(readChar());
  304. ch = lookChar();
  305. while (ch >= '0' && ch <= '9') {
  306. s.append(readChar());
  307. ch = lookChar();
  308. }
  309. }
  310. if (ch == 'E' || ch == 'e') {
  311. s.append(readChar());
  312. ch = lookChar();
  313. if (ch == '-' || ch == '+') {
  314. s.append(readChar());
  315. ch = lookChar();
  316. }
  317. while (ch >= '0' && ch <= '9') {
  318. s.append(readChar());
  319. ch = lookChar();
  320. }
  321. }
  322. return s.toString();
  323. }
  324.  
  325. private static long readInteger(long min, long max) { // read long integer, limited to specified range
  326. long x=0;
  327. while (true) {
  328. StringBuffer s=new StringBuffer(34);
  329. char ch=lookChar();
  330. while (ch == ' ' || ch == '\n') {
  331. readChar();
  332. if (ch == '\n');
  333. dumpString("? ",0);
  334. ch = lookChar();
  335. }
  336. if (ch == '-' || ch == '+') {
  337. s.append(readChar());
  338. ch = lookChar();
  339. while (ch == ' ') {
  340. readChar();
  341. ch = lookChar();
  342. }
  343. }
  344. while (ch >= '0' && ch <= '9') {
  345. s.append(readChar());
  346. ch = lookChar();
  347. }
  348. if (s.equals("")){
  349. errorMessage("Illegal integer input.",
  350. "Integer in the range " + min + " to " + max);
  351. }
  352. else {
  353. String str = s.toString();
  354. try {
  355. x = Long.parseLong(str);
  356. }
  357. catch (NumberFormatException e) {
  358. errorMessage("Illegal integer input.",
  359. "Integer in the range " + min + " to " + max);
  360. continue;
  361. }
  362. if (x < min || x > max) {
  363. errorMessage("Integer input outside of legal range.",
  364. "Integer in the range " + min + " to " + max);
  365. continue;
  366. }
  367. break;
  368. }
  369. }
  370. return x;
  371. }
  372.  
  373. private static String realToString(double x) {
  374. // Goal is to get a reasonable representation of x in at most
  375. // 10 characters, or 11 characters if x is negative.
  376. if (Double.isNaN(x))
  377. return "undefined";
  378. if (Double.isInfinite(x))
  379. if (x < 0)
  380. return "-INF";
  381. else
  382. return "INF";
  383. if (Math.abs(x) <= 5000000000.0 && Math.rint(x) == x)
  384. return String.valueOf( (long)x );
  385. String s = String.valueOf(x);
  386. if (s.length() <= 10)
  387. return s;
  388. boolean neg = false;
  389. if (x < 0) {
  390. neg = true;
  391. x = -x;
  392. s = String.valueOf(x);
  393. }
  394. if (x >= 0.00005 && x <= 50000000 && (s.indexOf('E') == -1 && s.indexOf('e') == -1)) { // trim x to 10 chars max
  395. s = round(s,10);
  396. s = trimZeros(s);
  397. }
  398. else if (x > 1) { // construct exponential form with positive exponent
  399. long power = (long)Math.floor(Math.log(x)/Math.log(10));
  400. String exp = "E" + power;
  401. int numlength = 10 - exp.length();
  402. x = x / Math.pow(10,power);
  403. s = String.valueOf(x);
  404. s = round(s,numlength);
  405. s = trimZeros(s);
  406. s += exp;
  407. }
  408. else { // constuct exponential form
  409. long power = (long)Math.ceil(-Math.log(x)/Math.log(10));
  410. String exp = "E-" + power;
  411. int numlength = 10 - exp.length();
  412. x = x * Math.pow(10,power);
  413. s = String.valueOf(x);
  414. s = round(s,numlength);
  415. s = trimZeros(s);
  416. s += exp;
  417. }
  418. if (neg)
  419. return "-" + s;
  420. else
  421. return s;
  422. }
  423.  
  424. private static String trimZeros(String num) { // used by realToString
  425. if (num.indexOf('.') >= 0 && num.charAt(num.length() - 1) == '0') {
  426. int i = num.length() - 1;
  427. while (num.charAt(i) == '0')
  428. i--;
  429. if (num.charAt(i) == '.')
  430. num = num.substring(0,i);
  431. else
  432. num = num.substring(0,i+1);
  433. }
  434. return num;
  435. }
  436.  
  437. private static String round(String num, int length) { // used by realToString
  438. if (num.indexOf('.') < 0)
  439. return num;
  440. if (num.length() <= length)
  441. return num;
  442. if (num.charAt(length) >= '5' && num.charAt(length) != '.') {
  443. char[] temp = new char[length+1];
  444. int ct = length;
  445. boolean rounding = true;
  446. for (int i = length-1; i >= 0; i--) {
  447. temp[ct] = num.charAt(i);
  448. if (rounding && temp[ct] != '.') {
  449. if (temp[ct] < '9') {
  450. temp[ct]++;
  451. rounding = false;
  452. }
  453. else
  454. temp[ct] = '0';
  455. }
  456. ct--;
  457. }
  458. if (rounding) {
  459. temp[ct] = '1';
  460. ct--;
  461. }
  462. // ct is -1 or 0
  463. return new String(temp,ct+1,length-ct);
  464. }
  465. else
  466. return num.substring(0,length);
  467.  
  468. }
  469. private static void dumpString(String str, int w) { // output string to console
  470. for (int i=str.length(); i<w; i++)
  471. out.print(' ');
  472. for (int i=0; i<str.length(); i++)
  473. if ((int)str.charAt(i) >= 0x20 && (int)str.charAt(i) != 0x7F) // no control chars or delete
  474. out.print(str.charAt(i));
  475. else if (str.charAt(i) == '\n' || str.charAt(i) == '\r')
  476. newLine();
  477. }
  478.  
  479. private static void errorMessage(String message, String expecting) {
  480. // inform user of error and force user to re-enter.
  481. newLine();
  482. dumpString(" *** Error in input: " + message + "\n", 0);
  483. dumpString(" *** Expecting: " + expecting + "\n", 0);
  484. dumpString(" *** Discarding Input: ", 0);
  485. if (lookChar() == '\n')
  486. dumpString("(end-of-line)\n\n",0);
  487. else {
  488. while (lookChar() != '\n')
  489. out.print(readChar());
  490. dumpString("\n\n",0);
  491. }
  492. dumpString("Please re-enter: ", 0);
  493. readChar(); // discard the end-of-line character
  494. }
  495.  
  496. private static char lookChar() { // return next character from input
  497. if (buffer == null || pos > buffer.length())
  498. fillBuffer();
  499. if (pos == buffer.length())
  500. return '\n';
  501. return buffer.charAt(pos);
  502. }
  503.  
  504. private static char readChar() { // return and discard next character from input
  505. char ch = lookChar();
  506. pos++;
  507. return ch;
  508. }
  509.  
  510. private static void newLine() { // output a CR to console
  511. out.println();
  512. out.flush();
  513. }
  514.  
  515. private static boolean possibleLinefeedPending = false;
  516.  
  517. private static void fillBuffer() { // Wait for user to type a line and press return,
  518. // and put the typed line into the buffer.
  519. StringBuffer b = new StringBuffer();
  520. out.flush();
  521. try {
  522. int ch = in.read();
  523. if (ch == '\n' && possibleLinefeedPending)
  524. ch = in.read();
  525. possibleLinefeedPending = false;
  526. while (ch != -1 && ch != '\n' && ch != '\r') {
  527. b.append((char)ch);
  528. ch = in.read();
  529. }
  530. possibleLinefeedPending = (ch == '\r');
  531. if (ch == -1) {
  532. System.out.println("\n*** Found an end-of-file while trying to read from standard input!");
  533. System.out.println("*** Maybe your Java system doesn't implement standard input?");
  534. System.out.println("*** Program will be terminated.\n");
  535. throw new RuntimeException("End-of-file on standard input.");
  536. }
  537. }
  538. catch (IOException e) {
  539. System.out.println("Unexpected system error on input.");
  540. System.out.println("Terminating program.");
  541. System.exit(1);
  542. }
  543. buffer = b.toString();
  544. pos = 0;
  545. }
  546.  
  547. private static void emptyBuffer() { // discard the rest of the current line of input
  548. buffer = null;
  549. }
  550.  
  551.  
  552. } // end of class Console

[edit] sorry I didn't realise you were using integers instead of strings[/edit]
*Voted best profile in the world*
Reply With Quote Quick reply to this message  
Join Date: Feb 2006
Posts: 21
Reputation: webmasts is an unknown quantity at this point 
Solved Threads: 0
webmasts webmasts is offline Offline
Newbie Poster

Re: Finding length

 
0
  #4
Mar 28th, 2006
Originally Posted by masijade
try this

  1. if (Math.abs(number / 10) < 1000) {
  2. error message
  3. }

since a five digit number will be at least 10000 or -10000

probably a little quicker than converting to string and evaluating
its length as well.
Whenever there is less than 5 digits, I'm still getting the following message:

Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at _uesJavaRun.main(_uesJavaRun.java:29)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:558)
at palindrome.main(palindrome.java:26)
... 5 more

What am I doing wrong?
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 5,273
Reputation: iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold 
Solved Threads: 378
Featured Poster
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Posting Expert

Re: Finding length

 
0
  #5
Mar 28th, 2006
Can you get this basic program to compile and execute properly?


  1. class Salut{
  2. public static void main(String[] args){
  3. String greeting = "salut monde";
  4. System.out.println(greeting);
  5. }
  6. }

If not you probably have your paths set up incorrectly. If this is the case check out the read_me files that came with whatever IDE you are using. Gotta Walk before you can run.
*Voted best profile in the world*
Reply With Quote Quick reply to this message  
Join Date: Feb 2006
Posts: 21
Reputation: webmasts is an unknown quantity at this point 
Solved Threads: 0
webmasts webmasts is offline Offline
Newbie Poster

Re: Finding length

 
0
  #6
Mar 28th, 2006
Originally Posted by iamthwee
Can you get this basic program to compile and execute properly?


  1. class Salut{
  2. public static void main(String[] args){
  3. String greeting = "salut monde";
  4. System.out.println(greeting);
  5. }
  6. }

If not you probably have your paths set up incorrectly. If this is the case check out the read_me files that came with whatever IDE you are using. Gotta Walk before you can run.
Yeah, it's working. Someone gave me a tip on using the % and / to compare the length. Any example? Thanks!
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 5,273
Reputation: iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold 
Solved Threads: 378
Featured Poster
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Posting Expert

Re: Finding length

 
0
  #7
Mar 28th, 2006
Originally Posted by webmasts
Yeah, it's working. Someone gave me a tip on using the % and / to compare the length. Any example? Thanks!
You're definitely on the right lines however, it is difficult to explain without providing a complete solution. Try it yourself kiddo, then come back wen u have sum sudo code or something.
*Voted best profile in the world*
Reply With Quote Quick reply to this message  
Join Date: Jun 2004
Posts: 2,108
Reputation: server_crash is on a distinguished road 
Solved Threads: 18
server_crash server_crash is offline Offline
Postaholic

Re: Finding length

 
0
  #8
Mar 28th, 2006
Why are you worrying about finding the length when it's still an integer? Convert it to a string. You'll have to do so sooner or later until you decide to do it some hard way:

  1. StringBuffer sb = new StringBuffer(string);
  2. newstring = sb.reverse();
  3.  
  4. if (string.equals(newstring) )
  5. {
  6. //palindrome
  7. }

all the code you need.
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 5,273
Reputation: iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold 
Solved Threads: 378
Featured Poster
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Posting Expert

Re: Finding length

 
0
  #9
Mar 28th, 2006
>all the code you need.

No I don't think so. I think the purpose of his assignment is to think of a way to check if an integer is a palindrome using the modulus and division operators.

I don't think he is even allowed to convert it to strings. He is just confused as to how to ascertain how many digits there are in a given integer... and is going down the string.length() avenue because he doesn't know any better.

Here's a hint to find out how many digits are in an integer:

>keep dividing the integer by ten until it gets to zero, each time incrementing a counter.
*Voted best profile in the world*
Reply With Quote Quick reply to this message  
Join Date: Jun 2004
Posts: 2,108
Reputation: server_crash is on a distinguished road 
Solved Threads: 18
server_crash server_crash is offline Offline
Postaholic

Re: Finding length

 
0
  #10
Mar 28th, 2006
No, it's all the code you need. At least I wouldn't need to do anymore. Of course it's like you said, it probably wasn't his assignment.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Java Forum
Thread Tools Search this Thread



Tag cloud for Java
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC