30876

Java Scanner input dilemma. Automatically inputs without allowing user to type

<strong>Thanks a lot for responses, I will probably stick to just adding extra input.nextLine() statements to catch any "leftovers"</strong>

So in this code I input 2, and once it goes to the if statement it skips the "sCreateLogin = input.nextLine();" and proceeds to the next input. Probably because there is something lingering in the Scanner yet I cannot figure out why it does it and how exactly to fix it.

If I do input.next() it stops, but it just isn't good enough because if you accidentally add a space it will also skip the next input. I know I could parse it etc., but I'm still confused with this.

Scanner input = new Scanner(System.in); System.out.println("(1) Login"); System.out.println("(2) Create Account"); int iAccountOption = input.nextInt(); if(iAccountOption==2) { System.out.println("Input desired login: "); String sCreateLogin = input.nextLine(); System.out.println("Input desired password: "); String sCreatePassword = input.nextLine(); }

Answer1:

The problem is likely end of line tokens that are not being dealt with. To fix this, after input.nextInt(); add an extra input.nextLine() to swallow the end of line tokens:

int iAccountOption = input.nextInt(); input.nextLine(); if (iAccountOption == 2) { .....

Answer2:

I will suggest you to use either of these two ways : 1. Using BufferedReader class 1a.Use BufferedReader Class and Wrap it with the InputStreamReader Class.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) //string str = br.readLine(); //for string input int i = Integer.parseInt(br.readLine()); // for Integer Input

1b.Now since the readLine method throw an IOException, so you need to catch it. so the whole code will look like this.

try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) //string str = br.readLine(); //for string input int i = Integer.parseInt(br.readLine()); // for Integer Input }catch(IOException ioe){ ioe.PrintStackTrace(); }

2.if you are using the Java SE6 or higher then you can make use of Console class

Console cons = System.console(); String str = cons.readLine("Enter name :"); System.out.print("your name :"+str);

Answer3:

Try having a different Scanner object for String.

Answer4:

Scanner input = new Scanner(System.in); System.out.println("(1) Login"); System.out.println("(2) Create Account"); int iAccountOption = input.nextInt(); if (iAccountOption == 2) { input.nextLine(); // here you forget System.out.println("Input desired login: "); String sCreateLogin = input.nextLine(); System.out.println("Input desired password: "); String sCreatePassword = input.nextLine(); System.out.println(sCreateLogin + " " + sCreatePassword); }

Answer5:

It was skipping sCreateLogin because scanner.nextLine() already had a value "\r \n". So I changed all scanners to nextLine(). It worked out fine, but maybe it won't be the best idea.

package com.stackoverflow.main; import java.util.Scanner; public class SO4524279 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("(1) Login"); System.out.println("(2) Create Account"); int iAccountOption = new Integer(scanner.nextLine()); String sCreateLogin = ""; String sCreatePassword = ""; if (iAccountOption == 2) { System.out.println("Input desired login: "); sCreateLogin = scanner.nextLine(); System.out.println("Input desired password: "); sCreatePassword = scanner.nextLine(); } System.out.println("Login: " + sCreateLogin + "Pass: " + sCreatePassword); } }

Remember to use try catch on new Integer(scanner.nextLine())

Recommend

  • java use Regular Expressions to generate a string [duplicate]
  • How to generate random events in android?
  • Meteor.. accounts- password— Create account on client without login
  • Generating anchors with PyYAML.dump()?
  • How to name a 'group' check box in Adobe Reader when wanting to fill form by FDF / XFDF
  • Can a Collections.shuffle be considered equivalent to a series of Randoms?
  • Real Time CountDown Timer In Python
  • Configure Spring's MappingJacksonHttpMessageConverter
  • If statement skipping right to else after being called once?
  • cordova is not defined - cordova.js has already been loaded :: Ionic
  • How to autopopulate a field in SugarCRM form
  • NUnit 3.0 TestCase const custom object arguments
  • ASP.NET MVC 2 Preview 2 - display directory list rather than home/index
  • How does this usort cmp function actually work?
  • Admob requires api-13 or later can I not deploy on old API-8 phones?
  • FFmpeg Conversion Error
  • Is there a javascript serializer for JSON.Net?
  • Master page gives error
  • Get object from AWS S3 as a stream
  • Java applet as stand-alone Windows application?
  • MySQL WHERE-condition in procedure ignored
  • Join two tables and save into third-sql
  • what is the difference between the asp.net mvc application and asp.net web application
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Adding custom controls to a full screen movie
  • Comma separated Values
  • Matrix multiplication with MKL
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • Error creating VM instance in Google Compute Engine
  • Hits per day in Google Big Query
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • how does django model after text[] in postgresql [duplicate]
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • How does Linux kernel interrupt the application?
  • Can't mass-assign protected attributes when import data from csv file
  • sending mail using smtp is too slow
  • Sorting a 2D array using the second column C++
  • Binding checkboxes to object values in AngularJs
  • java string with new operator and a literal