Hey guys! Ok, so my problem is that I'm trying to add something that says "num1 does not equal 'a number'" I want it to read any number I put it, but not anything that isn't a number. If I can figure this part out, it should loop where I want it to, and my code will be finally finished! Here is the specific part that I need help. Thanks so much!

    do
        {
            System.out.print ("Type the number of degrees.\nThen, press enter.\n->");

            num1=Keyboard.readDouble();
        }
        while(num1!=???????????????????????????????????????????????????????????);

Recommended Answers

All 20 Replies

What package is the Keyboard class in? I don't recognize it as part of Java SE and don't have any doc for what it does.

num1 !=

will just check your num against a Single value, not against every possible number. can you show your entire code there and the exact error message?

what exactly is Keyboard? is it a class? is it an instance of Scanner?

.

Well, here it is. stultuske, that is exactly what I'm trying to do, make it so that if num1!=any number, then I can loop that portion. If you notice, I did the same type of loop before.

There really isnt an error message because I really dont even know what to type in for the value of num1.

//=====================================================
//This program will convert various temperature units.
//=====================================================
public class Temperature_Converter
{
    public static void main(String[]args)
    {
        char c, f, k, y, n;
        double num1;
//=====================================================================================================================
//"while(true)" is the top of the loop; "y=='y'"{"continue;" is the bottom of the loop. This loops the entire program.
//=====================================================================================================================
        while(true)
        {
            System.out.print ("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            System.out.println ("Welcome to the temperature converter!");
//==============================================================================================================================
//"do" is the top of the loop; "while(!(c=='c' || c=='f' || c=='k'));" is the bottom of the loop. This loops the unit selection
// in the case of there being an error, such as inappropriate input.
//==============================================================================================================================
            do
            {
//==============================================================================================================================
//Prompts the user for selection of the temperature unit that they would like to convert from. Accepts the input of c, f, or k.
//==============================================================================================================================
                System.out.println ("\nType \"c\" for conversion from Celsius, \"f\" from Fahrenheit, or \"k\" from Kelvin.");
                System.out.print ("Then, press enter.\n->");

                c=Keyboard.readString().charAt(0);
                {
//=========================================================================================================================
//"if(!(c=='c' || c=='f' || c=='k'))" recognizes if an incorrect input is entered and sends an error message in that case.
//=========================================================================================================================
                    if(!(c=='c' || c=='f' || c=='k'))
                    {
                        System.out.println ("\nError! You have entered an inappropriate character. Try Again.");
                    }
                }
            }
            while(!(c=='c' || c=='f' || c=='k'));
//=================================================================================================
//Prompts the user to input the numeric value of how many degrees they would like to be converted.
//=================================================================================================
            do
            {
                System.out.print ("Type the number of degrees.\nThen, press enter.\n->");

                num1=Keyboard.readDouble();
            }
            while(num1!=?);
//==========================================================================================================================
//The "if (c=='c','f', or 'k')" statements dictate where the previous inputs are entered, along with the formulas performed.
//==========================================================================================================================
            if (c=='c')
            {
                double num2=(9.0/5.0)*num1+32.0; double num3=num1+273.15;
                System.out.println ("\n Celsius:" + num1 + " Degrees\n  ...is equal to...");
                System.out.println ("   Fahrenheit:" + num2 + " Degrees\n       or\n    Kelvin:" + num3 + " Degrees");
            }
            if (c=='f')
            {
                double num2=(num1-32.0)*(5.0/9.0); double num3=(num1+459.67)*(5.0/9.0);
                System.out.println ("\n Fahrenheit:" + num1 + " Degrees\n   ...is equal to...");
                System.out.println ("   Celsius:" + num2 + " Degrees\n      or\n    Kelvin:" + num3 + " Degrees");
            }
            if (c=='k')
            {
                double num2=(num1-273.15); double num3=(num1*(9.0/5.0))-459.67;
                System.out.println ("\n Kelvin:" + num1 + " Degrees\n   ...is equal to...");
                System.out.println ("   Celsius:" + num2 + " Degrees\n      or\n    Fahrenheit:" + num3 + " Degrees");
            }
//============================================================================================================================
//"do" is the top of the loop, while "while(!(y=='y' || y=='n'));" is the bottom. This loops the prompt to loop the entire
// program in the case of there being an error.
//============================================================================================================================
            do
            {
                System.out.print ("\nWould you like to try again?\nType \"y\" for yes or \"n\" for no.\nThen, press enter.\n->");

                y=Keyboard.readString().charAt(0);
                {
//=========================================================================================================================
//"if(!(c=='y' || c=='n'))" recognizes if an incorrect input is entered and sends an error message in that case.
//=========================================================================================================================
                    if(!(y=='y' || y=='n'))
                    {
                        System.out.println ("\nError! You have entered an inappropriate character. Try Again.");
                    }
                }
            }
            while(!(y=='y' || y=='n'));
//=============================================================
//"if (y=='y')" will complete the loop for the entire program.
//=============================================================
            if (y=='y')
            {
                continue;
            }
//==========================================================================================================================
//"if(y=='n')" will break the loop and exit the program, as well as display "Bye!" on its own separate page before exiting.
//==========================================================================================================================
            if (y=='n')
            {
                System.out.print ("\n\n\n\n\n\n\n\n\n\n\n\n                 Bye!\n\n\n\n\n\n\n\n\n\n\n\n\n");
//==================================================================================
//"try{Thread.sleep(1500L);" will make the program pause 1.5 seconds before exiting.
//==================================================================================
                try
                {
                    Thread.sleep(1500L);
                }
//==============================================================================================================
//"catch (Exception e){}" was used because the exception is rarely met, and every try needs a catch or finally.
//==============================================================================================================
                catch (Exception e){}

                break;
            }
        }
    }
}

Where is Keyboard defined? The posted code will not compile without a definition for Keyboard.

if num1!=any number

The readDouble() method should do that test. If it returns, then num1 has a valid number.
Otherwise readDouble() should throw an exception when the entered data was not a valid number.
The code should put the readDouble() in a try/catch block to handle any exceptions thrown by readDouble().

Oops, sorry, I am currently taking a course for computer science at my high school. This is my first project actually. The keyboard class is a file that was given to us; here is the code for that. If you put it in the same fodler as my code is in, it should compile. THANKS!

//package cs1;

//********************************************************************
//  Keyboard.java       Author: Lewis and Loftus
//
//  Facilitates keyboard input by abstracting details about input
//  parsing, conversions, and exception handling.
//********************************************************************

import java.io.*;
import java.util.*;

public class Keyboard
{
   //*************  Error Handling Section  **************************

