473,811 Members | 2,963 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

help with Scanner

4 New Member
Hey guys, im trying to finish an assignment for a java class, and i have finished the program except for one part. The program requires that i take 3 values inputted from the user, the first 2 must be digits between 0 and 9, and the third an operator.
the operator decides if the two numbers are added subtracted...et c. anyways the things i cannot get, is i need to check if they enter valid digits, and not letters, however if i do put a letter in, scanner gives me an exception. it happens at line 14 when you enter a letter.... how can i test if it is a letter... any suggestions?


here is my code

Expand|Select|Wrap|Line Numbers
  1. import java.util.Scanner;
  2. import java.text.DecimalFormat;
  3.  
  4. public class problem1 {
  5. public static void main(String[]args){
  6.  
  7.     double num1,  num2, answ;
  8.  
  9.     String tString,num1Word = " ",num2Word= " ";
  10.     Scanner scan = new Scanner(System.in);
  11.     DecimalFormat formatter = new DecimalFormat("0");
  12.  
  13.     System.out.println("Please enter two numbers between 0 and 9 ");
  14.     num1= scan.nextDouble();
  15.     num2= scan.nextDouble();
  16.  
  17.     if(Character.isDigit((Double.toString(num1)).charAt(0))){
  18.  
  19.     }
  20.     else{System.out.println("Please Enter Digits only!");
  21.     System.exit(0);
  22.     }
  23.  
  24.     switch((int)num1){
  25.     case 0: num1Word= "Zero";
  26.     break;
  27.     case 1: num1Word= "One";
  28.     break;
  29.     case 2: num1Word= "Two";
  30.     break;
  31.     case 3: num1Word= "Three";
  32.     break;
  33.     case 4: num1Word= "Four";
  34.     break;
  35.     case 5: num1Word= "Five";
  36.     break;
  37.     case 6: num1Word= "Six";
  38.     break;
  39.     case 7: num1Word= "Seven";
  40.     break;
  41.     case 8: num1Word= "Eight";
  42.     break;
  43.     case 9: num1Word= "Nine";
  44.     break;
  45.     default: 
  46.         System.out.println("Invalid Number");
  47.     System.exit(0);
  48.     break;
  49.     }
  50.     switch((int)num2){
  51.     case 0: num2Word= "Zero";
  52.     break;
  53.     case 1: num2Word= "One";
  54.     break;
  55.     case 2: num2Word= "Two";
  56.     break;
  57.     case 3: num2Word= "Three";
  58.     break;
  59.     case 4: num2Word= "Four";
  60.     break;
  61.     case 5: num2Word= "Five";
  62.     break;
  63.     case 6: num2Word= "Six";
  64.     break;
  65.     case 7: num2Word= "Seven";
  66.     break;
  67.     case 8: num2Word= "Eight";
  68.     break;
  69.     case 9: num2Word= "Nine";
  70.     break;
  71.     default: 
  72.         System.out.println("Invalid Number");
  73.     System.exit(0);
  74.     break;
  75.     }
  76.     System.out.println("Please enter the mathematical symbol for what you would like to do with these numbers. ");
  77.     tString = scan.next();
  78.     char operator = tString.charAt(0);
  79.  
  80.  
  81.  
  82.  
  83.     switch(operator){
  84.     case '*': answ= num1*num2;
  85.         System.out.println(num1Word+ " Multiplied by "+num2Word+" is "+formatter.format(answ));
  86.         break;
  87.     case '/': if(num2 == 0){
  88.         System.out.println("You cannot divide by zero, session terminated.");
  89.  
  90.     }
  91.     else{
  92.         answ= num1/num2;
  93.         System.out.println(num1Word+ " Divided by "+num2Word+" is "+formatter.format(answ));
  94.     }
  95.     break;
  96.     case '+': answ= num1 + num2;
  97.     System.out.println(num1Word+ " Added to "+num2Word+" is "+formatter.format(answ));
  98.     break;
  99.     case '-': answ= num1 - num2;
  100.     System.out.println(num1Word+ " Minus "+num2Word+" is "+formatter.format(answ));
  101.     break;
  102.     case '^': 
  103.         answ= Math.pow(num1,num2);
  104.     System.out.println(num1Word+ " raised to the power of " +num2Word+ " is "+ formatter.format(answ));
  105.     break;
  106.     default: System.out.println("Invalid Operator");
  107.     System.exit(0);
  108.     break;
  109.     }
  110.  
  111. }
  112. }
  113.  
