Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Java:Tutorial - User Input

java user input

  • Please log in to reply
8 replies to this topic

#1 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 09 December 2006 - 05:25 PM

Personally I’m a little bored with the basics; especially since they hardly do anything of use. This tutorial will attempt to show you how to prompt the user for input and then have your program perform a basic operation with that input. Before reading this tutorial, you should have a basic understanding of flow control and operators.

The first thing I am going to do is create a new package called math. By naming conventions, all characters in package names are lowercase. Within the math package I am going to create a new class called CelsiusToKelvin. Again sticking with the naming conventions, the class name starts with an uppercase letter and each subsequent word is capitalized. We are going to create our constructor and our main method which instantiates our class. Note I included comments which are denoted by two forward slashes “//” everything to the right of those is considered a comment and is ignored by the compiler. At this point your code should look something like this, with out the comments:

package math;//package declaration
public class CelsiusToKelvin {//class header

     public CelsiusToKelvin(){ //constructor header
     }

     public static void main (String[] args){//main
     new CelsiusToKelvin();//instantiation
     }
}
At this point, it is a good idea to step back and examine the properties in the domain of your application. Our goal is to create a program that prompts the user for input, takes his input stores it as a variable, performs a basic calculation and creates a new converted variable. We can assume we are going to need two variables, a Kelvin value and a Celsius variable. So not let’s declare them:
package math;//package declaration
public class CelsiusToKelvin {//class header
     
     double celsiusValue = 0.0; //declares celsiusValue as a double variable
     double kelvinValue = 0.0; //declares kelvinValue as a double variable
    
     public CelsiusToKelvin(){ //constructor header
     }

     public static void main (String[] args){//main
     new CelsiusToKelvin();//instantiation
     }
}
Now we want to “get” data from a user. To do that we take advantage of a class available to us

String userInput = JOptionPane.showInputDialog("Enter a Celsius Value");
At this point it’s a good idea to create a debug statement to make sure your program is actually receiving input from the user. So lets just print what they enter by adding the System.out.println after the input dialog.

package math;//package decleration

import javax.swing.JOptionPane;

public class CelsiusToKelvin {//class header

     double celsiusValue = 0.0; //declares celsiusValue as a double variable
     double kelvinValue = 0.0; //declares kelvinValue as a double variable
    
     public CelsiusToKelvin(){ //constructor header
          String userInput = JOptionPane.showInputDialog("Enter a Celsius Value");
          System.out.println(userInput);
     }
     
     public static void main (String[] args){//main
     new CelsiusToKelvin();//instantiation
     }
}
However, if you haven’t noticed we have a problem. When the user enters a value, it is returned as a string, and because Java is pickey, you cant perform mathematical operations on strings. So we now need to make use of another class available to us.
We now add this line:

celsiusValue = Double.parseDouble(userInput);
We are now going to program our equation and we are finished.

package math;//package decleration

import javax.swing.JOptionPane;

public class CelsiusToKelvin {//class header

     double celsiusValue = 0.0; //declares celsiusValue as a double variable
     double kelvinValue = 0.0; //declares kelvinValue as a double variable

     public CelsiusToKelvin(){ //constructor header

          String userInput = JOptionPane.showInputDialog("Enter a Celsius Value");
          //System.out.println(userInput);
          celsiusValue = Double.parseDouble(userInput);
          kelvinValue = celsiusValue - 273.0;
          System.out.println(kelvinValue);
     }

     public static void main (String[] args){//main
     new CelsiusToKelvin();//instantiation
     }
}

Edited by John, 18 July 2010 - 01:40 PM.

  • 1

#2 Ananta2010

Ananta2010

    CC Lurker

  • Just Joined
  • Pip
  • 9 posts

Posted 15 June 2010 - 09:34 PM

hey...i copied this program and ran it on jdk1.4......it compiled correctly but did not run....came up with a long error message sayin wrong class name...i double checked it...no use....pls. help
  • 0

#3 Guest

Guest

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 914 posts
  • Programming Language:C

Posted 19 June 2010 - 04:02 AM

hey...i copied this program and ran it on jdk1.4......it compiled correctly but did not run....came up with a long error message sayin wrong class name...i double checked it...no use....pls. help

I just removed the package math; part and it worked XD

Also +rep to John for a simple tutorial.
Posted Image
  • 0
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#4 Liam Flynn

Liam Flynn

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 13 August 2010 - 09:58 AM

Just something that bugged me but the kelvin value should have been celciusValue + 273 instead of -273. Otherwise spot on for getting me back to scratch for uni, cheers
  • -1

#5 Zer033x

Zer033x

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 50 posts
  • Programming Language:C++, C#, Lua
  • Learning:C++, C#, JavaScript, Lua, Others

Posted 19 August 2012 - 03:28 AM

Hey, thanks for the tutorial. I am new at Java, but have been using C++ for quite some time and I'm finding the way I see a lot of this java code a little confusing and/or cluttered. It seems like a lot of these java tutorials I've gone through have packed a ton of stuff into class constructors then just called new Class(); from main to execute. Is this standard for Java? The way I was always taught was to use a class to encapsulate the data and create the methods to do operations on it. I rewrote your tutorial to try to conform more to what I view as better coding practice, what do you guys think?