   private static boolean printErrors = true;
   private static int errorCount = 0;

   //-----------------------------------------------------------------
   //  Returns the current error count.
   //-----------------------------------------------------------------
   public static int getErrorCount()
   {
      return errorCount;
   }

   //-----------------------------------------------------------------
   //  Resets the current error count to zero.
   //-----------------------------------------------------------------
   public static void resetErrorCount (int count)
   {
      errorCount = 0;
   }

   //-----------------------------------------------------------------
   //  Returns a boolean indicating whether input errors are
   //  currently printed to standard output.
   //-----------------------------------------------------------------
   public static boolean getPrintErrors()
   {
      return printErrors;
   }

   //-----------------------------------------------------------------
   //  Sets a boolean indicating whether input errors are to be
   //  printed to standard output.
   //-----------------------------------------------------------------
   public static void setPrintErrors (boolean flag)
   {
      printErrors = flag;
   }

   //-----------------------------------------------------------------
   //  Increments the error count and prints the error message if
   //  appropriate.
   //-----------------------------------------------------------------
   private static void error (String str)
   {
      errorCount++;
      if (printErrors)
         System.out.println (str);
   }

   //*************  Tokenized Input Stream Section  ******************

   private static String current_token = null;
   private static StringTokenizer reader;

   private static BufferedReader in = new BufferedReader
      (new InputStreamReader(System.in));


   //-----------------------------------------------------------------
   //  Gets the next input token assuming it may be on subsequent
   //  input lines.
   //-----------------------------------------------------------------
   private static String getNextToken()
   {
      return getNextToken (true);
   }

