2014-05-19 87 views
0

我试图创建一个程序,它接收用户输入的字符并将小写字符转换为大写字母,反之亦然。每次进行转换时,更改次数都会递增,何时“。”。被输入时,程序停止询问输入。这是我下来迄今:Java大写,小写问题

import java.io.*; 
class Example5 
{ 
    public static void main(String args[]) throws IOException 
    { 
     InputStreamReader inStream = new InputStreamReader (System.in); 
     BufferedReader stdin = new BufferedReader (inStream); 
     char input = '\0'; 
     int counter = 0; 

     while(!(input == '.')) 
     { 
     System.out.print("Input a character. Input will continue until you enter a period : "); 
     input = (char)stdin.read(); 

     if((int)input > 96 & (int)input < 123) 
     { 
      char upperInput = Character.toUpperCase(input); 
      System.out.println(upperInput); 
      counter++; 
     } 
     else if((int)input > 64 & (int)input < 91) 
     { 
      char lowerInput = Character.toLowerCase(input); 
      System.out.println(lowerInput); 
      counter++; 
     } 
     } 

     System.out.println("The number of changes are : " + counter); 
    } 
} 

转化率和计数器工作正常,但由于某些原因,每次输入后,该行“输入一个字符输入会继续下去,直到你进入一段:”重复每次输入后多次。任何解决这个问题的方法?我犯了什么错误?

感谢提前:)

+0

你只需要移动是System.out.print'(“输入的文字输入会继续下去,直到你进入一段:”);上面的''的同时, '循环。 – yate

+0

user3580294 - 谢谢!不知道这个! – user3529827

+0

yate - yup,我改变了这种方式。但我也很好奇为什么这条线会重复多次。非常感谢! – user3529827

回答

3

您的打印语句在您的while循环中。这会导致程序在每次循环开始时都会打印。

循环不会等待更多输入,无论是否有新输入,循环都会循环。

要解决该问题,如果您只希望在程序执行开始时打印一次该语句,或者更改循环条件以便仅在新输入为给出。

我希望我已经清楚和有帮助。

+0

非常感谢! – user3529827

0

把它放在while循环

由于这是在循环外,每次的字符被读取,它得到的印刷。

System.out.print("Input a character. Input will continue until you enter a period : "); 

     while(!(input == '.')) 
+0

谢谢!帮助很多! – user3529827

+0

欢迎您:) – mohamedrias

0

你可以这样做:

InputStreamReader inStream = new InputStreamReader (System.in); 
     BufferedReader stdin = new BufferedReader (inStream); 
     char input = '\0'; 
     int counter = 0; 
     System.out.print("Input a character. Input will continue until you enter a period : "); 
     do 
     { 

     input = (char)stdin.read(); 
     System.out.print("Input a character. Input will continue until you enter a period : "); 
     if((int)input > 96 & (int)input < 123) 
     { 
      char upperInput = Character.toUpperCase(input); 
      System.out.println(upperInput); 
      counter++; 
     } 
     else if((int)input > 64 & (int)input < 91) 
     { 
      char lowerInput = Character.toLowerCase(input); 
      System.out.println(lowerInput); 
      counter++; 
     } 
     }while(!(input == '.')); 

     System.out.println("The number of changes are : " + counter); 
    }