Read spaces in String as Input Without using NextLine - java

Discription:
I used several scanner statments in below code. First i Read the "Adress" and then "Mobile No." and then some random stuff from user.
When i use adress=sc.next()
it reads the string value of adress from user(Without space) and go to the Next scan statement i.e. mobile=sc.nextBigInteger(). by using this method i am not able read the spaces in "adress(string) " and it throws the runtime error as inputMismatchException.
Now if i use the adress=sc.NextLine, the Progrram directly jumps to the mobile=sc.nextBigInteger().
How is it possible to read the spaces as input in above situations and the below code. How can i protect myself from runtime Errors. I got similar questions on the forum but non of them was satisfactory. Thank you. (Ask me if you need more information about question)
Expected:
input(In adress string) : pune maharashtra india
output(in display function) : pune mahrashtra india.
What exactly happened: if input(in adress string) : pune output(in display function) : pune
if input(in adress string) : Pune india
(Now As soon as i entered the string and hit the enter there I get a runtime error as an inputmismatchexception )
> JAVA
public class Data {
Scanner sc = new Scanner(System.in);
String adress;
BigInteger AcNo;
BigInteger mobile;
String ifsc;
void getData() {
System.out.println("Welcome to Bank System");
System.out.println("Please Enter the adress :");
adress= sc.next();
System.out.println("Enter the Mobile Number");
mobile = sc.nextBigInteger();
System.out.println("Enter the Account Number");
AcNo = sc.nextBigInteger();
System.out.println("Enter the IFSC Code");
ifsc= sc.next();
}
public static void main(String[] args) {
Data d=new Data();
d.getData();
}
}

Change this line ;
adress= sc.next();
with this line ;
adress = sc.nextLine();
this will solve your problem. scan.nextLine() returns everything up until the next new line delimiter, or \n ,but scan.next() is not.
So all code will be like this ;
public class Data{
String adress;
BigInteger AcNo;
BigInteger mobile;
String ifsc;
void getData() {
System.out.println("Welcome to Bank System");
System.out.println("Please Enter the adress :");
adress = new Scanner(System.in).nextLine();
System.out.println("Enter the Mobile Number");
mobile = new Scanner(System.in).nextBigInteger();
System.out.println("Enter the Account Number");
AcNo = new Scanner(System.in).nextBigInteger();
System.out.println("Enter the IFSC Code");
ifsc = new Scanner(System.in).next();
}
public static void main(String[] args) {
Data d = new Data();
d.getData();
}
}

Related

Console.getLine and Console.getString not taking in all of user input - JAVA

I am trying to take in user input (the name of a country) to add to a list of countries that I display. However, it is not letting me enter the name of a country longer than 8 characters.
For example, when I input "Venezuela" the output is "Venezuel" and when I input "United States" the output is "United S"
Below is the method I used to accept the user input. I have tried Console.getString as well as Console.getLine and neither are working to accept more than 8 characters.
public static void addCountry() {
String name = Console.getString("Enter country name: ");
Country country = new Country();
country.setName(name);
countryDAO.add(country);
System.out.println();
System.out.println(name
+ " has been added.\n");
}
I also have these methods in the Console class
import java.util.Scanner;
public class Console {
private static Scanner sc = new Scanner(System.in);
public static String getLine(String prompt) {
System.out.print(prompt);
String s = sc.nextLine();
return s;
}
public static String getString(String prompt) {
System.out.print(prompt);
String s = sc.next();
sc.nextLine();
return s;
}
}
Use this to take input instead of sc.next():
String s = sc.nextLine();
and remove the next line where you have added sc.nextLine()
Hope that helps!

How to check the user input is an integer or not with Scanner?

