日期:2014-05-20  浏览次数:20621 次

麻烦帮忙看下怎么走出循环。
本意是判断如果输入的非字母,提醒重新输入,目前的效果成了,即使是字母,也无法仍然提醒重新输入,咋回事呢?
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;
}
}

------解决方案--------------------
getChar tw = new getChar();//这个写错了吧??

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();
这句话就行了
------解决方案--------------------
另外

 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);
     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();