Making a text file work for an array

hello i am trying to get this text file to work with this program but i keep getting the same output. Zero will be for exit. In the text file the first line tells you how elements will be in the array. the second line are the numbers in each array position. the program is suppose to search for 1 in the array of elements. here is an example of the text file
5
2 3 1 4 5
3
1 9 3
0
    import java.util.*;
   import java.io.*;
    public class Array{
       public static void main(String[] args){
         try{
            Scanner stdin = new Scanner(System.in);
              Scanner fin = new Scanner(new File("array.txt"));
            int positionsOfArray = fin.nextInt();
            while (positionsOfArray != 0){
               int[] elements ={fin.nextInt()};
               for (int i=0; i<elements.length; i++){
                  int searchingOfUnity = elements;
if (searchingOfUnity == 1){
System.out.println("the unity is at position " + searchingOfUnity);
catch(FileNotFoundException e){}

I think what you mean to do is:
import java.util.*;
import java.io.*;
public class Array{
    public static void main(String[] args){
        try{
            Scanner fin = new Scanner(new File("array.txt"));
            int positionsOfArray = fin.nextInt();
            while (positionsOfArray != 0){
                for (int i=0; i<positionsOfArray; i++){
                    int searchingOfUnity = fin.nextInt();
                    if (searchingOfUnity == 1){
                        System.out.println("The unity is at position " + i);
                positionsOfArray = fin.nextInt();
        catch(FileNotFoundException e){}
}

Similar Messages

  • Reading from a text file in to an array, help please

    I have the following
    public class date extends Loans{
    public int dd;
    public int mm;
    public int yyyy;
    public String toString() {
    return String.format( "%d,%d,%d", mm, dd, yyyy );
    public class Loans extends Borrowing {
    public String name;
    public String book;
    public date issue;
    public char type;
    public String toString(){
    return String.format( "%s, %s, %s, %s", name, book, issue, type );
    import java.util.Scanner;
    import java.io.*;
    public class Borrowing extends BorrowingList {
    private Loans[] Loaned = new Loans[20];
    if i want to read in from a text file in to that array how do i do it?

    sorry to keep bothering you and thanks loads for your help but now I am getting the following error mesage
    C:\Documents and Settings\MrW\Menu.java:43: cannot find symbol
    symbol : class IOException
    location: class Menu
    }catch(IOException e){
    Note: C:\Documents and Settings\MrW\Borrowing.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    1 error
    BUILD FAILED (total time: 0 seconds)
    for this line
    }catch(IOException e){                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Do template files work for those not editing in dreamweaver?

    Hi!
    Do dreamweaver .dwt template files work for people who are not making changes with dreamweaver?
    Thanks!

    Better make that a *NO*.  Allowing people to edit Template controlled pages outside of DW will be a catastrophe, unless they are very familiar with DW Templates and how they work.

  • Hi, I'm making hyperlinks. They work for the main page of the webpage, but when I'm trying to redirect the hyperlink to a "sub page" of the webpage it is still going to the main page. (allthough I'm pasting the complete url address)

    Hi, I'm making hyperlinks. They work for the main page of the webpage, but when I'm trying to redirect the hyperlink to a "sub page" of the webpage it is still going to the main page. (allthough I'm pasting the complete url address)

    Hi! first of all, thank you so much for your help.
    I don't know about that panel you are talking about.
    what I do is RIGHT CLICK, INTERACTIVE, NEW HYPERLINK, and a window pops up, where I paste the address (images).
    Where says URL I paste the complete address that the "sub page" gives me.
    Is that correct? (for the main page of the wabepage works correctly)
    thanks!!!

  • Does class-scheme in the coherence config file works for C++ classes?

    Hello,
    Does anyone knows if the class-scheme in the coherence config file works for C++ classes as well? In other words if I have a C++ implementation of com.DBCacheStore will it work?
    <class-scheme>
    <class-name>com.DBCacheStore</class-name>
    <init-params>
    <init-param>
    <param-type>java.lang.String</param-type>
    <param-value>AAA</param-value>
    </init-param>
    </init-params>
    </class-scheme>
    Thanks,
    Jay

    931907 wrote:
    Hello Robert,
    I am refering here to both C++ client and Coherence Server. Will it work in either of the cases?
    Thanks,
    JayHi Jay,
    Coherence server: it definitely won't do anything with C++.
    C++ client: for the cache store of a local cache residing within the C++ client you may be able to specify it, but it will have nothing to do with the cluster itself. I never worked with the C++ client, so I can't guarantee you can configure it that way. Look at the following page for further documentation:
    http://docs.oracle.com/cd/E24290_01/coh.371/e22839/cpp_config.htm
    Best regards,
    Robert

  • Reading characters from a text file into a multidimensional array?

    I have an array, maze[][] that is to be filled with characters from a text file. I've got most of the program worked out (i think) but can't test it because I am reading my file incorrectly. However, I'm running into major headaches with this part of the program.
    The text file looks like this: (It is meant to be a maze, 19 is the size of the maze(assumed to be square). is free space, # is block, s is start, x is finish)
    This didn't paste evenly, but thats not a big deal. Just giving an idea.
    19
    5..................
    And my constructor looks like follows, I've tried zillions of things with the input.hasNext() and hasNextLine() to no avail.
    Code:
    //Scanner to read file
    Scanner input = null;
    try{
    input = new Scanner(fileName);
    }catch(RuntimeException e) {
    System.err.println("Couldn't find the file");
    System.exit(0);
    //Set the size of the maze
    while(input.hasNextInt())
    size = input.nextInt();
    //Set Limits on coordinates
    Coordinates.setLimits(size);
    //Set the maze[][] array equal to this size
    maze = new char[size][size];
    //Fill the Array with maze values
    for(int i = 0; i < maze.length; i++)
    for(int x = 0; x < maze.length; x++)
    if(input.hasNextLine())
    String insert = input.nextLine();
    maze[i][x] = insert.charAt(x);
    Any advice would be loved =D

    Code-tags sometimes cause wonders, I replaced # with *, as the code tags interprets # as comment, which looks odd:
    ******...*.........To your code: Did you test it step by step, to find out about what is read? You could either use a debugger (e.g., if you have an IDE) or system outs to get a clue. First thing to check would be, if the maze size is read correctly. Further, the following loops look odd:for(int i = 0; i < maze.length; i++) {
        for(int x = 0; x < maze.length; x++) {
            if (input.hasNextLine()) {
                String insert = input.nextLine();
                maze[x] = insert.charAt(x);
    }Shouldn't the nextLine test and assignment be in the outer loop? And assignment be to each maze's inner array? Like so:for(int i = 0; i < maze.length; i++) {
        if (input.hasNextLine()) {
            String insert = input.nextLine();
            for(int x = 0; x < insert.size(); x++) {
                maze[i][x] = insert.charAt(x);
    }Otherwise, only one character per line is read and storing a character actually should fail.

  • Importing text file into 2D char array

    Hey folks. I've aged a few years trying to figure this project out. Im trying to make a crossword puzzle and am having problems importing the answer letters into a 2D array of 15*15. The text file would look something like this:
    LAPSE TAP RAH
    AVAIL OLE ODE
    BARGE PARADOX
    etc
    I have JTextFields that the user will answer and a button the user can press to see if the answers are right by comparing the 2D array answer with what the user inputted.-the user input would be scanned and put into a 2D array also.
    How should i go about inserting each letter into an array? The spaces i would later need to make code to grey out the text field. This is what i have so far. Forgive me if its sloppy.
         class gridPanel extends JPanel
              //----Setting Grid variables
              private static final int ROWS = 15;
              private static final int COLS = 15;
              String[] letters = { "A", "B", "C", "D", "E" };// To test entering strings into array
               gridPanel()
                 this.setBackground(Color.BLUE);
                 //.......Making my JTextField grid for user input
                 JTextField[][] grid = new JTextField[ROWS][COLS];
                 for(int ROWS = 0; ROWS<grid.length; ROWS++)
                     for(int COLS = 0; COLS<grid.length; COLS++)
                         grid[ROWS][COLS] = new JTextField(1);
                         add(grid[ROWS][COLS]);
                     //grid[ROWS][COLS].setText("" + letters[0]);
                 String an = null;
                 StringTokenizer tokenizer = null;
                 Character[][] answer = new Character[ROWS][COLS];
              try{
                 BufferedReader bufAns = new BufferedReader( new FileReader("C:\\xwordanswers.txt"));
                 for (int rowCurrent = 0; rowCurrent < ROWS; rowCurrent++)
              an = bufAns.readLine();
              tokenizer = new StringTokenizer(an);
              for (int colCurrent = 0; colCurrent < COLS; colCurrent++) {
              char currentValue = tokenizer.nextToken().charAt(0);//Needs to be changed to reflect each letter
                        answer[rowCurrent][colCurrent] = currentValue;
                    System.out.println(currentValue);
              }catch (IOException ioex)           
                        System.err.println(ioex);
                        System.exit(1);
            }//xword graphics end
          This obviously prints the first char of each word, it also gives me an "Exception in thread "main" java.util.NoSuchElementException" error for some reason.
    Any help is greatly appreciated.
    John

    If the file format is stored as follows:
    APPLE
    L A
    PARSE
    N E
    PEAR then we can parse this into a 2D char array:
    char[][] readMap(String fileName) {
        char[][] ret = new char[ROWS][COLS];
        FileInputStream FIS = new FIleInputStream(fileName);
        int i, j;
        for(i = 0; i < ROWS; i++)
            for(j = 0; j < COLS; j++)
                ret[i][j] = FIS.read();
        FIS.close();
        return ret;
    }Then you can use the resulting 2D char array in your answer checking mechanism.
    Hope this helps~
    Alex Lam S.L.

  • Read words from a text file into an undefined array

    Dear all,
    Does anyone know how to read words in text file, seperated by all types of spaces ("_", "\n", "\t","\r","\f") and put them into a string array to be used later?
    So far I can read the words using the Tokenizer but can't assign to array:
    public class reader
    StringTokenizer tokenizer = new StringTokenizer(input);
    String[ ] array= null;  //unknown size of array
    int i=0;
                   while(tokenizer.hasMoreTokens())
                             array[i] = tokenizer.nextToken();
                             i++;
    Any suggestions welcome!
    thanks in advance!

    Hi
    sorry wrote in a hurry ;) din c the problem clearly
    there are two approaches
    1) best approach for your problem is Vector or ArrayList, these would make life easy for you.
    Always collections are better approach over arrays when the size is dynamic. However in your case the size cant be said to be DYNAMIC. coz the number of words will not grow / shrink during the runtime.. i know that number of words are not fixed but dynamic is something which will grow/shrink during runtime. but still collection is better approach.
    2)dirty approach
    use double dimensional array
    String arr[][] = null;
    then use one tokenizer for StringTokenizer(str,"\n");
    using countTokens on this will give you number of lines.
    use this to initialize array
    arr = new String[lineCount][];
    then iterate from 1 to lineCount and use 1 more tokenizer to get number of words for that line. use this number to initialize the column size for arr[i] like
    arr[i] = new String[wordCount];
    then store the token using nested for loops in this array
    go for the 1st one ;) 2nd one is hedious n time consuming but both will work ;)
    cheers
    amey

  • Making a Text File in Microsoft Virtual Studio Xaml App

    I'm trying to save kinect data to a text file, but first I'm trying to get any text file to start with. I have found a number of places that say to use:
         TextWriter tw = new StreamWriter("TestFile" + ".txt");
          tw.WriteLine("test");
          tw.Close();
    I have "using System.IO;" but I'm still getting errors
    Error 3
    'System.IO.TextWriter' does not contain a definition for 'Close' and no extension method 'Close' accepting a first argument of type 'System.IO.TextWriter' could be found (are you missing a using directive or an assembly reference?)
    C:\Users\Engineering\Documents\Visual Studio 2013\Projects\App1\App1\MainPage.xaml.cs
    164 10
    App1
    Error 1
    The best overloaded method match for 'System.IO.StreamWriter.StreamWriter(System.IO.Stream)' has some invalid arguments
    C:\Users\Engineering\Documents\Visual Studio 2013\Projects\App1\App1\MainPage.xaml.cs
    162 22
    App1
    Error 2
    Argument 1: cannot convert from 'string' to 'System.IO.Stream'
    C:\Users\Engineering\Documents\Visual Studio 2013\Projects\App1\App1\MainPage.xaml.cs
    162 39
    App1
    I think it has something to do with the fact that it's a xaml app or something, but don't know how to fix it. I don't want to remake my code in another type of app. If there is another way to save kinect data other than a text file then I'm all ears. 
    Thank you for your time.

    Hi Thardus,
    From your code snippet, I know that you are working with XAML application (Windows store app or windows phone store app). I would recommend you have a look at the following link to know how to write file to storage file.
    https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh758325.aspx. They are different with desktop application.
    If you still have question, please post more information to clarify the type of project you are using.
    Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. Click HERE to participate
    the survey.

  • Text file convert to string array

    I tried to convert text file to string array. But it is not successful.
     text file :
     SD, 1,2,3,4
     GD, 3,4,5,6
    I use spreadsheet string to Array function but ALL characters is become to zero.
     my result:
      0,1,2,3,4
      0,3,4,5,6
    Solved!
    Go to Solution.
    Attachments:
    convert.vi ‏18 KB

    Hi,
    indeed the solution of GerdW is the way to do it, except for the fact that the while loop isn't needed in this case
    Have fun using LabVIEW
    Kind regards,
    - Bjorn -
    Have fun using LabVIEW... and if you like my answer, please pay me back in Kudo's
    LabVIEW 5.1 - LabVIEW 2012
    Attachments:
    Speadsheet_to_array.JPG ‏27 KB

  • Reading from a text file into a 2D array

    How do you read from a text file and put it into a 2D array? Or if someone could guide me to where I can find the information?

    This tutorial shows how to read a file:
    http://java.sun.com/docs/books/tutorial/essential/io/scanfor.html
    This tutorial shows how to create arrays with multiple dimensions:
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html

  • How to copy data in text file into two-dimensional arrays?

    Greeting. Can somebody teach me how to copy the input file into two-dimensional arrays? I'm stuck in making a matrix with number ROWS and COLUMNS according to the data in "input.txt"
    import java.io.*;
    import java.util.*;
    public class array
        public static void main (String[] args) throws FileNotFoundException
        { Scanner sc = new Scanner (new FileReader("input.txt"));
            PrintWriter outfile = new PrintWriter("output.txt");
        int[][]matrix = new int[ROWS][COLUMNS];
    }my input.txt :
    a,b,c
    2,2,1
    1,1,1
    2,2,1
    3,3,1
    4,4,1
    5,5,1
    1,6,2
    2,7,2
    3,8,2
    4,9,2
    5,10,2

    import java.io.*;
    import java.util.*;
    public class array {
        public static void main(String[] args) throws IOException {
            FileInputStream in = null;
            FileOutputStream out = null;
    try {
        in = new FileInputStream("input.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {
            String split[]=line.split(",");
    catch (IOException x) {
        System.err.println(x);
    } finally {
        if (in != null) in.close();
    }}}What after this?

  • Text file needed for Defor01

    hi,,
         i need the text file for (Delfor01)Idoc type.
    whether its possible to see, if means say me the steps,
    Or Say the links to refer..
    Advance thaks.

    Hi Bala,
    It is possible to generate IDoc in XML format file.
    You need to maintain file port for XML (t/code WE21) and ensure the partner profile (t/code WE20) output pointed to XML file port.
    In this case, when IDoc generated SAP system will take care all conversion format.
    This could be applied for inbound process as well (SAP receives XML file from external system/SAP).
    Hope this will help.
    Regards,
    Ferry Lianto
    Please reward points if helpful.

  • Classic - text ringtones work for one contact but not for others

    Just got the new Blackberry classic.  I'm having trouble with the ringtones for the text messages.  The custom ringtone works for one contact but not for the others.  I have taken the same custom ringtone that works for contact A and used it for contact B but it only works for A.  B sounds the default ringtone from the default profile instead of the custom ringtone.
    I have deleted all contacts and done a re-sync thinking something was corrupt.  That didn't work. 
    None of the contacts have a link. 
    I have changed the notification profile and it still doesn't work. 
    I have deleted a contact and recreated it manually.  It still doesn't work. 
    I finally deleted my dad's  contact and from the phone app created a new contact.  I set a custom ringtone for him and it worked.  I of course had to recreate all his other information manually.  Please tell me there is some other way to fix this than recreating manually all 147 contacts in my contact list.
    I read that if the phone number has the hypen or space it won't work, but my dad's contact info that I created from the phone app has the hypen and it rings with the custom ringtone.  Also contact A has no hypen in the phone number and it rings the custom ringtone.  So that didn't seem to matter. 
    I have spent hours on Google and see that lots of people have had this problem (but not everyone) but have not yet found a solution. 
    Surely someone has found a fix for this issue.

    Make sure that the contact has "Mobile" as the field for her number and not "iPhone".
    Note that the iPad cannot send SMS messages.

  • Verizon iPhone 5 not sending or receiving texts. iMessage worked for a day then stopped or messages were severely delayed.

    New iPhone 5 on Verizon will not send or receive texts. In the beginning iMessage worked for about a day and then messages started to be delayed by hours. Eventually even these messages were not being sent. Reset network settings followed by a soft re-boot land still no change. Any ideas?

    For iMessage problems, try this:
    - Sign out of iMessage
    - Reset your network settings. Settings>General>Reset>Reset Network Settings
    - Sign back in to iMessage
    Best of luck.

Maybe you are looking for

  • Message coming up saying calendar can't find server

    I keep getting this error message.  It says the calendar might be pretending.  What should I do?

  • Suspend not working on Acer Aspire One AO751h

    Hi everyone! New forum user here So, I did a fresh install of Arch on the Aspire One AO751h. I worked out pretty much everything I need except the suspend function. I have 2 main problems with it: A- If I close the lid, the netbook enters immediately

  • Opening pictures in picasa as default

    how to request picasa as default program to open all picture files. i have downloaded picasa on mac 

  • How do you create a photo archive?

    I have a photo album already, shown as 2011 photos. I want to move those photos to an "archive" that would show as only a link on the new photo album page (shown as 2012). I do not want the 2011 "archive" to show in the main menu.

  • HT202157 apple tv full

    I Have 1st generation tv and the memory is now full,if i delete the films on box can i get them back with having to buy them again