gpt4 book ai didi

java - 我如何使用此代码更改为没有任何数组?

转载 作者:行者123 更新时间:2023-12-01 20:27:09 25 4
gpt4 key购买 nike

大家好,StackOverflow 社区,我想就我正在做的学校作业寻求一些帮助。总结一下作业,我们基本上必须创建一个文本文件,并在一行上写两件事。然后程序要求用户输入,如果该输入与任何行上的第一个内容匹配,则打印第二个内容。

示例:

线路:“brb 马上回来”用户输入:“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

一切都很好,直到我注意到,用小字母:“注意:不要使用数组”现在我被困住了。

我需要帮助来弄清楚如何做与我编写的代码相同的事情,但没有数组。有办法吗?

最佳答案

您可以使用 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;
}
}

关于java - 我如何使用此代码更改为没有任何数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43713518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com