473,395 Members | 2,006 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Using hasNextInt()

Trying to code in hasNextInt() for data type checking. Basicall my code ask user for input and if user doesn't use an int they get an error. I know i should have a if and else statement with this.
I am trying this data type checking in this block of code and I get tons of errors

while (isValid==false)
}
System.out.print("How many Hammers? ");
if(input.hasNextInt())
{
numHammers = input.NextInt();
isValid = true;
}
else
}
input.nextLine();
System.out.println("\nError! Please enter a number!");
}
}
Jan 30 '08 #1
12 12871
Laharl
849 Expert 512MB
After the else you use a close brace, not an open one. Switch that } to a { and you'll be fine.
Jan 30 '08 #2
Thanks have fixed problem, but now I have error that my varaible might not have been intialized looking for numHammers which is my int. I new to java and trying to learn this.
Jan 30 '08 #3
r035198x
13,262 8TB
Thanks have fixed problem, but now I have error that my varaible might not have been intialized looking for numHammers which is my int. I new to java and trying to learn this.
Yep, the local variables have to be definitely assigned in that block. You could initialize it to some negative number.
Jan 30 '08 #4
your saying in loop I must initialize numHammers to a number
Jan 30 '08 #5
I got 5 Items that user inputs amount of product he or she wants, only trying to determine if user enters an int when entering number for second product. I have been searching all over net for examples. I am sure I am missing something simple. I get an error saying numHammers not intailized. Puzzeled. Here is my input of code.

System.out.print("How many Hacksaws? ");
numHackSaws = input.nextInt();

while (numHackSaws <0 || numHackSaws >10)
{
System.out.print("Incorrect! Please re-enter a number between(0-10): ");
numHackSaws = input.nextInt();
}

while (isValid==false)
{
System.out.print("How many Hammers? ");
if(input.hasNextInt())
{
numHammers = input.nextInt();
isValid = true;
}
else
{
input.nextLine();
System.out.println("\nError! Please enter a number!");
}
}

System.out.print("How many Drills? ");
numDrills = input.nextInt();
System.out.print("How many HardHats? ");
numHardHats = input.nextInt();
System.out.print("How many pairs of Safety Goggles? ");
numSafetyGoggles = input.nextInt();
Jan 30 '08 #6
r035198x
13,262 8TB
Look at the error message (they are usually very informative) and initialize the variable (during declaration) being reported there to a negative number.
Jan 30 '08 #7
To use hasNextInt() in scanner class to validate input do I have to add in a range check for this to work.
Jan 31 '08 #8
r035198x
13,262 8TB
To use hasNextInt() in scanner class to validate input do I have to add in a range check for this to work.
I don't fully understand that but could you post the full code you have now and the error message you are getting.
Note: When posting code in the forum please make sure you use code tags.
Jan 31 '08 #9
import java.util.Date;
import java.util.Scanner;

class JohnVanHoutanP2
{
Expand|Select|Wrap|Line Numbers
  1. private static final double HACKSAW_COST = 15.99;        //class constants
  2.       private static final double HAMMER_COST = 12.18;
  3.       private static final double HARDHAT_COST = 18.75;
  4.       private static final double DRILL_COST = 19.99;
  5.       private static final double SAFETYGOGGLES_COST = 16.47;
  6.       private static final double TAX_RATE = 0.05;
  7.       private static final double SHIPPING_COST = 0.08;
/************************************************** ********
main Method - program starts execution here
************************************************** *******/

public static void main(String[] args)
{
Expand|Select|Wrap|Line Numbers
  1.  int numHackSaws, numHammers, numDrills, numHardHats, numSafetyGoggles, numItems;  //local variarables
  2.         double totalCost, tax, shipping, bill,average;
  3.         boolean isValid = false;
Scanner input = new Scanner(System.in); //create an object of the Scanner class
Date today = new Date(); //create an object of the Date class

System.out.println();
System.out.printf("John VanHoutan Java 9:30TTH %tD\n",today);
System.out.println();

printDisplay();
System.out.println();

/**********************input*********************** ******/
Expand|Select|Wrap|Line Numbers
  1. System.out.print("How many Hacksaws?                 ");
  2.         numHackSaws = input.nextInt();
  3.  
  4.         while (numHackSaws <0 || numHackSaws >10)
  5.         {
  6.             System.out.print("Incorrect! Please re-enter a number between(0-10): ");
  7.             numHackSaws = input.nextInt();
  8.         }
  9.  
  10.         while (isValid==false)
  11.         {
  12.             System.out.print("How many Hammers? ");
  13.             if(input.hasNextInt())
  14.             {
  15.                 numHammers = input.nextInt();
  16.                 isValid = true;
  17.             }
  18.             else
  19.             {
  20.                 input.nextLine();
  21.                 System.out.println("\nError! Please enter a number!");
  22.             }
  23.         }
  24.  
  25.         System.out.print("How many Drills?                   ");
  26.         numDrills  = input.nextInt();
  27.         System.out.print("How many HardHats?                 ");
  28.         numHardHats  = input.nextInt();
  29.         System.out.print("How many pairs of Safety Goggles?  ");
  30.         numSafetyGoggles  = input.nextInt();
/*********************processing******************* ******/
Expand|Select|Wrap|Line Numbers
  1. totalCost = (numHackSaws*HACKSAW_COST) + (numHammers*HAMMER_COST) +
  2.                     (numDrills*DRILL_COST) + (numHardHats*HARDHAT_COST) +
  3.                     (numSafetyGoggles*SAFETYGOGGLES_COST);
  4.  
  5.         tax = TAX_RATE * totalCost;
  6.         bill = totalCost + tax;
  7.  
  8.         numItems = numHackSaws + numHammers + numDrills +
  9.                    numHardHats + numSafetyGoggles;
  10.  
  11.         shipping = calcShipping (totalCost);
  12.         average = calcAvg(totalCost,numItems);
/***********************output********************* ******/
System.out.println();
System.out.printf("\nCost of Items: $%6.2f",totalCost);
System.out.printf("\nShipping Cost: $%6.2f",shipping);
System.out.printf("\nTax: $%6.2f",tax);
System.out.printf("\nFinal Bill: $%6.2f\n\n",bill);
System.out.printf("\nTotal Number of Items Purchased: %6d",numItems);
System.out.printf("\nAverage Price of Items: $%6.2f\n\n",average);
} //end of main method

/************************************************** *************
printDisplay Method - list items with prices
************************************************** ************/
public static void printDisplay()
{
System.out.print("Welcome To The Hardware Store");
System.out.println();
System.out.print("------------------------------");
System.out.printf("\nHackSaw\t\t\t$%5.2f",HACKSAW_ COST);
System.out.printf("\nHammer\t\t\t$%5.2f",HAMMER_CO ST);
System.out.printf("\nDrill\t\t\t$%5.2f",DRILL_COST );
System.out.printf("\nHardHat\t\t\t$%5.2f",HARDHAT_ COST);
System.out.printf("\nSafetyGoggle\t\t$%5.2f",SAFET YGOGGLES_COST);
System.out.println();
} //end of printDisplay method

/************************************************** *************
calcShipping Method - returns a double
************************************************** ************/
public static double calcShipping(double purchaseCost)
{
double shipping;

shipping = purchaseCost * SHIPPING_COST;

return shipping;
} //end of calcShipping method

/************************************************** *************
calcAverage Method - returns a double
************************************************** ************/
public static double calcAvg(double purchaseCost, int numProducts)
{
double average;

average = purchaseCost / numProducts;

return average;
} //end of calcAvg method

} //end of JohnVanHoutanP2 class
Jan 31 '08 #10
Not quite sure what I should tag as [code]

Error reads as follows: variable numHammers might not have been initialized
totalCost = (numHackSaws*HACKSAW_COST) + (numHammers*HAMMER_COST) +

I am only trying to determine if user put an int when asked for number of 2nd item.

I have never used any of the scanner methods to check validation of input
Jan 31 '08 #11
r035198x
13,262 8TB
Not quite sure what I should tag as [code]

Error reads as follows: variable numHammers might not have been initialized
totalCost = (numHackSaws*HACKSAW_COST) + (numHammers*HAMMER_COST) +

I am only trying to determine if user put an int when asked for number of 2nd item.

I have never used any of the scanner methods to check validation of input
1.) Unlike C, Java does not require you to declare all variables at the top. In fact it is encouraged to declare variables closest to where they are used.
2.) Your error is because you have not initialized the numHammers variable.
Just a simple
Expand|Select|Wrap|Line Numbers
  1. int numHammers = -1;
