[英]How to place the first character of a string in the last position of the string in Java?
初级Java程序员。 对于学校作业,我需要编写一个程序,用一个数字和相同的数字进行一些计算,如果它的第一个成员/字符被放置在最后一个位置(例如 2567 和 5672)。 我决定通过将数字转换为字符串来解决这个问题,获取每个字符串的第一个字符并将其放在背面以获得我需要的第二个数字。 虽然我认为这是一个非常愚蠢的问题,但我似乎无法找到一种以我需要的方式操作字符串的方法,那么我该怎么做呢?
提前致谢!
由于我完整地发布了代码,我还将包括整个问题的内容:计算 A 和 B 之间的差异(例如 2567 和 5672)是否大于 5000。如果是 - A 应该打印,那么对于 10 - 10000 范围内的所有数字 A 和 B 都是相同的,它的第一个字符作为最后一个字符。
public class new1 {
public static void main (String[] args){
int bot = 10;
int top = 10000;
int difference = 5000;
int a, b, c;
a = bot;
while (a<10000) {
String str1 = String.valueOf(a);
// my question comes at about this point
String str2 = "10"; // this line is just as an example; my idea is to then convert back to int and store in b for calculation;
b = Integer.parseInt(str2);
c = a - b;
if (c > difference)
System.out.println(c);
else
a++;
}
System.out.println("End");
}
}
将第 1 位的字符附加到上面的字符串中
String str = String.valueOf(2567); System.out.println(str.substring(1)+str.substring(0,1));
if it's first member/character has been placed in the last position (eg 2567 and 5672).
我不确定我是否理解,但第一个字符是charAt(0)
,最后一个字符是charAt(str.length()-1)
。
好的,我重新阅读了您的示例,我想我看到了不同的解释。 您也可以使用substring()
删除字符,然后使用连接再次添加它们,这最容易使用+
。
while (a<10000) {
String str1 = String.valueOf(a);
// problem: move first char to last;
String str2 = "10"; // example; convert to int and store in b for calculation;
// this takes the first character of str1 and moves it to
// end of str2.
// 1. Make a copy first
char first = str1.charAt(0);
// 2. Now remove the character and assign to str2
str2 = str1.substring(1);
// 3. Place the saved copy at the end
str2 = str2 + first;
b = Integer.parseInt(str2);
c = a - b;
if (c > difference)
System.out.println(c);
else
a++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.