Create a java array by reading from a file -
i have started learning java , trying read names text file created. want program ask user name , check if name in list. however, having trouble working arrays first trying read names , store them in array. here have done far.
import java.util.scanner; import java.io.file; import java.io.filenotfoundexception; public class readnames { public static void main(string[] args) throws filenotfoundexception { file file=new file("names.txt"); scanner my_input = new scanner(file); int i=0; string[] names = new string[20] ; while(my_input.hasnext() && !names.equals("-1")) { names[i]=my_input.nextline(); i++; } my_input.close(); system.out.println(names[i]); } }
public static void main(string[] args) throws filenotfoundexception { file file = new file("names.txt"); scanner my_input = new scanner(file); arraylist<string> names = new arraylist<>(); while (my_input.hasnext()) { string t =my_input.nextline(); if( !t.equals("-1")) names.add(t); } system.out.println("enter name"); string nametocheck = my_input.nextline(); if (names.contains(nametocheck)) { system.out.println("found"); } my_input.close(); }
i'd suggest use arraylist<> because file may contain more 20 names
with normal arrays
public static void main(string[] args) throws filenotfoundexception { file file = new file("names.txt"); scanner my_input = new scanner(file); string[] names = new string[20]; int = 0; while (my_input.hasnext()) { string t = my_input.nextline(); if(!t.equals("-1")) names[i++] = t; } system.out.println("enter name"); string nametocheck = my_input.nextline(); (string temp : names) { if (temp.equals(nametocheck)) { system.out.println("found"); } } my_input.close(); }
Comments
Post a Comment