I need help on the Java Scanner Code - java

So I need help on this code. This code is all in one so ignore the spaces but I need to write another scanner in the way bottom of the code and if I do add
String feeling = in.nextLine(); at the very end it does not work. I need a it so that I can write my feelings so that I can make jarvis answer but the string does not work and java ignores the string and goes right on to the next part. It starts from the middle.
Scanner in = new Scanner(System.in);
System.out.println("Type User Name:");
String userName = in.nextLine();
System.out.println("PASSWORD:");
int passcodeFromUser=in.nextInt();
int passcode = 2015;
if (passcodeFromUser == passcode) {
System.out.println("Welcome Mr." + userName + "!");
Random random = new Random(userName.hashCode());
System.out.println("Mr." + userName + ", You are now recognized and you are now able to command me.");
System.out.println("I was created by John Choi");
System.out.println("JARVIS stands for Just A Rather Very Intelligent System");
System.out.println("How are you today Mr." + userName + "?");
}
So if I add this code at the back it does not work. It ignores and says Oh. Mr is feeling.
String feeling = in.nextLine();
System.out.println("Oh. Mr." + userName + "is feeling" + feeling + ".")

That is because your nextInt invocation does not actually parse a line feed.
Quoting the API, Scanner#nextInt:
Scans the next token of the input as an int.
(focus on the token part here)
Here's one (but not the only) way to fix it:
Integer passcodeFromUser = null;
try {
passcodeFromUser= Integer.parseInt(in.nextLine());
}
catch (NumberFormatException nfe) {
// TODO handle non-numeric password
}
... instead of int passcodeFromUser=in.nextInt();.
You can also loop the parsing of the Integer so that you print an error message when catching the NumberFormatException and don't break the loop until you have a valid numeric passcode.

You can consume the \n character:
in.nextLine();
String feeling = in.nextLine();
So just putting in.nextLine() before the code you were going to add will easily fix your problem.

Related

What is wrong in my file reading with Scanner class?

Every time I run it, gives this message (( InputMismatchException )) where is the problem from ?
File f = new File("nameList.txt");
try {
PrintWriter out;
out = new PrintWriter(f);
for (int i = 0; i < 4; i++) {
out.printf("Name : %s Age : %d ", "Rezaee-Hadi", 19);
out.println("");
}
out.close();
} catch (IOException ex) {
System.out.println("Exception thrown : " + ex);
}
try {
Scanner in = new Scanner(f);
String name = in.nextLine();
int age = in.nextInt();
for (int i = 0; i < 4; i++) {
System.out.println(name);
System.out.println(age);
}
in.close();
} catch (FileNotFoundException ex) {
System.out.println("Exception thrown : " + ex);
}
You are creating your data file in the following data format:
Name : Rezaee-Hadi Age : 19
Now, it really doesn't matter (to some extent) how you format your data file as long as you realize that you may need to parse that data later on. You really don't need to maintain a header with your data on each file line. We already know that the first piece of data on any file line is to be a Name and the second piece of data on any file line is to be the Age of the person the Name relates to. So, the following is sufficient:
Rezaee-Hadi, 19
If you want, you can place a header as the very first line of the data file so that it can easily be determined what each piece of data on each line relates to, for example:
Name, Age
Rezaee-Hadi, 19
Fred Flintstone, 32
Tom Jones, 66
John Smith, 54
This is actually a typical format for CSV data files.
Keeping with the file data format you are already using:
There is nothing wrong with using the Scanner#nextLine() method. It's a good way to go but you should be iterating through the file line by line using a while loop because you may not always know exactly how many actual data lines are contained within the file, for example:
Scanner in = new Scanner(f);
String dataLine;
while (in.hasNextLine()) {
dataLine = in.nextLine().trim();
// Skip Blank Lines
if (dataLine.equals("")) {
continue;
}
System.out.println(dataLine);
}
This will print all the data lines contained within your file. But this is not what you really want is it. You want to separate the name and age from each line which means then that you need to parse the data from each line. One way (in your case) would be something like this:
String dataLine;
Scanner in = new Scanner(f);
while (in.hasNextLine()) {
dataLine = in.nextLine().trim();
// Skip Blank Lines
if (dataLine.equals("")) {
continue;
}
String[] dataParts = dataLine.replace("Name : " , "").split(" Age : ");
System.out.println("The Person's Name: " + dataParts[0] + System.lineSeparator()
+ "The Person's Age: " + dataParts[1] + System.lineSeparator());
}
In the above code we iterate through the entire data file one line at a time using a while loop. As each line is read into the dataLine string variable it is also trimmed of any leading or trailing whitespaces. Normally we don't want these. We then check to make sure the line is not blank. We don't normally want these either and here we skip past those blank lines by issuing a continue to the while loop so as to immediately initiate another iteration. If the file line line actually contains data then it is held within the dataLine variable.
Now we want to parse that data so as to retrieve the Name and the Age and place them into a String Array. We do this by using the String#split() method but first we get rid of the "Name : " portion of the line using the String#replace() method since we don't want to deal with this text while we parse the line. In the String#split() method we supply a string delimiter to split by and that delimiter is " Age : ".
String[] dataParts = dataLine.replace("Name : " , "").split(" Age : ");
Now when each line is parsed, the Name and Age will be contained within the dataParts[] string array as elements located at index 0 and index 1. We now use these array elements to display the results to console window.
At this point the Age is a string located in the dataParts[] array at index 1 but you may want to convert this age to a Integer (int) type value. To do this you can utilize the Integer.parseInt() or Integer.valueOf() methods but before you do that you should validate the fact the the string you are about to pass to either of these methods is indeed a string numerical integer value. To do this you would utilize the String#matches() method along with a simple little Regular Expression (RegEx):
int age = 0;
if (dataParts[1].matches("\\d+")) {
age = Integer.parseInt(dataParts[1]);
// OR age = Integer.valueOf(dataParts[1]);
System.out.println("Age = " + age);
}
else {
System.out.println("Age is not a numerical value!");
}
The regular expression "\\d+" placed within the String#matches() method basically means, "Is the supplied string a string representation of a integer numerical value?". If the method finds that it is not then boolean false is returned. If it finds that the value supplied is a string integer numerical value then boolean true is returned. Doing things this way will prevent any NumberFormatException's from occurring.
Replace this:
int age=0;
while (in.hasNext()) {
// if the next is a Int,
// print found and the Int
if (in.hasNextInt()) {
age = in.nextInt();
System.out.println("Found Int value :"
+ age);
}
}
in place of this:
int age = in.nextInt();
Then you will not get "InputMismatchException" anymore..

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.

