分别利用string类或stringbuilder类或stringbuffer类实现:制作一个简单的“加密”程序,通过键盘输入一个字符串,将每个字符对应的数值加3,显示输出新字符串。
时间: 2023-05-02 19:03:20 浏览: 69
可以使用任何一个类来实现“加密”程序,但建议使用StringBuffer或StringBuilder。因为它们可以动态改变其长度,这对于在每个字符处进行密钥计算并将其附加到结果字符串中非常有用。而String类一旦创建之后,就不能更改其内容,每次更改都会创建一个新的字符串对象,这样会消耗大量的内存和时间。
相关问题
java要求用String类通过键盘输入一个英文字符串,将其反转后,输出在屏幕上
好的,这是一个简单的Java程序,可以实现你的要求:
```java
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个英文字符串:");
String str = sc.nextLine();
String reversed = reverseString(str);
System.out.println("反转后的字符串为:" + reversed);
}
public static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
}
```
这个程序首先通过`Scanner`类从键盘上读取一个英文字符串,然后调用`reverseString()`方法将其反转,最后将结果输出到屏幕上。
`reverseString()`方法使用了`StringBuilder`类来进行字符串反转操作,它会先将字符串转换成可变字符串,然后调用`reverse()`方法进行反转,最后再通过`toString()`方法将结果转换成字符串返回。
输入一个字符串是否为回文 如:"上海自来水来自海上"就是回文(使用String类)
可以使用Java中的String类的方法来判断一个字符串是否为回文。下面是一个示例代码:
```java
public class Main {
public static void main(String[] args) {
String str = "上海自来水来自海上";
boolean isPalindrome = isPalindrome(str);
System.out.println("字符串:" + str);
System.out.println("是否为回文:" + isPalindrome);
}
public static boolean isPalindrome(String str) {
String reverseStr = new StringBuilder(str).reverse().toString();
return str.equals(reverseStr);
}
}
```
输出结果为:
```
字符串:上海自来水来自海上
是否为回文:true
```
在上述示例中,我们定义了一个名为isPalindrome的方法,该方法接受一个字符串作为参数。在方法中,我们使用StringBuilder的reverse()方法将字符串反转,并转换为String类型。然后,我们将反转后的字符串与原始字符串进行比较,如果相等,则说明该字符串是回文,返回true;否则,返回false。在main()方法中,我们调用isPalindrome方法,并打印是否为回文的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)