-1

I do not know how to take the integer and ignore the strings from the file using scanner. This is what I have so far. I need to know how to read the file token by token. Yes, this is a homework problem. Thank you so much.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ClientMergeAndSort{
public static void main(String[] args){

 int length = 13;

try{
  Scanner input = new Scanner(System.in);
        System.out.print("Enter the file name with extention : ");
        File file = new File(input.nextLine());

        input = new Scanner(file);


        while (!input.hasNextInt()) {
           input.next();

        }
         int[] arraylist = new int[length];

        for(int i =0; i < length; i++){
        length++;
        arraylist[i] = input.nextInt();
        System.out.print(arraylist[i] + " ");    
        }  
    } catch (Exception ex) {
        ex.printStackTrace();
    }



}

}

5
  • 1
    First; welcome to Stack Overflow! At least one person has downvoted your question, and it's at least worth telling you (probably) why. Questions that are obviously homework are usually bad... unless you openly admit "this is homework", which you did. (Good!) However, the title of this post is confusing; you should consider changing it, to avoid downvotes.
    – Dean J
    Commented Apr 11, 2015 at 19:02
  • You can remove "Java" from the title; you used that in the tags, and putting the language in the tags is generally enough on this site.
    – Dean J
    Commented Apr 11, 2015 at 19:02
  • For the rest, "how to remove non-integers from a text file" or "how to get only integers from a file using a Scanner" are probably good.
    – Dean J
    Commented Apr 11, 2015 at 19:03
  • One bit on the question; if you need to use a Scanner, it might help to say so. If you don't need to use a Scanner, people could give different answers here.
    – Dean J
    Commented Apr 11, 2015 at 19:03
  • 1
    Overall: don't let people downvoting your questions ever slow you down from asking more questions; just try to figure out why they downvote and fix it in the future.
    – Dean J
    Commented Apr 11, 2015 at 19:04

4 Answers 4

2

Take a look at the API for what you're doing.

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()

Specifically, Scanner.hasNextInt().

"Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."

So, your code:

while (!input.hasNextInt()) {
    input.next();
}

That's going to look and see if input hasNextInt().

So if the next token - one character - is an int, it's false, and skips that loop. If the next token isn't an int, it goes into the loop... and iterates to the next character.

That's going to either: - find the first number in the input, and stop. - go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going.

  • Write down in words what you want to do here.
  • Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet.
  • Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it.
  • Read the file first. Then display it as you read it, so you know it works.
  • Then worry about if it has numbers or not.
0
1

A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask.

Have a nice programming.

1
    import static java.nio.file.Files.readAllBytes;
    import static java.nio.file.Paths.get;

    import java.io.IOException;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Test {
       public static void main(String args[]) throws IOException    {
            String newStr=new String(readAllBytes(get("data.txt")));        
            Pattern p = Pattern.compile("-?\\d+");
            Matcher m = p.matcher(newStr);
            while (m.find()) {
              System.out.println("- "+m.group());
            }
}
}

This code fill read the file and then using the regular expression you can get only Integer values.

Note: This code works in Java 8

0
1

I Think This will work for you requirement.

Before reading the data from the file initially,try to write some content to the file by using scanner and filewriter then try to execute the below code snippet.

File file = new File(your filepath);
        List<Integer> list = new ArrayList<Integer>();
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String str =null;
            while(true) {
                str = bufferedReader.readLine();
                if(str!=null) {
                System.out.println(str);
                char[] chars = str.toCharArray();
                String finalInt = "";
                for(int i=0;i<chars.length;i++) {
                    if(Character.isDigit(chars[i])) {
                        finalInt=finalInt+chars[i];
                    }
                }

                list.add(Integer.parseInt(finalInt));
                System.out.println(list.size());
                System.out.println(list);
        } else {
            break;
        }
            }
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

The final println statement will display all the integer in your file line by line.

Thanks

1
  • Thank you so much for giving ur time to answer my question.
    – happy face
    Commented Apr 13, 2015 at 1:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.