我的老师给了我们一项任务,即使用字符串数组创建一个由办公室及其楼层组成的建筑目录。之后,她告诉我们用户应该能够在目录中搜索业务,更改目录,查看目录并保存对文件的更改。我坚持如何允许用户更改数组中的元素,因为我们从未在课堂上这样做过,我似乎无法在任何教科书中找到它。请帮助:')..这是我到目前为止的代码:
import java.util.Arrays;
import java.util.Scanner;
public class Townsendtest {
public static void main(String[] args) {
//String array of businesses on each floor starting at floor 0-24
String floor [] = { "Ground Floor", "Advanced Technologies", "HiMark Marketing",
"Law Offices of John Daniels", "PST Systems", "Century United Brokers Inc.",
"Creative Resources", "Design Centre Associates", "Ideal Media Group",
"SF Net Developers", "Shears Medical Services Inc.",
"Green Space Construction Inc.", "Cornerstone Mortgage Capital",
"Allied Advantage Realty", "JAMS the Resolution Experts",
"Law Offices of Matt Dill", "Vacant", "The Drop in Centre",
"Artisan Interiors Consultancy", "NGS Group",
"Robert H. Greene Real Estate", "Vacant", "Vacant",
"Denise A. Patterson Attorney at Law", "Conference Rooms 1-6" };
String namefind;
System.out.print("Enter the name of the Business: ");
namefind = businessname.nextLine();
for (int i = 0; i < floor.length; i++){
if(namefind.equalsIgnoreCase(floor[i])) {
System.out.println("Business Found!");
System.exit(0);
}
}
//if business is not found, it will assume the user needs to see the entire building directory
System.out.println("Business not found, try again.\nHere is the directory:");
//prints the Floor Number of index and he Business listed on the floor
System.out.println("Floor Number\t\tBusiness");
//for loop to print entire index to the user
for(int counter=0; counter<floor.length; counter++ ) {
System.out.println(counter + "\t\t\t" + floor[counter]);
}//end for loop
}//end main
}//end class
答案 0 :(得分:2)
要修改数组的内容,只需使用:
floor[i] = "Some new data";
在这种情况下,i
是索引,即计数器。数组以索引0
开头。
但是,一旦输入匹配,程序就会终止,因为您正在调用System.exit
。你可能需要把它放在循环中以保持程序活着。
因此,对于您的确切问题,这可能是一个解决方案:
if(namefind.equalsIgnoreCase(floor[i])) {
System.out.print("Enter the NEW name of the Business: ");
floor[i] = businessname.nextLine();
// Do NOT System.exit - wrap the whole thing in a loop.
}
答案 1 :(得分:0)
使用
会更有意义if(floor[i].contains(namefind)) {
答案 2 :(得分:0)
假设你的问题,我会说你在问:
要从标准输入读取用户输入,我会使用以下内容:
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
String input = inputReader.readLine();
这将读取用户输入,直到换行符。
要将变量的值赋给数组元素,您应该可以执行以下操作:
array[0] = input;
此外,简单的Google搜索为您提供了许多解决方案: https://www.google.com/search?ion=1&espv=2&ie=UTF-8&q=java%20read%20user%20input%20into%20array