   //-----------------------------------------------------------------
   //  Gets the next input token, which may already have been read.
   //-----------------------------------------------------------------
   private static String getNextToken (boolean skip)
   {
      String token;

      if (current_token == null)
         token = getNextInputToken (skip);
      else
      {
         token = current_token;
         current_token = null;
      }

      return token;
   }

   //-----------------------------------------------------------------
   //  Gets the next token from the input, which may come from the
   //  current input line or a subsequent one. The parameter
   //  determines if subsequent lines are used.
   //-----------------------------------------------------------------
   private static String getNextInputToken (boolean skip)
   {
      final String delimiters = " \t\n\r\f";
      String token = null;

      try
      {
         if (reader == null)
            reader = new StringTokenizer
               (in.readLine(), delimiters, true);

         while (token == null ||
                ((delimiters.indexOf (token) >= 0) && skip))
         {
            while (!reader.hasMoreTokens())
               reader = new StringTokenizer
                  (in.readLine(), delimiters,true);

            token = reader.nextToken();
         }
      }
      catch (Exception exception)
      {
         token = null;
      }

      return token;
   }

   //-----------------------------------------------------------------
   //  Returns true if there are no more tokens to read on the
   //  current input line.
   //-----------------------------------------------------------------
   public static boolean endOfLine()
   {
      return !reader.hasMoreTokens();
   }

   //*************  Reading Section  *********************************

   //-----------------------------------------------------------------
   //  Returns a string read from standard input.
   //-----------------------------------------------------------------
   public static String readString()
   {
      String str;

      try
      {
         str = getNextToken(false);
         while (! endOfLine())
         {
            str = str + getNextToken(false);
         }
      }
      catch (Exception exception)
      {
         error ("Error reading String data, null value returned.");
         str = null;
      }
      return str;
   }

   //-----------------------------------------------------------------
   //  Returns a space-delimited substring (a word) read from
   //  standard input.
   //-----------------------------------------------------------------
   public static String readWord()
   {
      String token;
      try
      {
         token = getNextToken();
      }
      catch (Exception exception)
      {
         error ("Error reading String data, null value returned.");
         token = null;
      }
      return token;
   }

   //-----------------------------------------------------------------
   //  Returns a boolean read from standard input.
   //-----------------------------------------------------------------
   public static boolean readBoolean()
   {
      String token = getNextToken();
      boolean bool;
      try
      {
         if (token.toLowerCase().equals("true"))
            bool = true;
         else if (token.toLowerCase().equals("false"))
            bool = false;
         else
         {
            error ("Error reading boolean data, false value returned.");
            bool = false;
         }
      }
      catch (Exception exception)
      {
         error ("Error reading boolean data, false value returned.");
         bool = false;
      }
      return bool;
   }

   //-----------------------------------------------------------------
   //  Returns a character read from standard input.
   //-----------------------------------------------------------------
   public static char readChar()
   {
      String token = getNextToken(false);
      char value;
      try
      {
         if (token.length() > 1)
         {
            current_token = token.substring (1, token.length());
         } else
            current_token = null;

         value = token.charAt (0);
      }
      catch (Exception exception)
      {
         error ("Error reading char data, MIN_VALUE value returned.");
         value = Character.MIN_VALUE;
      }

      return value;
   }

   //-----------------------------------------------------------------
   //  Returns an integer read from standard input.
   //-----------------------------------------------------------------
   public static int readInt()
   {
      String token = getNextToken();
      int value;
      try
      {
         value = Integer.parseInt (token);
      }
      catch (Exception exception)
      {
         error ("Error reading int data, MIN_VALUE value returned.");
         value = Integer.MIN_VALUE;
      }
      return value;
   }

   //-----------------------------------------------------------------
   //  Returns a long integer read from standard input.
   //-----------------------------------------------------------------
   public static long readLong()
   {
      String token = getNextToken();
      long value;
      try
      {
         value = Long.parseLong (token);
      }
      catch (Exception exception)
      {
         error ("Error reading long data, MIN_VALUE value returned.");
         value = Long.MIN_VALUE;
      }
      return value;
   }

