0

I know this question sounds somewhat rhetorical but I was curious if it was possible to use a string inside of an Integer scanner.

I am asking this because I was curious if, for example, a user enters numbers and types DONE when they have entered all of the numbers they wish. I know I could do it where I would have them enter eg. a number less than 0 (this could work for grades).

But how would you do this as I wish to do it inside of a while statement, and use it to terminate the statement.

Phantomazi
  • 408
  • 6
  • 22
  • 2
    You can accept Strings and parse them to Integers. – Phantomazi Nov 11 '15 at 15:03
  • 1
    A scanner is never associated with a data type. You can read almost any type from the Scanner. You can read everything as Strings and parse them as integers – TheLostMind Nov 11 '15 at 15:05
  • As @Phantomazi said, you can accept strings and parse them into integers like so, `int input = Integer.parseInt("string from scanner")` – Brandon Laidig Nov 11 '15 at 15:05
  • Make sure to handle `NumberFormatException` if `Integer#parseInt` fails. – dguay Nov 11 '15 at 15:07
  • First check if the String is equal to `"done"` or use `matches("\\d+")` for checking and then parse them as integers. This will prevent *known* NumberFormatExceptions. – TheLostMind Nov 11 '15 at 15:17
  • @VinodMadyalkar I didn't mean it literally as, "take the input string without doing any checks on it and attempt to parse it into an integer". I meant it as, "once you get to the point where you need to parse it, this is how you do it". – Brandon Laidig Nov 11 '15 at 15:18
  • @BrandonLaidig - OK. Addressed the comment to the OP :) – TheLostMind Nov 11 '15 at 15:20

1 Answers1

0

As stated in the comments the Scanner is not associated with a data type. Having said so this could be one simple solution - have in mind that it could be improved to better handle your exceptions !

import java.util.Scanner;                               

public class Start {

public static void main(String[] args) {
    Scanner Reader = new Scanner(System.in);    
    boolean continueReading = true;
    int grade;
    while (continueReading)
    {
        String input;                                      
        System.out.println("Please input a number or type in Done to exit.");

        input = Reader.nextLine();                       
        if(input.equalsIgnoreCase("Done"){
           System.out.println("Finishing..");
           continueReading == false;
        }
        else{
           try{
              grade = Integer.parseInt(input);
              System.out.println("The grade is: " + grade);
           }catch(NumberFormatException e){
              //Some exception handling
           }
        }
    }
}
Phantomazi
  • 408
  • 6
  • 22