本意是判断如果输入的非字母,提醒重新输入,目前的效果成了,即使是字母,也无法仍然提醒重新输入,咋回事呢?
import java.util.*;
public class Test3{
public static void main(String[] args)
{
getChar tw = new getChar();
char ch = tw.getChar();
System.out.println(ch);
}
public char getChar() {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char ch = str.charAt(0);
if(ch<'a' || ch>'Z') {
System.out.println("输入错误,请重新输入");
ch=getChar();
}
return ch;
}
}
import java.util.*;
public class Test3{
public static void main(String[] args)
{
getChar tw = new getChar();
char ch = tw.getChar();
System.out.println(ch);
}
public char getChar() {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char ch = str.charAt(0);
if(ch<'a' || ch>'Z') {
System.out.println("输入错误,请重新输入");
ch=getChar();
}
return ch;
}
}
if(ch<'a' || ch>'Z') //这个不能判断是不是字母啊
字母的ASCII范围是65~90(A~Z)、97~122(a~z)。像你这样判断,岂不是把所有的都排除了?
package cn.test;import java.util.Scanner;public class Test3{
public static void main(String[] args)
{
Test3 tw = new Test3();
char ch = tw.getChar();
System.out.println(ch);
}
public char getChar() {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char ch = str.charAt(0);
if(ch<'a' || ch>'Z') {
System.out.println("输入错误,请重新输入");
}
return ch;
}
}楼主类实例化错了,如果是楼主发的那些代码是不可能运行成功的。
估计是你赋值错了。
另外
删除ch=getChar();
这句话就行了
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char ch = str.charAt(0);
if(ch<'A' || ch>'z') {
System.out.println(ch);
System.out.println("输入错误,请重新输入");
getChar();
}
return ch;
}
判断条件错了
import java.util.*;
public class Test3{
public static void main(String[] args)
{
Test3 tw = new Test3();
char ch = tw.getChar();
System.out.println(ch);
}
public char getChar() {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char ch = str.charAt(0);
if(ch<'A' || ch>'z') {
System.out.println("输入错误,请重新输入");
}
return ch;
}
}修改成这样应该就没事了
public class Test3{
public static void main(String[] args)
{
getChar tw = new getChar();
char ch = tw.getChar();
System.out.println(ch);
}
}
class getChar{
public char getChar() {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char ch = str.charAt(0);
if(ch<'A' || ch>'Z' && (ch < 'a' || ch > 'z')) {
System.out.println("输入错误,请重新输入");
ch=getChar();
}
return ch;
}
}
最后处理成这样就行了。
如果输入非字母,会提醒重新输入。ch = getChar();此处就是起到循环判断作用。