java


Printing a message if a char has more than one symbol(using char, not String)


Basically I need to write this message:
System.out.println("Invalid grade - must enter exactly one letter");
And I don't know how to write an (if,for,while loop) which will find if letterGrade is bigger than one character, it has to be only one character if > 1 character it should follow this message.
And problem is that I know how to do it with string.length() but this is char and it doesn't work.
I tried this:
while(String.valueOf(letterGrade).length() > 1)
{
System.out.println("Invalid grade - must enter exactly one letter");
System.out.print("Enter grade (one character): ");
letterGrade = in.next().charAt(0);
}
But it doesn't print me message that I want, is there some method that finds char greater than one character? Can charAt() help me ?
I would propose to use regular expression since you might want to only allow letters a-f/A-F.
The expression to use would be
[a-fA-F]
The Java code used to check this would be:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Type");
Scanner reader = null;
try {
// Read from System.in
reader = new Scanner(System.in);
// Only work with first character
char c = reader.findInLine(".").charAt(0);
// ""+c creates a string since RegEx only works on strings
String testString = ""+c;
// Test string
if(!(""+c).matches("[a-fA-F]")) {
System.out.println("Invalid input");
return;
}
// c has a valid grade
System.out.println("Valid input");
}
catch(Exception ex) {
if(reader != null)
reader.close();
}
}
}
Test results:
a > Valid input
z > Invalid input
az > Valid input
za > Invalid input
You may use System.in.read(); if you want to read only one charactor.
So you should probably be a little more clear with your question and not in a paragraph form with the entire block of code including variable declaration and user inputlines.
In java, a char can only be one character (i am sure you know this) and so having multiple would mean that it is a string.
Assuming that you are working with letterGrade as an input from the user using Scanner, the way to check if the input is one character or not and do something in response will be
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input.length==1)
{sysout("There is only 1 character in the input");
char value = input.indexOf(0);
}else
{sysout("Invalid grade");
}

Related Links

Value true at action of type java.lang.String cannot be converted to JSONArray
TomEE maven not getting updated class files
Java's ExecutorService.awaitTermination vs Future.get(<TimeOut>)
Java/HtmlUnit - How to get an HtmlImage from an HtmlImageInput?
Making java call to determine Apache Camel conditional routing
Spring batch define FlatFileItemReader in class reader that implements ItemReader not in bean java conf
Using JavaRDD.flatmap() iterator in Apache Spark 2
Java GUI Table adding certain rows to a watch-list
Complex string split method in java
Using Recursion to determine if input is prime
TensorFlow: initializing state for RNN between inferences in Android
How to store the full HTML table in JTable after parsing with JSoup?
What is a test script?
java regex matching &[text(text - text text) !text]
Container Managed EntityManager is Null on REST Application
Spring Mail, Failure sending HELO comand to SMTP Server

Categories

HOME
ms-access
atom-editor
omnet++
iterator
syntax
react-redux
spring-jdbc
amazon-ecs
electronics
flyway4
constraint-programming
upload
primary-key
session-variables
maude-system
vifm
timeout
remote-access
event-handling
iron-router
libtiff
connection-string
lldb
jtextfield
custom-wordpress-pages
object-detection
functional-testing
graphicsmagick
facebook-instant-articles
javacv
spark-jobserver
dynamic-featured-image
vsts-build-task
repo
xenforo
user-controls
janrain
outlook-api
reactive-cocoa-5
businessworks
btrace
flickr-api
osx-mavericks
azure-application-gateway
prolog-setof
togetherjs
colorama
csound
sqlbulkcopy
memory-alignment
pintos
url-pattern
probability-density
ado.net-entity-data-model
login-control
lttng
moveit
packagist
bgp
tform
feedback
0xdbe
appfabric-cache
unity3d-gui
sonarqube5.1.2
javax.mail
csquery
clicktag
camanjs
wordpress-theme-customize
zend-route
expected-exception
mechanize-ruby
braille
balanced-payments
imdbpy
google-cloud-save
dotnetnuke-5
easy-install
ora-00911
android-screen-support
sharp-repository
typoscript2
simba
runas
datawindow
parametric-equations
code-cleanup
table-footer
appendto
ecl
lpeg
radcombobox
zend-translate
procedural-music
putchar
private-members
ajax-forms

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App