at the start of your main method will make that error disappear.
Jan 31 '08 #12
thanks for the interpetation I have used C in past makes sense. thanks, for helping me out
Jan 31 '08 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: rawCoder | last post by:
Hi All, I have a *.cer file, a public key of some one and I want to encrypt some thing using this public key. Can someone point me to a sample code for Encrypting some file using...
1
by: Mike | last post by:
When trying to compile (using Visual Web Developer 2005 Express Beta; frameworkv2.0.50215 ) the source code below I get errors (listed below due to the use of ICallBackEventHandler. Ultimately I...
10
by: Christopher Benson-Manica | last post by:
Why can't I use a class destructor in a using declaration: using MyClass::~MyClass; ? -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org ...
17
by: beliavsky | last post by:
Many of my C++ programs have the line using namespace std; but the "Accelerated C++" book of Koenig and Moo has many examples where the library names are included one at a time, for example ...
8
by: Petter Reinholdtsen | last post by:
I ran into a problem on HP-UX 11.00 the other day, where it refused to compile a program using 'using namespace std;' at the top. The reason seem to be that the compiler refuses to accept 'using...
14
by: john.burton.email | last post by:
I've done some extensive searching and can't seem to find an answer to this - Is it correct to using "using" with templates, for example: using std::vector; Or do I need to specify the type...
5
by: Enos Meroka | last post by:
Hallo, I am a student doing my project in the university.. I have been trying to compile the program using HP -UX aCC compiler, however I keep on getting the following errors. ...
3
by: JDeats | last post by:
I have some .NET 1.1 code that utilizes this technique for encrypting and decrypting a file. http://support.microsoft.com/kb/307010 In .NET 2.0 this approach is not fully supported (a .NET 2.0...
10
by: AZRebelCowgirl73 | last post by:
This is what I have so far: My program! import java.util.*; import java.lang.*; import java.io.*; import ch06.lists.*; public class UIandDB {
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectóplanning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.