![](/img/trans.png)
[英]Write a program that prompts the user to enter a string, then displays the total number of characters and total number of lower case characters
[英]I need to write a java program that continuously prompts the user to enter a sentence. then reverse string only exit if stop entered
這是我到目前為止所擁有的,我想我可能需要一個我不知道如何實現的無限循環:
我需要寫一個Java程序,不斷提示用戶輸入一個句子,然后把字符串倒過來。 僅當輸入“停止”時才會退出
import java.util.Scanner;
public class Reverse
{
public static void main(String[] args)
{
System.out.println("Plaese enter a sentence:");
Scanner read = new Scanner(System.in);
String str = read.nextLine();
String reverse = "";
for(int i = str.length() - 1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}
System.out.println("Please enter a sentence:");
System.out.println(reverse);
}
}
您可以同時使用while
或for
循環進行無限循環。 也可以有兩種方法來終止程序:
end of file marker
。 例如:在 linux 上Ctrl + z
。這是示例代碼:
import java.util.Scanner;
public class Reverse {
public static void main(String[] args)
{
while(true) {
System.out.println("Please enter a sentence, Type Stop to exit the program ");
Scanner read = new Scanner(System.in);
String str = read.nextLine();
if( str.equalsIgnoreCase("stop")) {
System.exit(0);
}
String reverse = "";
for(int i = str.length() - 1; i >= 0; i--) {
reverse = reverse + str.charAt(i);
}
System.out.println(reverse);
}
}
}
使用while(true)
無限循環。 檢查每個輸入字符串,如果輸入等於“退出”,則退出循環。 您也可以使用 StringBuilder 的 reverse 方法來反轉字符串。
public static void main(String[] args)
{
String input;
Scanner read = new Scanner(System.in);
while ( true )
{
System.out.println("Please enter a sentence:");
input = read.nextLine();
if ("exit".equalsIgnoreCase(input))
{
break;
}
// reverse a string
System.out.println(new StringBuilder(input).reverse().toString());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.