简体   繁体   中英

i need help for my code which uses scanner

i am writing a code that reads input from a file and writes into another after some processing ofcourse. now, my input file is,

4
0 1
0 2
0
0 3
3
0
0
0
E

and what i need to do is copy elements on left to an array in first column and elements on right to second column. i used scanner but it does not recognize end of line. help me!!!! this is what i tried. i tried copying lines and then modifying it.

for (i = 0; i < size; i++) {
    if (!f1.hasNext(endPage)) {
        String temp1 = f1.next();

        String temp2 = f1.next();

        int a[] = new int[4];
        a[0] = (int) temp1.charAt(temp1.length() - 1);
        a[1] = (int) temp2.charAt(temp1.length() - 1);
        a[2] = (int) temp1.charAt(temp1.length() - 2);
        a[3] = (int) temp1.charAt(temp1.length() - 2);
        scales[i].weightOnLeft = a[0];
        scales[i].weightOnRight = a[1];
        scales[i].left = scales[a[2]];
        scales[i].right = scales[a[3]];

    }
}

Try this way:

Scanner input = new Scanner(new File("..."));
while(input.hasNextLine())
{
   String data = input.nextLine();
}

Try to use the Scanner to read line by line and then split(on space, in your case) your line to get the tokens.

Scanner f1 = new Scanner(new File("yourFileName.extn"));
while(input.hasNextLine()) {
   String line = f1.nextLine();
   String[] tokens = line.split(" "); // Splitting on space
   // Do what you want with your tokens
   // Since not all lines have equal no. of tokens, you need to handle that accordingly
}

Try like this below:- In your first column it will store on array[0] and second column value will store on array[1]. Also for second column you need to check the condtion as written below. Please follow:-

    File file=new File("/Users/home/Desktop/a.txt");
    String[] aa=new String[2];
    try {
        Scanner sc=new Scanner(file);

        while (sc.hasNextLine()) 
        {
            String ss=sc.nextLine();
            aa=ss.split("\\s");
//it will store left column value in this index
            System.out.println("aa[0]"+aa[0]);
            if(aa.length>1) 
            {
//it will store right column value in this index
            System.out.println("aa[1]"+aa[1]);
            }

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM