I'm supposed to write a program that takes in a string representing an integer as input, and outputs yes if every character is a digit 0-9.
I have gone back through my chapters reading and gone through Google, but I'm still having trouble. I know my code is a mess but I am lost. I may have bits and pieces correct or be wrong all together but this is what I have.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userString;
// Add more variables as needed
userString = scnr.next();
boolean check1 = Character.isDigit(userString);
while (check1 = True) {
System.out.println ("Yes");
}
System.out.println ("No");
Where did I go wrong?
As pointed out by people in comments, there are some mistakes in your code. Character.isDigit won't work with String. What you need to use is Integer.parseInt(...). You can put it in a try catch block; Print yes if parsing is successful and print No if exception is thrown:
userString = scnr.next();
try {
int parsedValue = Integer.parseInt(userString);
// Do something with parsedValue
System.out.println("Yes");
} catch (NumberFormatException numberFormatException) {
System.out.println("No");
}
You could use regular expressions for that:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// your input, can also be from a scanner
String input = "1234567890";
// regex pattern to match a string that consists only of numbers and is also not empty
String regex = "^[0-9]+$";
// to match negative numbers as well: "^[\\-]?[0-9]+$"
// create a pattern object
Pattern pattern = Pattern.compile(regex);
// create a matcher object
Matcher matcher = pattern.matcher(input);
// check if the input matches
if (matcher.find()) {
System.out.println("It's a number, yay!");
};
How does the regex work:
^ matches the beginning of the input to make sure there is nothing before the number characters
[0-9]+ tells it to match the range 0-9 one or more times (+), which also makes sure that an empty string does not match
$ matches the end of the string to make sure there is no non-numbers after the match
If you want to match negative numbers as well, there is an additional part of the regex: [\\-]? this matches one minus sign if there is on or none if there is no sign (?)
https://www.tutorialspoint.com/java/java_regular_expressions.htm
It's also possible the way you tried it:
// open a scanner
Scanner scanner = new Scanner(System.in);
// read user input from the scanner
String input = scanner.next();
// assume it is a number until we find a non-digit character below
String isNumber = true;
// loop over each character of the user input
for (char character : input) {
// check if the character is not a digit
if (!Character.isDigit(character)) {
System.out.println("NOT a number: ", character);
// set the is number variable to false
isNumber = false;
// break the loop, because it cannot be a number because we already found a non-digit
break;
};
};
System.out.println("Is it a number? ", isNumber);
Related
So I'm supposed to use the scanner to read the users employee number and then put that into a method that returns a boolean value. The employee is supposed to have the form DDDDD-LDDDD with the d being digits and l being letters. If the input matches this format I'm supposed to inform the user that they have a valid number and if it doesn't then I have to say it's invalid. I've trying to separate into two substrings to be able to see if they contain digits as well as to see if it contains a letter. I then try to combine these using a loop and if it's in that format the user is told it's valid and if it's not they are informed it's not. Is there any other possible way to check and see if the employee number is composed of digits besides obviously the dash and letter that I can then use to prompt the user if what they wrote is valid? This is only written in Java
You can use regular expressions:
final String[] strings = {
"54321-A1234", // A valid employee ID
"012948B9832", // The dash is replaced with a number
"39832-30423", // The letter is replaced with a number
"24155-C90320", // A valid employee ID but the last number
};
for (String string : strings) {
if (string.matches("[0-9]{5}-[A-Za-z]{1}[0-9]{4}")) {
System.out.println("The string " + string + " is a valid pattern.");
} else {
System.out.println("The string " + string + " is an invalid pattern.");
}
}
This will output
The string 54321-A1234 is a valid pattern.
The string 012948B9832 is an invalid pattern.
The string 39832-30423 is an invalid pattern.
The string 24155-C90320 is an invalid pattern.
Explanation:
[0-9]{5} means "match exactly five digits";
- means "match the character - exactly one time";
[A-Za-z]{1} means "match exactly one letter, case-insensitive";
[0-9]{4} means "match exactly four digits";
Note that [0-9] can be replaced with \\d and that {1} is optional, but I've added just for explicitness.
You can do it with a regular expression. This prompts for the string and if not in proper format, reprompts.
Scanner input = new Scanner(System.in);
String str = null;
System.out.println("Please enter string in DDDDD-LDDDD format");
while (true) {
str = input.nextLine();
// checks for 5 digits followed by - one letter and four digits.
if(str.matches("\\d{5}-\\p{Alpha}\\d{4}")) {
break;
}
System.out.println("Please try again!");
}
System.out.println(str + " is a valid string");
When I input any sentence, my output returns that any string is a palindrome, and I think that my replaceAll calls aren't working in some cases. This is likely due to error my part, because using the Scanner class in Java is new for me (more used to input from C++ and Python3). I added comments to make it clearer what my intentions were when writing the program.
import java.util.Scanner;
public class PalindromeTest
{
public static void main (String[] args)
{
Scanner stringScan = new Scanner(System.in); //Scanner for strings, avoids reading ints as strings
Scanner intScan = new Scanner(System.in); //Scanner for ints, avoids reading strings as ints
String forwardPal = ""; //Variables for the rest of the program
String reversePal = "";
String trimForward = "";
char tempChar;
int revCount;
int revPalLength;
int quit;
while (true) //Loop to keep the program running, problem is in here
{
System.out.println("Please enter a word or a sentence."); //Prompts user to enter a word or sentence, I assume that the program is counting
forwardPal = stringScan.nextLine();
trimForward = forwardPal.replaceAll(" " , ""); //Trims the forwardPal string of characters that are not letters
trimForward = trimForward.replaceAll("," , "");
trimForward = trimForward.replaceAll("." , "");
trimForward = trimForward.replaceAll("!", "");
trimForward = trimForward.replaceAll(":", "");
trimForward = trimForward.replaceAll(";", "");
revPalLength = trimForward.length() ; //Makes the reverse palindrome length equal to the length of the new trimmed string entered
for (revCount = revPalLength - 1; revCount >= 0; revCount--) //Loop to count the reverse palindrome and add each character to the string reversePal iteratively
{
tempChar = trimForward.charAt(revCount);
reversePal += tempChar;
System.out.println(reversePal);
}
if (trimForward.equalsIgnoreCase(reversePal)) //Makes sure that the palindrome forward is the same as the palindrome backwards
{
System.out.println("Congrats, you have a palindrome"); //Output if the sentence is a palindrome
}
else
{
System.out.println("Sorry, that's not a palindrome"); //Output if the sentence isn't a palindrome
}
System.out.println("Press -1 to quit, any other number to enter another sentence."); //Loops to ask if the user wants to continue
quit = intScan.nextInt(); //Checks if the user input a number
if (quit == -1) //If the user inputs -1, quit the program and close the strings
{
stringScan.close();
intScan.close();
break;
}
}
}
}
Your problem is this line
trimForward = trimForward.replaceAll("." , "");
That function takes the first argument as a regex, and the dot means that it is replacing all characters as a "".
Instead, use
trimForward = trimForward.replace("." , "");
In fact, all your lines should be using #replace instead of #replaceAll as none of them take advantage of regex. Only use those if you plan to take advantage of it.
Or in fact, if you do want to use a regex, this is a nice one which does all of that in one neat line.
trimForward = forwardPal.replaceAll("[ .!;:]" , "");
I hope this was of some help.
The simplest fix is to use replace() instead of replaceAll().
replace() replaces all occurences of the given plain text.
replaceAll() replaces all occurences of the given regex.
Since some of your replacements have special meaning in regex (specifically the dot ., which means any character), you cant use replaceAll() as you are currently (you'd have to escape the dot).
It's common, and quite reasonable, to assume that replace() replaces one occurrence and replaceAll() replaces all occurrences. They are poorly named methods, because they interpret their parameters differently, yet both replace all matches.
As an aside, you may find this briefer solution of interest:
forwardPal = forwardPal.replaceAll("\\W", ""); // remove non-word chars
boolean isPalindrome = new StringBuilder(forwardPal).reverse().toString().equals(forwardPal);
I am a beginner in both, Java and regular expressions. I want to get a name as an input, by which I mean that only names that have English alphabets A-Z, case insensitive and spaces.
I am using a Scanner class to get my input but my code doesn't work. It looks like:
Scanner sc= new Scanner(System.in);
String n;
while(!sc.hasNext("^[a-zA-Z ]*$"))
{
System.out.println("That's not a name!");
sc.nextLine();
}
n = sc.next();
I checked my regular expression on the website regex101.com and found out that it works fine.
For example, If I input it my name, Akshay Arora , the regex site says it is okay but my program prints
That's not a name
That's not a name
Same line is printed twice and it again asks me for input. Where am I going wrong?
Two parts are wrong:
$ and ^ anchors are considered in the context of entire input, not in the context of the next token. It will never match, unless the input has a single line that matches the pattern in its entirety.
You use default delimiters, which include spaces; therefore, Scanner will never return a token with a space in it.
Here is how you can fix this:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
String n;
while(!sc.hasNext("[a-zA-Z ]+"))
{
System.out.println("That's not a name!");
sc.nextLine();
}
n = sc.next();
Demo.
Here its sample program related to regex.
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputName = sc.next();
String regex = "^[a-zA-Z ]*$";
// Compile this pattern.
Pattern pattern = Pattern.compile(regex);
// See if this String matches.
Matcher m = pattern.matcher(inputName);
if (m.matches()) {
System.out.println("Valid Name");
} else
System.out.println("Invalid Name");
}
}
Hope this will help you
I am using the following logic to extract double value from a String. It works fine on the first String but raise an Exception on second String. The raised Exception is java.util.NoSuchElementException.
public class StringHandling {
public String processString(String string)
{
Scanner st = new Scanner(string);
while (!st.hasNextDouble())
{
st.next();
}
double value = st.nextDouble();
return String.valueOf(value);
}
public static void main(String[] args)
{
String first = "Hey, he is 70.3 miles away.";
String second = "{\"Hey\", \"he\" \"is\": 1.0, \"miles\" away}";
StringHandling sh = new StringHandling();
System.out.println("First Value is "+sh.processString(first));
System.out.println("Second Value is "+sh.processString(second));
}
}
I just want to know why it is raising the Exception.
This is the problem:
"{\"Hey\", \"he\" \"is\": 1.0, \"miles\" away}"
The next method of class Scanner by default gives you the next input until a space is reached.
The next method would fetch it like that:
{"Hey",
"he"
"is":
1.0,
"miles"
away}
In that case, you have 1.0, which is not a double (note the comma).
That's why you get a NoSuchElementException: you keep doing st.next(), but a double is never found, so the end of the string gets reached and the Scanner doesn't find other elements.
You could use a regex pattern instead of the scanner:
public String processString(String string) {
Pattern p = Pattern.compile("(\\d+(?:\\.\\d+))");
Matcher m = p.matcher(string);
while(m.find()) {
return m.group(1);
}
return null;
}
The Problem
By default, a Scanner splits on white space. So your second example finds 1.0, as one of the inputs, which it doesn't recognise as a double.
Your code also assumes that you'll exit the while loop because you found a double. In this case, there is no value to read so you get an exception.
Solution 1 — Change Delimiter
One option is to change the delimiter used by your Scanner object. Perhaps to something like this:
st.useDelimiter("[^\\w.]");
This will break your input into "words" containing any combination of alphanumeric characters, underscores and periods.
Solution 2 — Regex
You can find this value with a regular expression. The example below looks for numbers that include a decimal point and at least one decimal place:
public static String findWithRegex(String string) {
Pattern pattern = Pattern.compile("\\d+\\.\\d+");
Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
return matcher.group();
} else {
// do something more useful here
return "none";
}
}
How to catch integer if the user must input String only, no integer and Symbols included to the input? Help me sir for my beginner's report.
import java.util.*;
public class NameOfStudent {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name = "";
System.out.print("Please enter your name: ");
name = input.nextLine(); // How to express error if the Strin contains
//integer or Symbol?...
name = name.toLowerCase();
switch(name)
{
case "cj": System.out.print("Hi CJ!");
break;
case "maria": System.out.print("Hi Maria!");
break;
}
}
}
Use this regular expression.
Check if a String contains number/symbols etc..
boolean result = false;
Pattern pattern = Pattern.compile("^[a-zA-Z]+$");
Matcher matcher = pattern.matcher("fgdfgfGHGHKJ68"); // Your String should come here
if(matcher.find())
result = true;// There is only Alphabets in your input string
else{
result = false;// your string Contains some number/special char etc..
}
Throwing custom exceptions
Throwing custom exceptions in java
Working of a try-catch
try{
if(!matcher.find()){ // If string contains any number/symbols etc...
throw new Exception("Not a perfect String");
}
//This will not be executed if exception occurs
System.out.println("This will not be executed if exception occurs");
}catch(Exception e){
System.out.println(e.toString());
}
I just given a overview, how try-catch works. But you should not use a general "Exception" ever. always use your customized exception for your own exceptions.
Once you have the String in your hand, e.g. name you can apply a regexp to it as follows.
String name = "your string";
if(name .matches(".*\\d.*")){
System.out.println("'"+name +"' contains digit");
} else{
System.out.println("'"+name +"' does not contain a digit");
}
Adapt the logic checks to your needs.
Please be aware that a string can contain numeric character, and it's still a string:
String str = "123";
I think what you meant in your question is "How to enforce alphabetical user input, no numeric or symbol", which can be easily done using regular expression
Pattern pattern = Pattern.compile("^[a-zA-Z]+$"); // will not match empty string
Matcher matcher = pattern.matcher(str);
bool isAlphabetOnly = matcher.find();
Use Regex which is a sequence of characters that forms a search pattern:
Pattern pattern = Pattern.compile("^[a-zA-Z]*$");
Matcher matcher = pattern.matcher("ABCD");
System.out.println("Input String matches regex - "+matcher.find());
Explanation:
^ start of string
A-Z Anything from 'A' to 'Z', meaning A, B, C, ... Z
a-z Anything from 'a' to 'z', meaning a, b, c, ... z
* matches zero or more occurrences of the character in a row
$ end of string
If you also want to check for empty string then replace * with +
If you want to do it without regex then:
public boolean isAlpha(String name)
{
char[] chars = name.toCharArray();
for (char c : chars)
{
if(!Character.isLetter(c))
{
return false;
}
}
return true;
}
You can change your code as follows.
Scanner input=new Scanner(System.in);
System.out.print("Please enter your name: ");
String name = input.nextLine();
Pattern p=Pattern.compile("^[a-zA-Z]*$");// This will consider your
input String or not
Matcher m=p.matcher(name);
if(m.find()){
// your implementation for String.
} else {
System.out.println("Name should not contains numbers or symbols ");
}
Follow this link more about Regex. And test some regex by your self from here.
In Java you formulate what the String is allowed to contain in a regular expression. Then you check if the String contains the allowed sequence - and only the allowed sequence.
Your code looks like this. I've added a do-while-loop to it:
Scanner input = new Scanner(System.in);
String name = "";
do { // get input and check for correctness. If not correct, retry
System.out.print("Please enter your name: ");
name = input.nextLine(); // How to express error if the String contains
//integer or Symbol?...
name = name.toLowerCase();
} while(!name.matches("^[a-z][a-z ]*[a-z]?$"));
// The above regexp allows only non-empty a-z and space, e.g. "anna maria"
// It does not allow extra chars at beginning or end and must begin and end with a-z
switch(name)
{
case "cj": System.out.print("Hi CJ!");
break;
case "maria": System.out.print("Hi Maria!");
break;
}
Now you can change the regular expression, e.g. to allow names with asian character sets. Take a look here how to handle predefined character sets. I was once checking any text for words in any language (and any part of the UTF-8 character set) and ended up with a regular expression like this to find the words in a text: "(\\p{L}|\\p{M})+"
if we want to check that two different user enter same email id while registration.....
public User updateUsereMail(UserDTO updateUser) throws IllegalArgumentException {
System.out.println(updateUser.getId());
User existedUser = userRepository.findOneById(updateUser.getId());
Optional<User> user = userRepository.findOneByEmail(updateUser.getEmail());
if (!user.isPresent()) {
existedUser.setEmail(updateUser.getEmail());
userRepository.save(existedUser);
} else {
throw EmailException("Already exists");
}
return existedUser;
}
Scanner s = new Scanner(System.in);
String name;
System.out.println("enter your name => ");
name = s.next();
try{
if(!name.matches("^[a-zA-Z]+$")){
throw new Exception("is wrong input!");
}else{
System.out.println("perfect!");
}
}catch(Exception e){
System.out.println(e.toString());
}
umm..try storing the values in an array..for each single value , use isLetter() and isDigit() ..then construct a new string with that array
use try catch here and see !
i am not used to Pattern class ,use that if thats' simpler