   //-----------------------------------------------------------------
   //  Returns a float read from standard input.
   //-----------------------------------------------------------------
   public static float readFloat()
   {
      String token = getNextToken();
      float value;
      try
      {
         value = (new Float(token)).floatValue();
      }
      catch (Exception exception)
      {
         error ("Error reading float data, NaN value returned.");
         value = Float.NaN;
      }
      return value;
   }

   //-----------------------------------------------------------------
   //  Returns a double read from standard input.
   //-----------------------------------------------------------------
   public static double readDouble()
   {
      String token = getNextToken();
      double value;
      try
      {
         value = (new Double(token)).doubleValue();
      }
      catch (Exception exception)
      {
         error ("\nError! You have entered a character that is not a number. Try again.\n");
         value = Double.NaN;
      }
      return value;
   }
}

I also tried this: but a ".class expected" error occurred. I think I might be getting closer to the answer. By the way, I am very new at programming, so there is a lot that I still don't understand.

do
            {
                System.out.print ("Type the number of degrees.\nThen, press enter.\n->");

                num1=Keyboard.readDouble();
            }
            while(num1!=double);

I changed the part where num1!=double

I want to make it so, if you type something that isnt a double or integer, then you will have to retry the prompt, and cannot continue my program.

What does the readDouble() method do when you enter something that is not a number?

What is the variable num1 defined as? If it's a double then it will ALWAYS have a numeric value.

Look at line 312 in the code you posted. It shows what readDouble() will return.

well, that isnt my code, it was given to me, so i dont know much about it. And just test what happens when you dont enter a number by getting rid of lines 44 and 50 on my temperature converting code. it will compile and run if you do this.

If it's a double then it will ALWAYS have a numeric value.

Unless, of course its value is NaN (Java Language Spec. 4.2.3) ;)

Try this:
Add a println to print out the value of num1 after the call to readDouble(), compile and execute the code and enter a non-numeric value and see what is printed.

i know what happens when i type in a non numeric character, such as "a" or something, it says, error, you have entered and innapprorpriate character, try again. i put that message. i just want it to loop if i type soemthing other than a number in...

Did you try this:
Add a println to print out the value of num1 after the call to readDouble(), compile and execute the code and enter a non-numeric value and see what is printed for the value of num1.

When you see what is printed you will know how to code the loop.

it prints out that num1= NaN value

Ok, that's what your code can test for in the while loop. When num1 = NaN then go back and ask for another input.

ok, so the value it outputs when i dont enter a number is "Double.NaN". So i entered this as num1==Double.NaN for my loop, but now im getting an error.

"D:\ASteinheiser14\Junior\1-Computer Science\Projects\Temperature Converter\Temperature_Converter.java:50: cannot find symbol
symbol  : variable Nan
location: class java.lang.Double
            while(num1==Double.Nan);
                              ^
1 error

Tool completed with exit code 1"

Wait! i got it now... it works with the error and the loop if i type in anyhting that isnt a number, but if i type in something that is a number, it just loops without the error message... Here is my code, it should compile and run, try to tell me what you can figure out.