Make an email list, by entering only recipient names

I want to make a simple code, that prompts you to enter names, separated by comma or just a space, and when you click enter, to take every one word you entered, and put a #gmail.com at the end of it, how can I do it?
That's what I have for now
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
String names;
System.out.println("Enter names: ");
names = input.next();
System.out.println(names + mail);
This should be everything you asked for, if you put a list of names separated by commas it will loop through them, otherwise it will just print a single name.
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
System.out.println("Enter names: ");
String names = input.next();
if(names.contains(",")) {
for(String name : names.split(",")) {
System.out.println(name + mail);
}
} else {
System.out.println(names + mail);
}
Hope that helps.
Not knowing what language this is, here's the pseudo-code:
names = input.next();
namesArray = names.split(" ") -- replace with your preferred delimiter
foreach name in namesArray
print name + mail

Why does the compiler complain "while expected" when I try to add more code?

Write a program with a word containing # character as an input. If the word doesn't contain #, it should prompt the user for a word with #. Once a word with # is read, it should output the word then terminate.
This is what I have done so far:
public class find {
public static void main(String[] args) {
System.out.println(" Please enter a word with # ");
Scanner scan = new Scanner(System.in);
String bad = "#";
String word = scan.next();
do
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
while (!word.contains(bad));
}
}
I can get it to terminate after a word containing "#" is given as input, but if I try to add a Scanner to the line after "please try again", it says while expected.
I think issue is you are missing surrounding braces for do/while:
do
if (!word.contains( bad ))
System.out.println( " Please try again " );
else
System.out.println( " " + word);
while ( !word.contains( bad ));
should be:
do
{
if (!word.contains( bad ))
System.out.println( " Please try again " );
else
System.out.println( " " + word);
}while ( !word.contains( bad ));
Some people may not like this, but my suggestion is always use open/close braces. In this case, for the code if/else also. It avoids lot of confusion.
This is where your problem lies:
do
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
while (!word.contains(bad));
You need to put braces from where the loop starts until it ends. |So this thing should like:
do {
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
} while(!word.contains(bad));
For Better Practice You should Check do...while loops here.
The problem with your code is it is not re-reading the word in your loop.
Modify your loop like this (minimum change to your code).
do {
word = scan.next();
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
}
while (!word.contains(bad));
And yes as others have pointed out try to use braces especially with nested constructs.
There are two issues.
Your code is not using the braces properly
you are not attempting to read the new word if right word is not entered.
Also I prefer while loop better in the case as opposed to do-while loop as below.
Scanner scan = new Scanner ( System.in );
String required= "#";
System.out.println( " Please enter a word with # " );
String word = scan.next() ;
//check if the right word(containing #) is entered,
//if not then loop until it is enteres
while((!word.contains(required)){
System.out.println( " Please try again " );
//read the new word as input from the user
word = scan.next() ;
}
//right word is entered, display it
System.out.println(word);
Also please note that when you use scan.next(), it reads each word separately if entered in the same line.

Java: 2 runtime errors I can't figure out

I am working on a homework assignment, and I am going a little "above and beyond" what is called for by the assignment. I am getting a run-time error in my code, and can not for the life of me figure out what it is that I have done wrong.
Here is the assignment:
Write a program that displays a simulated paycheck. The program should ask the user to enter the date, the payee’s name, and the amount of the check. It should then display a simulated check with the dollar amount spelled out.
Here is my code:
CheckWriter:
/* CheckWriter.java */
// Imported Dependencies
import java.util.InputMismatchException;
import java.util.Scanner;
public class CheckWriter {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
// Try to get the name
String name = "";
NameValidator validateName = new NameValidator();
while (validateName.validate(name) == false) {
System.out.println("Enter the name: ");
name = keyboard.nextLine();
if (validateName.validate(name) == false) {
System.out.println("Not a valid name.");
}
}
// Get the date
String date = "";
DateValidator validateDate = new DateValidator();
while (!validateDate.validate(date)) {
System.out.println("Enter the date (dd/mm/yyyy): ");
date = keyboard.nextLine();
if (!validateDate.validate(date)) {
System.out.println("Not a valid date.");
}
}
// Try to get the amount of the check
String checkAmount = "";
CurrencyValidator validateCurrency = new CurrencyValidator();
while (!validateCurrency.validate(checkAmount)) {
System.out.print("Enter the Check Amount (XX.XX): $");
checkAmount = keyboard.nextLine();
if (!validateCurrency.validate(checkAmount)) {
System.out.println("Not a valid check amount.");
}
}
String checkWords = checkToWords(checkAmount); // ERROR! (48)
System.out
.println("------------------------------------------------------\n"
+ "Date: "
+ date
+ "\n"
+ "Pay to the Order of: "
+ name
+ " $"
+ checkAmount
+ "\n"
+ checkWords
+ "\n"
+ "------------------------------------------------------\n");
}
private static String checkToWords(String checkAmount) {
/**
* Here I will use the string.split() method to separate out
* the integer and decimal portions of the checkAmount.
*/
String delimiter = "\\.\\$";
/* Remove any commas from checkAmount */
checkAmount.replace(",", "");
/* Split the checkAmount string into an array */
String[] splitAmount = checkAmount.split(delimiter);
/* Convert the integer portion of checkAmount to words */
NumberToWords intToWord = new NumberToWords();
long intPortion = Long.parseLong(splitAmount[0]); // ERROR! (84)
intToWord.convert(intPortion);
String intAmount = intToWord.getString() + " dollars";
/* Convert the decimal portion of checkAmount to words */
String decAmount = "";
long decPortion = Long.parseLong(splitAmount[1]);
if (decPortion != 0) {
NumberToWords decToWord = new NumberToWords();
decToWord.convert(Long.parseLong(splitAmount[1]));
decAmount = " and " + decToWord.getString() + " cents.";
}
return (intAmount + decAmount);
}
}
Note that I am using external class files to handle validation of the name, date, currency, and conversion from numbers to words. These class files all work as intended.
The error I am getting is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at CheckWriter.checkToWords(CheckWriter.java:82)
at CheckWriter.main(CheckWriter.java:46)
I have commented the lines in my code that are causing the errors that I am experiencing.
Could someone please assist me in figuring where my code is going wrong? I can include the other class files if you feel that it would be needed.
EDIT: When I run the code, it asks for the name and date. Before asking for the check amount is when it throws the error.
EDIT 2: A huge thank you to cotton.m! Thanks to his advice, I have changed the while statements to look like this:
while(!validateDate.validate(date) && date == "")
This has now fixed my issue. It would appear that when validating data with a regex expression, an empty string will return true.
The String you are trying to parse in an empty length string.
My suggestion would be to
1) Check the value of checkAmount at the start of checkToWords - if it is blank there's your problem
2) Don't do that split. Just replace the $ like you did the , (I think this is your real problem)
Also you are going to have another issue in that 10000.00 is not a long. I see you are splitting out the . but is that really what you want?
It is NumberFormatException, the value in checkAmount (method parameter) is not a valid Number.
You need to set checkAmount=checkAmount.replace(",", "");
Otherwise checkAmount will still have , inside and causes NumberFormatExcpetion.
Your issue is with your delimiter regex, currently you are using \.\$ which will split on a literal . followed by a literal $. I'm assuming that what you are actually intending to do is to split on either a . or a $, so change your delimiter to one of the following:
String delimiter = "\\.|\\$"
or
String delimiter = "[\\.\\$]"
As your code is now, checkAmount.split(delimiter) is not actually successfully splitting the string anywhere, so Long.parseLong(splitAmount[0]) is equivalent to Long.parseLong(checkAmount).
It should be:
String delimiter = "[\\.\\$]";
and then you have to check that splitWord[i] is not empty.

Categories