我是一名新手程序员,我正在尝试做一些我觉得有趣的项目,以帮助我更多地了解这门语言,然后我的学校类(class)已经能够提供。我想尝试反转字符串,但我没有在字符串中定义字符串,而是添加了一个扫描器,以便能够允许用户输入他们想要的内容。在寻求任何帮助后,我无法找到我遇到的问题。到目前为止我有这个:
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
static ArrayList<String> newString = new ArrayList();
static int inputLength = 0;
static String PlaceHolder = null;
static String beReturned = null;
static int lengthArray = 0;
static String ToBeReversed;
static String hold = null;
public static void reversal(){
inputLength = ToBeReversed.length();
for (int e = 0; e <= inputLength; e++)
{
PlaceHolder = ToBeReversed.substring(inputLength -1, inputLength);
newString.add(PlaceHolder);
}
}
public static String putTogether()
{
int lengthcounter = 0;
lengthArray = newString.size();
for (int i = 0; i < lengthArray; i++)
{
beReturned = beReturned + newString.get(lengthcounter);
if (lengthcounter < lengthArray)
{
lengthcounter++;
}
}
return beReturned;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
Reverse.reversal();
Reverse.putTogether();
}
}
对于我输入的任何输入都没有结果。我没有收到错误消息或任何形式的返回...输出为空白。我只是想知道我是否在使用扫描仪时犯了错误,或者这是否是我尝试存储字符/从我创建的 ArrayList 访问它们的方式。我试图不让其他人给我完整的所有修复的答案,我希望我能得到一个指针或提示,指出我搞砸了的地方。感谢您的宝贵时间和帮助。
最佳答案
你需要打印输出,例如
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
System.out.println("ToBeReversed = " + ToBeReversed);
Reverse.reversal();
System.out.println("newString = " + newString);
System.out.println(Reverse.putTogether());
}
我不想给出一个完整的答案,因为那会破坏你的乐趣(并偷走你开始使用调试器的机会),但这里有一些提示......
- 您可以使用
String#charAt
从给定索引处的String
中获取单个字符 - Java 通常从 0 开始索引,这意味着像数组、
String
、List
这样的东西从索引0
开始,一直到长度 - 1
null
+String
=nullString
;)- 你可以向后运行一个循环。
for-loop
不必从0-x
升序运行,它们可以按降序运行x-0
;)
关于Java 初级扫描仪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25050735/