CelsiusToKelvin.java
package fundamentals;
import javax.swing.JOptionPane;
public class CelsiusToKelvin
{//START CLASS
		 private double m_celsiusValue;
		 private double m_kelvinValue;
		 private String m_userInput;
		
public CelsiusToKelvin()
{//START CONSTRUCTOR
			
		  m_celsiusValue = 0.0;
		  m_kelvinValue = 0.0;
		  m_userInput = null;
}
		
public void FillInput()
{
    m_userInput = JOptionPane.showInputDialog("Enter a Celsius Value");
}
public String GetStrInput()
{
    return m_userInput;
}
public Double ConvertInputStringToDouble()
{
	 m_celsiusValue = Double.parseDouble(m_userInput);
   
	 return m_celsiusValue;
}
public void InputToKelvin()
{  
    if(m_userInput != null)//If input has been filled
    {
	    m_kelvinValue = Double.parseDouble(m_userInput)+273.0;
    }
    else
    {
	    System.out.println("Must prompt user input before attempting to convert to Kelvin");
    }
   
}
public void OutputKelvin()
{
    System.out.println(m_kelvinValue);
}
}//END CLASS
	   

Main.java
package fundamentals;

public class Main {
    /**
	 * @param args the command line arguments
	 */
    public static void main(String[] args) {
	   
	    CelsiusToKelvin g_celToKelObj = new CelsiusToKelvin();
	   
	    g_celToKelObj.FillInput();
	   
	    g_celToKelObj.InputToKelvin();
	   
	    g_celToKelObj.OutputKelvin();
    }
}

  • 0

#6 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 20 August 2012 - 02:38 AM

- You have weird (but legal) variable names for Java.
- Your method names cannot start with a capital letter (illegal)
- Getters are normally called "getVariableName"
private String GetStrInput() {
return m_userInput;
}
(and notice this method isn't used)

convertInputStringToDouble isn't used either.

Personally I would not write all the methods you wrote. Or at least not public.
Because now you can first call inputToKelvin, without having done fillInput, and convertInputStringToDouble.

The way the class works, those 3 methods should always be executed in the same order, or else the program will
give weird results. So don't allow it to do so.

Note how I did not write the constructor because zeros, and nulls are the default values for primitive numbers and objects.

import javax.swing.JOptionPane;

public class CelsiusToKelvin {
    private double kelvinValue;
    private String userInput;

    public void askAndConvertUserInput(){
        fillInput();
        inputToKelvin();
        outputKelvin();
    }

    private void fillInput() {
        userInput = JOptionPane.showInputDialog("Enter a Celsius Value");
    }

    private void inputToKelvin() {
        if (userInput != null) {
            kelvinValue = Double.parseDouble(userInput) + 273.0;
        } else {
            System.out.println("Must prompt user input before attempting to convert to Kelvin");
        }

    }

    private void outputKelvin() {
        System.out.println(kelvinValue);
    }
}

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

                CelsiusToKelvin celsiusToKelvin = new CelsiusToKelvin();

                celsiusToKelvin.askAndConvertUserInput();
        }
}





But personally, I would probably end up with something like
import javax.swing.JOptionPane;

public class CelsiusToKelvin {
    public static void askAndConvertUserInput(){
        String celsius = JOptionPane.showInputDialog("Enter a Celsius Value");
        if (celsius != null && celsius.matches("\\d+")) {
            int kelvin = TemperatureConverter.celsiusToKelvin(Integer.parseInt(celsius));
            System.out.println("kelvin: " + kelvin);
        } else {
            System.out.println("Must prompt user input before attempting to convert to Kelvin");
        }
    }
}
Main:

public class Main {

    public static void main(String[] args) {

        CelsiusToKelvin celsiusToKelvin = new CelsiusToKelvin();

        celsiusToKelvin.askAndConvertUserInput();
    }
}
Utility class:
public class TemperatureConverter {
    public static int celsiusToKelvin(int celsius) {
        return celsius + 273;
    }

    public static int kelvinToCelsius(int kelvin) { 
        return kelvin - 273;
    }
}

  • 0

#7 Orjan

Orjan

    CC Mentor

  • Moderator
  • 2918 posts
  • Location:Karlstad, Sweden
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Pascal
  • Learning:Java, C#

Posted 20 August 2012 - 03:06 AM

- Your method names cannot start with a capital letter (illegal)

Methods can be capitalized in Java, but it's not recommended.
  • 0

I'm a System developer at XLENT Consultant Group mainly working with SugarCRM.
Please DO NOT send mail or PM to me with programming questions, post them in the appropriate forum instead, where I and others can answer you.


#8 Zer033x

Zer033x

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 50 posts
  • Programming Language:C++, C#, Lua
  • Learning:C++, C#, JavaScript, Lua, Others

Posted 20 August 2012 - 05:01 PM

@ Wim DC

Yea optimization of the class wasn't really what my point was. I know there were methods that were unused and I know InputToKelvin could be called prior to asking user for data which is why I added the check to see if it was entered yet. The point was though is that I've noticed that in a lot of these Java examples I see online people put a bunch of execution code in a class constructor then just call new Class from main to use the class which didn't seem right to me. If you're going to create a class then create a class with data members and functions/methods to work on that data then call it as an object through main and use the functions. The way you did it in both examples looks fine to me as all the operations are in a function that can be used from an object.

- You have weird (but legal) variable names for Java.
- Your method names cannot start with a capital letter (illegal)
- Getters are normally called "getVariableName"


As for my variable names when I use C++ I usually prefix with m_ if they're member variables within a class and g_ for global variables, m_p or g_p if they're pointers, and no prefix for temp variables in some loop/function scope or something. It's just what I'm used to.

Method names I've always started with capital so I can differentiate them easily from variables of which I start lower case and do camel case on.

Never really had a way of doing getters other than just get and then the item I wanted to get, but not necessarily the variable name exactly.

Why isn't it recommended to start methods with capital?
  • 0

#9 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 20 August 2012 - 10:23 PM

Why isn't it recommended to start methods with capital?

Cause it's all in the naming conventions: http://www.oracle.co...toc-136057.html
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download