Welcome Guest ( Log In | Register )



 
Reply to this topicStart new topic
> Need Help: Find Lowest Character Using Java
cyph3r
post Oct 19 2005, 01:29 PM
Post #1


Advanced Member
Group Icon

Group: Members
Posts: 116
Joined: 3-August 05
From: The Digital Arena !
Member No.: 7,604



Heya guys,

Been a looooong time eh, yeah well i was kinda buzy with college stuff and all those assignments just keep pouring in. I have java this semester and i have "NO" idea how to go abt it, 1 reason being that my proff. is going real fast in the explaination part and i doubt she knows anything in java blink.gif

Newayz , i was asked to do a small program in java , heres how it goes :

I need to enter a word prefixed by the number of letters in it, and the output should show me the smallest character in that word.
eg: 5Hello .... Smallest character is : e

We were started off in studio .net and i have again no idea of how that works .. but playing around a bit made me get used to a few controls. This is how i started off , but i duno how to continue , could someone please point out any mistake and give me any ideas or better off , just give me ideas and not the whole program so i would try it myself , i am really bad at logic sad.gif i know that suc*s .. but err .. i need to pass out oof this subject and get rid of this annoying proff. i have ...

CODE
package smallchar;
import java.io.*;
import java.awt.*;
/**
* Summary description for Class1.
*/
public class Class1
{
public Class1()
{
 //
 // TODO: Add Constructor Logic here
 //
}

/** @attribute System.STAThread() */
public static void main(String[] args) throws IOException
{
 DataInputStream n=new DataInputStream(System.in);
 String ch;
 String a;
 char small;
 int p;
 System.out.println("Enter The String After Entering The Number Of Characters");
 ch=n.readLine();
 int i;
 a=ch.substring(0,1);
 p=Integer.parseInt(a);
 small=ch.charAt(1);
 for (i=2;i<p;i++)


...... How do i proceed with the for loop ? i really have no idea ..

Thankx in advance
Dhanesh

This post has been edited by microscopic^earthling: Oct 21 2005, 05:03 PM
Go to the top of the page
 
+Quote Post
miCRoSCoPiC^eaRt...
post Oct 21 2005, 05:03 PM
Post #2


PsYcheDeLiC dR3aMeR
Group Icon

Group: Admin
Posts: 2,242
Joined: 29-January 05
From: Nakorn Chaisri, Thailand
Member No.: 2,411
myCENTs:84.36



You were on the right track but not quite.

First of all you really don't need the package statement, unless you want to classify your code in a separate namespace. But anyway, no harm with that. Besides if you're using Visual Studio.NET, this will be added automatically. Also you don't need to import java.awt - that's the Abstract Windowing Toolkit - which you need only when you are designing Windows based Appz with a GUI.

CODE
package smallchar;
import java.io.*;
import java.awt.*;


This part is fine... although you might consider naming your class something meaningful, instead of simply Class1
CODE

/**
* Summary description for Class1.
*/
public class Class1
{
public Class1()
{
 //
 // TODO: Add Constructor Logic here
 //
}


You don't really need to add that throws IOException to your main - it will do so in any case.

CODE

/** @attribute System.STAThread() */
public static void main(String[] args) throws IOException
{


The part below this is really messed up. You can use DataInputStream to read in your line, but I'd advise you to use a subroutine that I use to fetch lines for me.. works like a charm.
Here it goes:
CODE

   public String readLine( )
   {
       char nextChar;
       String result = "";
       boolean done = false;

       while (!done)
       {
           nextChar = readChar( );
           if (nextChar == '\n')
              done = true;
           else if (nextChar == '\r')
           {
               //Do nothing.
               //Next loop iteration will detect '\n'.
           }
           else
              result = result + nextChar;
       }

       return result;
   }


=============================================
String ch;
String a;
char small;
int p;
System.out.println("Enter The String After Entering The Number Of Characters");
ch=n.readLine();
int i;
a=ch.substring(0,1);
p=Integer.parseInt(a);
small=ch.charAt(1);
for (i=2;i<p;i++)[/code]
=============================================
As for this messed up part... I wouldn't go into rectifying it - but rather am providing you with a full sample program that would do what you're trying to do.

Full Sample
CODE

package LowestChar;
import java.io.*;
import java.util.*;

/**
* Summary description for Class1.
*/
public class LowestChar
{
public LowestChar()
{
 //
 // TODO: Add Constructor Logic here
 //
}

/** @attribute System.STAThread() */
public static void main(String[] args)
{

 // Variables
 String line;
 int Lowest = 128, Ascii = -1;  // To keep the compiler happy

 // Prompt
 System.out.println ("Enter a line of text: ");

 // Read Line
 line = readLine ();
         
 // Loop through each character of the string and find which is the lowest
 for ( int Count = 0; Count < line.length(); Count ++ )
 {
  // This is the step that gets you the lowest value
  // Every time Count increment, a new character is taken into consideration
  // String.charAt (Position) gives you the particular character at that position of the string
  // Type casting it to 'int', by: (int) character - gives you the Ascii value of that character
  // You store that in Ascii and compare to lowest. If it is lower than the lowest value, make Lowest
  // equal to that character and loop again.
  Ascii = (int) line.charAt(Count);

  if ( Ascii < Lowest )
   Lowest = Ascii;

 }

 // Print out the lowest char by type casting the integer value back to char
 System.out.println ( "Lowest Character: " + (char) Lowest );

}


// Method to read in a line of text
public static String readLine( )
{
 char nextChar;
 String result = "";
 boolean done = false;

 // Loop till enter/newline character is met
 while (!done)
 {
  nextChar = readChar( );
  if (nextChar == '\n')
   done = true;
  else if (nextChar == '\r')
  {
   //Do nothing.
   //Next loop iteration will detect '\n'.
  }
  else
   result = result + nextChar;
 }

 // Return the string
 return result;

} // end readLine

// Method to read a Character
public static char readChar( )
{

 int charAsInt = -1;   // Keep the compiler happy
 
 try
 {
  // Read the character as integer
  charAsInt = System.in.read( );
 }
 catch(IOException e)
 {
  System.out.println(e.getMessage( ));
  System.out.println("Fatal error. Ending program.");
  System.exit(0);
 }

 // Return the character
 return (char)charAsInt;

} // end readChar

} // end class



NOTE: Keep in mind that this wouldn't return the lowest char as you've shown. The lowest char is actually the character with the lowest ASCII value. The lowest values will be that of Numbers followed by CAPITAL Alphabet and then small Alphabet. This should help you out in what you are trying to achieve. Feel free to modify the code to suit your needs.
Go to the top of the page
 
+Quote Post
cyph3r
post Oct 23 2005, 08:07 PM
Post #3


Advanced Member
Group Icon

Group: Members
Posts: 116
Joined: 3-August 05
From: The Digital Arena !
Member No.: 7,604



First off ... Welcome Back ! smile.gif Had a nice vacation i see .. hehe

Do u NOT know anything ? Jeez I least expected you to reply , and wow what a timing. Thankx a bunch for the quick reply.

About the code, well i gave ur code a nice look and tried doing the thing on my own, well it took some time to get it right, but finally came up with the solution, i checked up with my proff at college ( belive me i hate that woman to the core ) , she had like a million problems with it, its like " I dont want u to do it the easy way and use pre frunctions .. write your own and do it " HELL !

Newayz , this was the final outcome

/** @attribute System.STAThread() */
public static void main(String[] args)throws IOException
{
DataInputStream n=new DataInputStream(System.in);
String ch;
String l;
String a;
char small;
int p;
System.out.println("Enter The String After Entering The Number Of Characters");
ch=n.readLine();
int i;
a=ch.substring(0,1);
p=Integer.parseInt(a);
small=ch.charAt(1);
for (i=2;i<p;i++)
{
if(small>ch.charAt(i))
small=ch.charAt(i);
}

System.out.println("\n Smallest Character");
System.out.println(small);

l=n.readLine();
}
}

I got an idea from ur code and used it in the one i did, hope that isnt a problem. The only thing bothering me is that .. what is "throws IOException" i know its one of the components of import java.io, but in this case as u said it will do it any ways .. How does that happen ? I mean dont we have to define every bit of code supporter while programming ?

Please pardon me for being so pestering , but i really duno this subject that well , i mean javascript was fine , it was fun and cool , but this is just crazy, either i need a good teacher or i need a good book. I rather consider myself to be a Hardware Freek than a software one.

Thankx for the Reply and i guess m done with this bit of program smile.gif just working on the palindrome program now .. blink.gif ughh

Regards
Dhanesh
Go to the top of the page
 
+Quote Post
evought
post Oct 23 2005, 11:55 PM
Post #4


Premium Member
Group Icon

Group: Members
Posts: 200
Joined: 3-October 05
From: Missouri
Member No.: 8,888
myCENTs:71.12



QUOTE(cyph3r @ Oct 23 2005, 03:07 PM)
<snip...>

I got an idea from ur code and used it in the one i did, hope that isnt a problem. The only thing bothering me is that .. what is "throws IOException" i know its one of the components of import java.io, but in this case as u said it will do it any ways .. How does that happen ? I mean dont we have to define every bit of code supporter while programming ?

Please pardon me for being so pestering , but i really duno this subject that well , i mean javascript was fine , it was fun and cool , but this is just crazy, either i need a good teacher or i need a good book. I rather consider myself to be a Hardware Freek than a software one.

Thankx for the Reply and i guess m done with this bit of program smile.gif just working on the palindrome program now ..  blink.gif ughh

Regards
Dhanesh
*



"throws IOException" tells the compiler that the method is allowed to throw an Exception derived from IOException to indicate a problem. When an exception is thrown, it travels up the stack, back through all the methods that have been called until it reaches a "catch" statement which handles it. If there is no 'catch', the exception goes all the way up to main and exits the program.

The reason you do not need it in your case is that the method you were adding it to *was* main. There is no where else for the exception to go, so do not bother declaring it. If an exception is thrown in main, it will jsut exit the program anyway.

If you wanted to handle the error in some way, like printing put a message or giving the user another chance, you would put the read calls inside a try...catch block.
Go to the top of the page
 
+Quote Post
cyph3r
post Oct 24 2005, 06:56 PM
Post #5


Advanced Member
Group Icon

Group: Members
Posts: 116
Joined: 3-August 05
From: The Digital Arena !
Member No.: 7,604



QUOTE(evought @ Oct 24 2005, 04:55 AM)
"throws IOException" tells the compiler that the method is allowed to throw an Exception derived from IOException to indicate a problem. When an exception is thrown, it travels up the stack, back through all the methods that have been called until it reaches a "catch" statement which handles it. If there is no 'catch', the exception goes all the way up to main and exits the program.

The reason you do not need it in your case is that the method you were adding it to *was* main. There is no where else for the exception to go, so do not bother declaring it. If an exception is thrown in main, it will jsut exit the program anyway.

If you wanted to handle the error in some way, like printing put a message or giving the user another chance, you would put the read calls inside a try...catch block.
*



Hey evought .. thankx for the explaination smile.gif , kinda understood what it really does , wished i had a better proffessor to teach sad.gif .. newayz have to live with it tho .. I need to pass out of this semester ! Sheesh .. i sound desperate ! rolleyes.gif
Go to the top of the page
 
+Quote Post
miCRoSCoPiC^eaRt...
post Oct 25 2005, 12:24 PM
Post #6


PsYcheDeLiC dR3aMeR
Group Icon

Group: Admin
Posts: 2,242
Joined: 29-January 05
From: Nakorn Chaisri, Thailand
Member No.: 2,411
myCENTs:84.36



No problem at all - that's why I told you, that I'll give you a basic working code - just modify it to suit your needs. Also good explanation of the IOException, evought. Couldn't have done it better myself.

Dhanesh - it's like speaking in english terms, Exceptions are thrown, when something exceptional occurs - i.e. something out of the ordinary, an event that isn't supposed to happen during the normal flow of your code. To handle such scenarios we use the exception catchers in the form of a try..catch.. block. Exception itself is a base class, sort of a mother of all exception classes, which is thrown when some error occurs. When you write code to deal with a particular type of exception, you usually inherit the exception class and modify it to suit your needs.

When it comes to your void main() - it is already pre-taught to throw the IOException. That is why, it is not really necessary to add the code to it - although it doesn't do any harm. If it was for some other sub-routine, then yeah, of course, you'd have to add it, to inform the subroutine that it is to throw a particular type of exception when a problem occurs.

If you face any more tough java nuts to crack, post 'em all here. Haven't touched Java in a long while - would be fun again brushing up my skills smile.gif

Regards,
m^e
Go to the top of the page
 
+Quote Post
BitShift
post May 9 2006, 10:09 PM
Post #7


Advanced Member
Group Icon

Group: Members
Posts: 153
Joined: 8-May 06
From: Houston, TX
Member No.: 13,291



My computer teacher told me that although "throwing" and exception is handy, its a bad idea.

He said always use the try..catch block


try
{
//code here
}
catch(Exception exc){}
Go to the top of the page
 
+Quote Post
iGuest
post Aug 27 2008, 02:17 PM
Post #8


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 0
Joined: 1-November 07
Member No.: 25,869



character
Need Help: Find Lowest Character Using Java

Do you NOT know anything ? Jeez I least expected you to reply , and wow what a timing. Thankx a bunch for the quick reply.

About the code, well I gave your code a nice look and tried doing the thing on my own, well it took some time to get it right, but finally came up with the solution, I checked up with my proff at college ( belive me I hate that woman to the core ) , she had like a million problems with it, its like " I don't want you to do it the easy way and use pre frunctions .. Write your own and do it " HELL !

Newayz , this was the final outcome

/** @attribute System.STAThread() */
Public static void main(String[] args)throws IOException
{
DataInputStream and=new DataInputStream(System.In);
String ch;
String l;
String a;
Char small;
Int p;
System.Out.Println("Enter The String After Entering The Number Of Characters");
Ch=and.ReadLine();
Int I;
A=ch.Substring(0,1);
P=Integer.ParseInt(a);
Small=ch.CharAt(1);
For (I=2;I<p;I++)
{
If(small>ch.CharAt(I))
Small=ch.CharAt(I);
}

System.Out.Println("\and Smallest Character");
System.Out.Println(small);

L=and.ReadLine();
}
}

I got an idea from your code and used it in the one I did, hope that isnt a problem. The only thing bothering me is that .. What is "throws IOException" I know its one of the components of import java.Io, but in this case as you said it will do it any ways .. How does that happen ? I mean don't we have to define every bit of code supporter while programming ?

Please pardon me for being so pestering , but I really duno this subject that well , I mean javascript was fine , it was fun and cool , but this is just crazy, either I need a good teacher or I need a good book. I rather consider myself to be a Hardware Freek than a software one.

Thankx for the Reply and I guess m done with this bit of program just working on the palindrome program now .. Ughh

Regards
Kuljeet

-reply by kuljeet
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic

Collapse

> Similar Topics

Topics Topics
  1. java.lang.NullPointException(4)
  2. Using system date in java... How?(5)
  3. Java Unlimited(14)
  4. Array Sorting(21)
  5. What Are The Advantages Of Java Vs C++?(15)
  6. Download Java Ebooks(15)
  7. Java By Example(8)
  8. Video Streaming In Web Browser Through Java Or Jsp(1)
  9. Looking For A Java IDE(25)
  10. On Why Java Is 'c'ooler!(10)
  11. Other Sound Format Support(3)
  12. Java Phone Book(2)
  13. How To Create Exe File In Java?(13)
  14. How Do I Test A Java Aplication(11)
  15. Mozilla And Java!(2)
  1. Need To Modify Xml Attribute Using Java(4)
  2. Bluetooth And Java(5)
  3. Java Sdk Vs. Java Jdk?(2)
  4. Graphcal User Interfaces In Java(4)
  5. Java Db Help Pls(2)
  6. Loading 3d Models In Java?(2)
  7. Java Applet Loading Error(5)
  8. Setting Up Java Correctly(8)
  9. Java Java.security.accesscontrolexception(6)
  10. Simple Java Question(3)
  11. Java And Sql: Data Mismatch(6)
  12. Java Memory Leak?(2)
  13. Java Mouse Movement.(2)


 



- Lo-Fi Version Time is now: 5th December 2008 - 01:23 AM