Hey StackOverflow社区,我想请求一些我正在做的学校作业的帮助。总结一下这个任务,我们基本上要创建一个文本文件,并在一行上写两件事。然后程序要求用户输入,如果该输入与任何行上的第一件事相匹配,则打印第二件事。
示例:
线:“brb be right back” 用户输入:“brb” 输出:“马上回来”
我成功了,这是我的代码。你可以运行它来看看它做得更清楚。
// The "NetSpeak_raminAmiri" class.
import java.io.*;
public class NetSpeak_raminAmiri
{
public static void main (String[] args)
{
sendLines ();
readLines ();
} // main method
public static void sendLines ()
{
try
{
FileWriter fw = new FileWriter ("net.txt");
PrintWriter pw = new PrintWriter (fw);
pw.println ("brb\tbe right back");
pw.println ("lol\tlaugh out loud");
pw.println ("g2g\tgot got go");
pw.println ("d8\tdate");
pw.println ("h8\thate");
pw.println ("luv\tlove");
pw.println ("pos\tparents over shoulder");
pw.println ("u\tyou");
pw.println ("sup\twhat's up");
pw.println ("yolo\tyou only live once");
pw.println ("smh\tshake my head");
pw.println ("lmao\tlaugh my ass off");
pw.println ("ttyl\ttalk to you later");
pw.println ("idc\ti don't care");
pw.println ("idk\ti don't know");
pw.println ("ily\ti love you");
pw.println ("bae\tdanish word for poop");
pw.println ("omg\toh my god");
pw.println ("tmi\ttoo much information");
pw.println ("tbh\tto be honest");
pw.println ("jk\tjust kidding");
pw.println ("ftw\tfor the win");
pw.println ("np\tno problem");
pw.close ();
}
catch (IOException e)
{
}
} //sendLines method
public static void readLines ()
{
try
{
FileReader fr = new FileReader ("speak.txt");
BufferedReader br = new BufferedReader (fr);
String input;
String line;
System.out.println ("What net-speak would you like to translate?");
input = In.getString ();
while ((line = br.readLine ()) != null)
{
String translate[] = line.split ("\t");
for (int i = 0 ; i < translate.length - 1 ; i++)
{
if (input.equals (translate [i]))
{
System.out.println (translate [i + 1]);
}
}
}
}
catch (IOException e)
{
e.printStackTrace ();
}
} //readLines method
} // NetSpeak_raminAmiri class
一切都很好,直到我注意到,用小写字母:“注意:不要使用数组” 而现在我被卡住了。
我需要帮助弄清楚如何对我所做的代码做同样的事情,但没有数组。有办法吗?
答案 0 :(得分:3)
您可以使用IndexOf和Substring
while ((line = br.readLine()) != null)
{
int p = line.IndexOf('\t');
string key = line.Substring(0, p);
if (input.equals(key))
{
System.out.println(line.Substring(p+1));
break;
}
}