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

cmd command not running within java program
Do you need System.out.flush() before System.error.print(“”);
How to use Kerberos ticket on another machine
Define default locale and treat exceptions for Spring Locale Interceptor
overwrite a value inside a file in java
Open Source Continuous Integration tool for solo developer [Java] [closed]
Why is redis throwing NullPointerException running via JUnit with spring and default config?
Why does this python script run out of memory?
JPanel content not displaying
Regarding initialization of class instances
Sending events via code generation with annotations
Automatically generate Retrofit Types
ClassNotFoundException Error Spring + JSF trying to implement Spring Security login
JPA Entity updating database without persist/merge
Android Studio can't find installed SDK packages
Java SOAP client stub generation with service endpoint determined at runtime

Categories

HOME
sendgrid
multithreading
image
deployment
hook
amazon-ec2
cookies
magnific-popup
image-processing
path-finding
nullpointerexception
angular-material
stock
fft
iot
tizen-web-app
amazon-ecs
communication
spring-tool-suite
size
ibm-odm
quickfix
msp430
iolanguage
tostring
windows-7-x64
propel
jprofiler
zapier
tar
facebook-instant-articles
crosstab
django-storage
facebook-access-token
publish
dbclient
gitignore
catel
multilingual
jna
awt
import-from-excel
qwt
apache-fop
komodoedit
jlink
svmlight
carrot
windows-mobile-6.5
jspdf-autotable
crosswalk-runtime
migradoc
medium.com
abcpdf9
wdf
log4c
phishing
holder.js
sigabrt
captivenetwork
goose
ford-fulkerson
natvis
wordml
purge
coveralls
deis
sailfish-os
oberon
clipperlib
kineticjs
facebook-graph-api-v2.4
nstableviewcell
rdtsc
device-manager
bitcoinj
uitouch
jubula
valueconverter
transcoding
tidy
buster.js
back-stack
hungarian-algorithm
ember-app-kit
http-unit
typoscript2
runas
datawindow
multipage
punbb
stage
qt-jambi
doh
coercion
xmlspy
javax.script
floating
h.323
paster
infrastructure
forums
webkit.net
temporal-database
genealogy
lzh

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