//=====================================================
//This program will convert various temperature units.
//=====================================================
public class Temperature_Converter
{
    public static void main(String[]args)
    {
        char c, f, k, y, n;
        double num1;
//=====================================================================================================================
//"while(true)" is the top of the loop; "y=='y'"{"continue;" is the bottom of the loop. This loops the entire program.
//=====================================================================================================================
        while(true)
        {
            System.out.print ("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            System.out.println ("Welcome to the temperature converter!");
//==============================================================================================================================
//"do" is the top of the loop; "while(!(c=='c' || c=='f' || c=='k'));" is the bottom of the loop. This loops the unit selection
// in the case of there being an error, such as inappropriate input.
//==============================================================================================================================
            do
            {
//==============================================================================================================================
//Prompts the user for selection of the temperature unit that they would like to convert from. Accepts the input of c, f, or k.
//==============================================================================================================================
                System.out.println ("\nType \"c\" for conversion from Celsius, \"f\" from Fahrenheit, or \"k\" from Kelvin.");
                System.out.print ("Then, press enter.\n->");

                c=Keyboard.readString().charAt(0);
                {
//=========================================================================================================================
//"if(!(c=='c' || c=='f' || c=='k'))" recognizes if an incorrect input is entered and sends an error message in that case.
//=========================================================================================================================
                    if(!(c=='c' || c=='f' || c=='k'))
                    {
                        System.out.println ("\nError! You have entered an inappropriate character. Try Again.");
                    }
                }
            }
            while(!(c=='c' || c=='f' || c=='k'));
//=================================================================================================
//Prompts the user to input the numeric value of how many degrees they would like to be converted.
//=================================================================================================
            do
            {
                System.out.print ("Type the number of degrees.\nThen, press enter.\n->");

                num1=Keyboard.readDouble();
            }
            while(num1!=Double.NaN);
//==========================================================================================================================
//The "if (c=='c','f', or 'k')" statements dictate where the previous inputs are entered, along with the formulas performed.
//==========================================================================================================================
            if (c=='c')
            {
                double num2=(9.0/5.0)*num1+32.0; double num3=num1+273.15;
                System.out.println ("\n Celsius:" + num1 + " Degrees\n  ...is equal to...");
                System.out.println ("   Fahrenheit:" + num2 + " Degrees\n       or\n    Kelvin:" + num3 + " Degrees");
            }
            if (c=='f')
            {
                double num2=(num1-32.0)*(5.0/9.0); double num3=(num1+459.67)*(5.0/9.0);
                System.out.println ("\n Fahrenheit:" + num1 + " Degrees\n   ...is equal to...");
                System.out.println ("   Celsius:" + num2 + " Degrees\n      or\n    Kelvin:" + num3 + " Degrees");
            }
            if (c=='k')
            {
                double num2=(num1-273.15); double num3=(num1*(9.0/5.0))-459.67;
                System.out.println ("\n Kelvin:" + num1 + " Degrees\n   ...is equal to...");
                System.out.println ("   Celsius:" + num2 + " Degrees\n      or\n    Fahrenheit:" + num3 + " Degrees");
            }
//============================================================================================================================
//"do" is the top of the loop, while "while(!(y=='y' || y=='n'));" is the bottom. This loops the prompt to loop the entire
// program in the case of there being an error.
//============================================================================================================================
            do
            {
                System.out.print ("\nWould you like to try again?\nType \"y\" for yes or \"n\" for no.\nThen, press enter.\n->");

                y=Keyboard.readString().charAt(0);
                {
//=========================================================================================================================
//"if(!(c=='y' || c=='n'))" recognizes if an incorrect input is entered and sends an error message in that case.
//=========================================================================================================================
                    if(!(y=='y' || y=='n'))
                    {
                        System.out.println ("\nError! You have entered an inappropriate character. Try Again.");
                    }
                }
            }
            while(!(y=='y' || y=='n'));
//=============================================================
//"if (y=='y')" will complete the loop for the entire program.
//=============================================================
            if (y=='y')
            {
                continue;
            }
//==========================================================================================================================
//"if(y=='n')" will break the loop and exit the program, as well as display "Bye!" on its own separate page before exiting.
//==========================================================================================================================
            if (y=='n')
            {
                System.out.print ("\n\n\n\n\n\n\n\n\n\n\n\n                 Bye!\n\n\n\n\n\n\n\n\n\n\n\n\n");
//==================================================================================
//"try{Thread.sleep(1500L);" will make the program pause 1.5 seconds before exiting.
//==================================================================================
                try
                {
                    Thread.sleep(1500L);
                }
//==============================================================================================================
//"catch (Exception e){}" was used because the exception is rarely met, and every try needs a catch or finally.
//==============================================================================================================
                catch (Exception e){}

                break;
            }
        }
    }
}

loops without the error message.

What happens when you enter bad data?

it works when i enter bad data, exactly how i wanted it to, but when i enter good data, it just loops the "please enter the degrees" prompt, but no error message.

it works when i enter bad data

What does "it works" mean? Does it loop and ask again? or what?

Are you saying that the program always loops no matter what data you enter?

Has the program ever exited the loop? What data did you enter when that happened?

Add a println to print the value of num1 that is returned by readDouble() so you can see what values you are working with and know how to code the condition in the while().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.