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

getClassLoader not getting resources when run on Android Studio, but works on command line ./gradlew. Why?
Dividing a string into groups of four
NumberFormatException: Invalid int: “”
My com.mongoDB jar file don't have a mongoClient
Spring data mongo with more than 10 parameters
Calculate month and time difference in java?
Displaying things in processing
Create Array Attribute In Java
How do I count how many negative elements are in a circular doubly linked list?
How to fix can not resolve symbol OnMenuTabClickListener
How to implement Quartz Exponential Backoff strategy?
RCP application Subversion entegration
Binary file transfer do not reset idle timeout in Websocket in JBoss Undertow
SVNKit Ignore certain revisions in diff
PATH set manually is different from PATH displayed in JAVA
Hibernate 3 map Enum

Categories

HOME
sendgrid
hook
gerrit
octobercms
mean-stack
c#-2.0
cross-browser
onelogin
podio
upload
synchronization
virtualization
primary-key
python-unittest
gnupg
metatrader4
collectd
windows-azure-storage
apache-metamodel
samoa
grails3
paging
tokenize
wkwebview
bootstrap-tour
icloud-api
sqlcipher
internet-explorer-9
filezilla
fifo
wtx
large-file-upload
librato
madlib
phonegap
google-cloud-endpoints-v2
framemaker
commit
jmonkeyengine
vxworks
dartium
squib
mesos-chronos
particles.js
dynamic-reports
quadratic-programming
elmah
texmaker
botbuilder
bootstrap-dialog
outlook-api
eclipse-gef
sas-jmp
dotcover
smartcontracts
filepicker
tizen-native-app
togetherjs
forever
sqlclient
font-size
eventkit
removechild
vmware-tools
bonobo
url-masking
intrusion-detection
merge-conflict-resolution
persist
master-slave
python-stackless
ptrace
qtableview
thredds
sniffer
iiviewdeckcontroller
clipperlib
codeigniter-routing
client-side-templating
html-helper
project-planning
mesa
typo3-neos
fmod
quartz-graphics
ftps
padarn
cassini-dev
coderush
funscript
google-email-migration
errai
netbeans-6.9
custom-backend
heartbeat
xdomainrequest
remember-me
asp.net-mvc-areas
fixed-width
audio-capture
misv

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