string scanning

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Norgy
    New Member
    • May 2013
    • 56

    string scanning

    Code:
     public static void main(String[] args) {
            // TODO code application logic here
            Scanner input = new Scanner(System.in);
            int noOfCases = input.nextInt();
            System.out.println("no of c is :" + noOfCases);
            for (int i = 0; i < noOfCases; i++) {
                Scanner in = new Scanner(System.in);
                credit = in.nextInt();
                System.out.println("no of cr is :" + credit);
                noOfItems = in.nextInt();
                System.out.println("no of it is :" + noOfItems);
                prices = in.nextLine();
                System.out.println("no of pr is :" + prices);
               // pri(prices);
    
            }
            
        }
    when running this code, the program do not give me the chance to input the prices, what is the problem?
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    First of all, it is difficult to know what you are trying to do. The variables credit, noOfItems and prices are never defined. But as Scanner#nextInt () will always give us an integer and Scanner#nextLin e() will return a String (both according to the Java API docs) I'm guessing you have a definition similar to this one:
    Code:
    int credit, noOfItems;
    String prices;
    OK, next step. When I add these and run the program, it throws an InputMismatchEx ception when I would expect to input the prices and enter anything but an integer. But wait, it already output the line
    Code:
    no of pr is :
    Why so? Well, nextLine() will scan for the rest of the line, remove any line separator and return the result. This means, that it won't wait for you to input something but will rather just return an empty String. Change the last printout to
    Code:
    System.out.println("no of pr is : '" + prices + "'");
    and you'll see an empty result. It will then continue with the second reading of the credit

    So, what's the solution? Well, depending on what exactly you're expecting for the prices variable, use a different method from the Scanner class.

    PS.: You don't need two Scanners. Just use input rather than in inside the loop.

    Comment

    • Norgy
      New Member
      • May 2013
      • 56

      #3
      Actually, i declared those variables outside the main, but i did not put the declaration here, sorry for that :)
      and thank you

      Comment

      Working...