I want the country codes are integer that input by the user. I want an error message to be show when user inputs a code which is not an integer. How can I do this? The program is to ask user to enter country name and country code. In which user will input the country code. But if user inputs a character I want a message to be shown saying Invalid Input.
System.out.println("Enter country name:");
countryName = in.nextLine();
System.out.println("Enter country code:");
int codeNumber = in.nextInt();
in.nextLine();
If the input is not an int value, then Scanner's nextInt() (look here for API) method throws InputMismatchException, which you can catch and then ask the user to re-enter the 'country code' again as shown below:
Scanner in = new Scanner(System.in);
boolean isNumeric = false;//This will be set to true when numeric val entered
while(!isNumeric)
try {
System.out.println("Enter country code:");
int codeNumber = in.nextInt();
in.nextLine();
isNumeric = true;//numeric value entered, so break the while loop
System.out.println("codeNumber ::"+codeNumber);
} catch(InputMismatchException ime) {
//Display Error message
System.out.println("Invalid character found,
Please enter numeric values only !!");
in.nextLine();//Advance the scanner
}
One simple way of doing it, is reading a line for the numbers as you did with the name, and then checking witha Regex (Regular Expression) to see if contains only numbers, with the matches method of string, codeNumber.matches("\\d+"), it returns a boolean if is false, then it's not a number and you can print your error message.
System.out.println("Enter country name:");
countryName = in.nextLine();
System.out.println("Enter country code:");
String codeNumber = in.nextLine();
if (codeNumber.matches("\\d+")){
// is a number
} else {
System.out.println("Please, inform only numbers");
}
You can do something like this, by first getting the input as a string, then try to convert the string to an integer, then outputs an error message if it can't:
String code= in.nextLine();
try
{
// the String to int conversion happens here
int codeNumber = Integer.parseInt(code);
}
catch (NumberFormatException nfe)
{
System.out.println("Invalid Input. NumberFormatException: " + nfe.getMessage());
}
You could instead check hasNextInt then call nextInt
int codeNumber;
System.out.println("Enter country code:");
if(in.hasNextInt())
{
codeNumber = in.nextInt();
}
else
{
System.out.println("Invalid Code !!");
}
If you are creating your own custom exception class, then use regex to check if the input string is an integer or not.
private final String regex = "[0-9]";
Then, check if the input follows the regex pattern.
if (codeNumber.matches(regex)) {
// do stuff.
} else {
throw new InputMismatchException(codeNumber);
}
You can use build in InputMismatchException if you are not creating your custom exception handler.

Java GetstringMethod

The assignment:
Write a program (Greetings) that prompts the user to enter the first name, the last name, and year of birth, then it returns a greetings message
in proper format (see the example below).
Create a method(s) that accept the scanner and a prompt as parameters and return the user input. A separate method should accept the user input results as parameters, format and print the results. No print statement or scanner input should happen inside main(). Here is an example dialogue with the user:
Please enter your first name:
tom
Please enter your last name:
cruise
Please enter your year of birth:
1962
Greetings, T. Cruise! You are about 53 years old.
I finished the code, but right now it is giving me a compilation error. How do i fix it?
import java.util.*;
public class Greetings {
public static void main(String[] args) {
Scanner newscanner = new Scanner(System.in);
String ask = ("Please enter your first name: ");
String ask2 = ("Please enter your last name: ");
String ask3 = ("Please enter your year of birth: ");
public static String getString(Scanner newscanner, String ask, String ask2, String ask3){
System.out.println(ask);
String first = newscanner.next();
String firstletter = first.substring(0,1).toUpperCase() ;
return firstletter;
System.out.println(ask2);
String second = newscanner.next();
int x = second.length();
String y = second.substring(0, x).toLowerCase();
String lastname = y.substring(0,1).toUpperCase();
return lastname;
System.out.println(ask3);
int third = newscanner.nextInt();
int age = (2015 - third);
return age
System.out.println("Greetings, "+ firstletter + ". " + lastname+"!" +" You are about " + age + " years old");
}
}
}
Hard to read, but I think you actually have the getString() method inside your main() method - it needs to be after it, and only be called from inside main(), not defined there.

Generating username with given information from the user

Hi Im Can Somebody help me with my program ?
my professor ask us to do a program that will get information from the user and generate a 6 letter username from the lastname and firstname of the user.
the first 3 letters of the user name is the first 3 letters of the firstname and the other 3 is the last 3 letters of the lastname of the user. and we need to test it by log-in module
to test if the username and password are match on the generated username and user inputted password
As far as im doing i cant find a answer on this and our professor didn't teach us about this this and im struggling right now.
this is my program right now>>>
public static InputStreamReader r = new InputStreamReader(System.in);
public static BufferedReader i = new BufferedReader(r);
public static void main(String[]args) throws Exception{
String Lname,Fname,Mi;
int age,bday;
float pass;
System.out.print("Enter Last Name: ");
Lname=i.readLine();
System.out.print("Enter First Name: ");
Fname=i.readLine();
System.out.print("Enter Middle Name: ");
Mi=i.readLine();
System.out.print("Age: ");
age=Integer.parseInt(i.readLine());
System.out.print("Birthday (MM/DD/YY) :");
bday=Integer.parseInt(i.readLine());
System.out.println("Password Must Be A 4-6 Digit Combination");
System.out.print("Enter Password : ");
pass=Float.parseFloat(i.readLine());
System.out.println("Please Wait While Generating Your UserName");
for(int j=0;j<=35;j++)
{
try{
Thread.sleep(100);
}
catch(InterruptedException ex)
{
//do nothing
}
System.out.print("*");
}
}
Can Somebody Help Me Please....
You can just:
String username = FName.substring(0,3) + LName.substring(LName.length() - 3, LName.length());
You should probably check that FName and LName have a minimum length of 3 characters, or you will get an exception

Parse Text using scanner useDelimiter

Looking to parse the following text file:
Sample text file:
<2008-10-07>text entered by user<Ted Parlor><2008-11-26>additional text entered by user<Ted Parlor>
I would like to parse the above text so that I can have three variables:
v1 = 2008-10-07
v2 = text entered by user
v3 = Ted Parlor
v1 = 2008-11-26
v2 = additional text entered by user
v3 = Ted Parlor
I attempted to use scanner and useDelimiter, however, I'm having issue on how to set this up to have the results as stated above. Here's my first attempt:
import java.io.*;
import java.util.Scanner;
public class ScanNotes {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
//String regex = "(?<=\\<)([^\\>>*)(?=\\>)";
s = new Scanner(new BufferedReader(new FileReader("cur_notes.txt")));
s.useDelimiter("[<]+");
while (s.hasNext()) {
String v1 = s.next();
String v2= s.next();
System.out.println("v1= " + v1 + " v2=" + v2);
}
} finally {
if (s != null) {
s.close();
}
}
}
}
The results is as follows:
v1= 2008-10-07>text entered by user v2=Ted Parlor>
What I desire is:
v1= 2008-10-07 v2=text entered by user v3=Ted Parlor
v1= 2008-11-26 v2=additional text entered by user v3=Ted Parlor
Any help that would allow me to extract all three strings separately would be greatly appreciated.
You can use \s*[<>]\s* as delimiter. That is, any of < or >, with any preceding and following whitespaces.
For this to work, there must not be any < or > in the input other than the ones used to mark the date and user fields in the input (i.e. no I <3 U!! in the message).
This delimiter allows empty string parts in an entry, but it also leaves empty string tokens between any two entries, so they must be discarded manually.
import java.util.Scanner;
public class UseDelim {
public static void main(String[] args) {
String content = " <2008-10-07>text entered by user <Ted Parlor>"
+ " <2008-11-26> additional text entered by user <Ted Parlor>"
+ " <2008-11-28><Parlor Ted> ";
Scanner sc = new Scanner(content).useDelimiter("\\s*[<>]\\s*");
while (sc.hasNext()) {
System.out.printf("[%s|%s|%s]%n",
sc.next(), sc.next(), sc.next());
// if there's a next entry, discard the empty string token
if (sc.hasNext()) sc.next();
}
}
}
This prints:
[2008-10-07|text entered by user|Ted Parlor]
[2008-11-26|additional text entered by user|Ted Parlor]
[2008-11-28||Parlor Ted]
See also
regular-expressions.info/Character classes
regular-expressions.info/Repetition

Categories