what is the problem in the following code?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • phpuser123
    New Member
    • Dec 2009
    • 108

    what is the problem in the following code?

    # import java.io.IOExcep tion;
    #
    # class Toread
    # {
    # public static void main(String args[])
    # {
    # int x;
    # System.out.prin tln("Enter a digit");
    # try
    # {
    # x= System.in.read( );
    # System.out.prin tln("Entered Value:"+x);
    # }
    # catch(IOExcepti on e)
    # {
    # System.out.prin tln("You had entred wrong value");
    # }
    # }
    #
    # }

    When I try to read a value and print it its not projecting the same i dont understand what is the mistake i am giving the code which i tried to compile

    When i try to compile the output is this way
    Enter a digit: 1
    Entered Value :50
  • rotaryfreak
    New Member
    • Oct 2008
    • 74

    #2
    um, i have no idea why its giving you the answer it is. i tried your code out for myself inputting 12 and the program would echo 49.

    i have always been shown to grab user input using the Scanner class and creating a scanner object
    Code:
    import java.util.Scanner;
    
    public class ToRead {
    
    	public static void main(String[] args) {
    		Scanner kb = new Scanner(System.in);
    		int x;
    		System.out.println("Enter a digit");
    		try {
    			x = kb.nextInt();
    			System.out.println("Entered Value:" + x);
    		} catch (Exception e) {
    			System.out.println("You had entred wrong value");
    		}
    	}
    }
    now, when i try to input 12, it echos the inputted number, 12.

    You should check out the scanner class, it's quite useful and has lots of features for grabbing user input from keyboard, etc. etc.

    Java Scanner Class

    hope this helps :)

    Comment

    • newlearner
      New Member
      • May 2007
      • 67

      #3
      Code:
      import java.io.BufferedReader;
      import java.io.InputStreamReader;
      
      
      public class SysRead {
      	public static void main(String[] args) { 
      		String x; 
      		System.out.println("Enter a digit"); 
      		try { 
      			BufferedReader x1 = new BufferedReader(new InputStreamReader(System.in));
      			System.out.println("Entered Value:" + Integer.parseInt(x1.readLine())); 
      		} catch (Exception e) { 
      			System.out.println("You had entred wrong value"); 
      		} 
      	} 
      }
      Try this out.... hope ul understand the difference

      Comment

      • Oralloy
        Recognized Expert Contributor
        • Jun 2010
        • 988

        #4
        BTW, 50 is the (decimal) ASCII value for '2'. Check your input once again.

        What your program is doing is reading the raw byte, hoisting that value to an integer, and then string converting the integer to generate your output.

        Your code likely would have worked if you'd declared 'x' as a char.

        Comment

        Working...