Feb 19 '09 #1
2 2104
horace1
1,510 Recognized Expert Top Contributor
you can use method scanner.hasNext Double() to check if the next token can be read as a double and if not ignore it, e.g.
Expand|Select|Wrap|Line Numbers
  1. System.out.println("Please enter two numbers between 0 and 9 ");
  2. while(!scan.hasNextDouble())
  3.    { 
  4.     System.out.printf("error, enter a double !"); 
  5.     scan.nextLine();          // ignore rest of line
  6.    }
  7. num1= scan.nextDouble();
  8.  
Feb 19 '09 #2
bvav22
4 New Member
i really cannot thank you enough, that was such a big help.... :)
Feb 19 '09 #3

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

Similar topics

13
4280
by: Andrew Bell | last post by:
I'm doing a uni course in the UK and one of my semesters is about programming. This is just going to be compilied and executed with no menu just using command promt (javac classfile.class) I am not that good at programming but what I need to know is in java how would i do this.................. menu appears, user selects menu option (1,2,3,4,5,6) a new menu appears after selecting option 1 asking the user to select another option...
2
1586
by: porky008 | last post by:
I can not figure out how to use an array to store the different things and the total is only showing 0.0 instead of the total of the inventory. Can I please get some help on this? // This calls the external class scanner import java.util.Scanner; class inventory { // start of class // Variable Declaration private String productname; // name of movie
1
1508
by: klubbhead | last post by:
This part of my program needs to read from 4 parameter files and then displays them on the screen by clicking a different radio button. The program itself works, but my professor says that I have to improve the code in the DescriptionPanel 's listener because there are several lines of code that are identical and I should only have them once. Here is the code: import javax.swing.*; import java.awt.*; import java.awt.event.*; import...
4
1632
nomad
by: nomad | last post by:
I'm very new to java and programing. I need some help with this. Check each user entry to ensure validity. Color is either Black, White, or Red. if the user enter the wrong color the following with show ERROR – Incorrect color – try again: I'm tring to figure out if this is a while loop or a do while loop. and help would be great. Here is what I have so far. //make a Scanner object for color
5
1736
by: sandyw | last post by:
I need help in two areas: Both are at the bottom of my program where a client has two choice to make, 1. When the client enter "Y" it takes him to the begin of the program. I would like to know what this is done ie maybe at the part where it ask you do you want to enter a new product. 2. If the client enters the wrong value or then "Y" or "N" then they are prompted with "error - Please try again" for some reason my no matter what I enter I...
5
3562
by: koonda | last post by:
Hi all, I am a student and I have a project due 20th of this month, I mean May 20, 2007 after 8 days. The project is about creating a Connect Four Game. I have found some code examples on the internet which helped me little bit. But there are lot of problems I am facing developing the whole game. I have drawn the Board and the two players can play. The players numbers can fill the board, but I have problem implementing the winner for the...
15
1541
by: djtosh | last post by:
hi there hoping someone can help me out with this. im designing a code that is a basic database holding peoples details and i need to implement a method that searches by txt for a record by their last name. import java.util.*; import java.io.PrintStream; import java.io.File; import java.io.FileNotFoundException; public class coursework4
3
2955
by: thename1000 | last post by:
Hi, I'm trying to create this output: Input team 1's name: Team 1 Input team 1's ranking: 90.4 etc.
5
2160
by: saytri | last post by:
Hi i have this project were i have to do a quiz. i wrote the questions in a textfile and i called them through java. I have also made a menu to choose which type of quiz. But before accessing the quiz i have to do a password and a login. I managed to do the password but when i tried to join this to the whole program its not working. This is the main program: import java.util.*; import java.io.*; import java.util.Scanner; import...
1
1753
by: ImortalSorrow | last post by:
Please I need urgent help with this program! Everything is working well except a part where i want to repeat the riddle if the answer isnt correct. here's the code..hope someone can help me! import java.util.Scanner; class TheRiddle { public static void main(String args) {
0
9722
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10644
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10379
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4334
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.