You can use a while loop that uses the hasNext() function. Like so: while(scan.hasNextLine()) {...} Also, you can check if the text file you are reading from has no extra lines at the end. You can also try just .hasNext()...
java,java.util.scanner,contains,string-concatenation
When using UNIX line endings (\n) in your text file, your program produces the output you expect. If however you use dos line endings, you (almost) get the output you describe. The true output I see is: words otestingo for otestingo testing otestingo false You're probably not on a UNIX...
java,loops,for-loop,java.util.scanner
You're calling scanner.next() twice. The first time all you do is print it out, and then discard it. Try putting it in a variable instead: //this could use scanner.nextInt() instead int limit = Integer.parseInt(scanner.next()); System.out.println(limit); for (int i = 0; i < limit; i++) { //... ...
Use a regular expression or pattern to grab the digits from the line. If you want to throw an exception: Pattern pattern = Pattern.compile("\\d+"); String s = scanner.nextLine(pattern); System.out.println(s); If you don't... Pattern pattern = Pattern.compile("\\d+"); String s = scanner.nextLine(); Matcher matcher = pattern.matcher(s); if (matcher.find()) { System.out.println(s.substring(matcher.start(), matcher.end())); }...
Not a big IO guy, but from what I remember in school (using C, not Java), often times we would put an escape at the end of a file (in your case, the last line could be "0 EOF") and then when number == 0 and name.equals("EOF"), you know to...
It would seem that after you pass if (lineFromFile.contains(entry.key)) in your parseFile(String s) method, you would want to know if your user entered input contains any of the entry.syns and replace the synonym with the key // This is case sensitive boolean synonymFound = false; for (String synonym : entry.syns)...
java,if-statement,java.util.scanner
If you want to call writer if not found, then you must use: if (!found) writer(); Your break is only terminating the inner loop, you might want to add an if (found) break; to terminate the outer loop as well (you did not say if this is required or not)....
java,while-loop,java.util.scanner
scan.nextInt will remove only the "2" from the input stream. The "\n" (new line) you enter when you press enter is still in the input stream; the first nextLine call will therefore return an empty line. To clarify: // assuming we enter "2\ntest\n" at the command line Scanner s =...
java,swing,java.util.scanner,joptionpane
dinesh, input.nextInt() - will wait for the user to enter integer value in the console. once you entered the value click enter. then your messagedialogue box will be displayed. use this code for showing the user entered value in message box: JOptionPane.showMessageDialog(null, String.valueOf(sample)); keep learning.....
java,methods,while-loop,switch-statement,java.util.scanner
Creating Scanner once either in main, or in the constructor as a class level object will be much cheaper than creating every time you call the input method. If created at class level it can be used directly in input method, otherwise if it is created in main method it...
java,while-loop,count,java.util.scanner
you can calculate the words,lines with the following code public static void printWordsOfLines(Scanner x){ Scanner line=x; Scanner word=x; int lines = 0; System.out.println("Enter q to quite input"); int words=0; while(line.hasNextLine()){ String xx=line.next(); String w[]=xx.split(" "); String l[]=xx.split("\n"); words+=w.length; lines+=l.length; if(xx.equals("q")) break; else x.nextLine(); } System.out.println("lines: " + lines); System.out.println("words: "...
More Simple Version: public static void main(String[] args) { int[] nmberchck = new int[51]; int[] numbs = new int[15]; Scanner sc = new Scanner(System.in); System.out.println("Enter 15 numbers that are between 0 and 50 "); System.out.println(); for (int i = 0; i < 15; i++) { numbs[i] = sc.nextInt(); } for...
java,loops,console,java.util.scanner
You're closing the scanner near the end of the method. That closes the stream it's working on - System.in in this case. That means next time you call the method, the stream is still closed, so there are no lines. You should set up one Scanner, and pass that into...
This is because Smith\nScuba becomes one token. (There's no , separating them.) Using file.useDelimiter(",|\n"); solves the problem. If you happen to be using Java 8, I'd recommend using something like: Files.lines(Paths.get("input.txt")) .forEach(line -> { Scanner s = new Scanner(line); s.useDelimiter(","); System.out.println(s.next() + " " + s.next()); }); ...
You need to change fileContents += fileScanner.nextLine(); or fileContents =fileContents + fileScanner.nextLine(); With your approach you are reassigning the fileContents value instead you need to concat the next line....
java,text-files,java.util.scanner
Looks like you have a bug in the regex. * is the wildcard for 0 or more matches so ",|\\s*" will match the empty string. Try ",|\\s+".
Below is a simple example of reading a file char by char , and appending a new line after 16 characters Excerpt from How to read an input file char by char using a Scanner? public class FileReader { public static void main(String[] args) throws FileNotFoundException { StringBuilder stringBuilder =...
Scanner A Scanner does split the input into tokens, splitted by a delimiter (nice explanation http://www.tutorialspoint.com/java/util/java_util_scanner.htm), by default it is a whitespace. Since you don't have any delimiting characters, the first token is the whole string, so your pattern in hasNext should match the whole string and not only parts...
Without any testing I would think you would need something like this Scanner in = new Scanner(System.in); int a,b,n,t; String input_line; String[] input_numbers = new String[3]; t = in.nextInt(); in.nextLine(); input_line = in.nextLine(); while(!input_line.equals("")){ input_numbers = input_line.split(" "); // do what you want with numbers here for instance parse to...
java,list,java.util.scanner,poker
First thought i have is that you should do Player objects. It would consist in : - 2 poker cards - The amount of money the player/dealer has Now the methods : GetStack(); Returns the stack of the player MakeBet(double BetSize); Take away BetSize from player stack and put it...
java,string,if-statement,java.util.scanner
The easiest algorithm I can think of is: For each character inputted, remove all occurences from the string. At the end, check if string is empty. Or in code: char[] cs = new char[] {'h', 'e', 'l', 'o', 'p'}; String s = "hello"; for (char c : cs) s =...
The problem lies in the code here: for(int i=0; (i=br.read())>-1;){ tempLigne = br.readLine().split(" "); for(int j=0; j<tempLigne.length; j++){ if(tempLigne[j].equals("0")){ countZeros++; }else if(tempLigne[j].equals("1")){ countOnes++; } } } br.read() actually reads one character. Instead of processing that character, you discard the result by reading the remaining whole line by br.readline(). Since there...
string,if-statement,java.util.scanner
You need to use equals to compare strings if(test == "y") becomes if (test.equals("y")) Same for "n" obviously. == test for reference equality, but you're looking for value equality, that's why you should use equals, and not ==....
You are not providing enough input. The loop: for(int i=0;i<n;i++) { int idx = map.get(sc.next()); int gift = sc.nextInt(); int M = sc.nextInt(); int reminder =gift%M; int dev = gift/M; money[idx]=reminder; money[idx]-=gift; } will run 3 times, as per your input and in every run it will expect one string...
Strings are immutable which means that you can't change their state. Because of that replace doesn't change string on which it was invoked, but creates new one with replaced data which you need to store somewhere (probably in reference which stored original string). So instead of parts[0].replace("\"", ""); you need...
Your problem lies in your compare method; using == compares reference values. Since you are using different object in your comparisons, they will never have the same reference value in this case. You need to use .equals(Object) to compare the exact values. I have edited the code below to reflect...
The following appends a student record to the file. Irrespective of the old contents. public class Student { private static final char SEPARATOR = ','; private static final String NEWLINE = "\r\n"; private static final Charset CHARSET = StandardCharsets.UTF_8; public void addStudentInfo() throws IOException { Path path = Paths.get(".../student.txt"); StringBuilder...
java,io,java.util.scanner,fileinputstream
Files contain bytes. FileInputStream reads these bytes. So if a file contains one byte whose value is 49, stream.read() will return 49. If the file contains two identical bytes 49, calling read() twice will return 49, then 49. Characters like 'a', '1' or 'Z' can be stored in files. To...
java,runtime-error,java.util.scanner,space
You can use InputStreamReader wrapped around BufferedReader: BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); reader.readLine(); // this will read two words ...
java,while-loop,java.util.scanner
You are reading too much from the scanner! In this line while (sc.nextLine() == "" || sc.nextLine().isEmpty()) you are basically reading a line from the scanner, comparing it (*) with "", then forgetting it, because you read the next line again. So if the first read line really contains the...
it gets complicated when you use nextInt() and nextLine() together. you can try this version which only uses nextLine(); public static void main(String args[]){ Scanner one = new Scanner(System.in); System.out.print("Enter Id"); String number =one.nextLine(); int e = Integer.parseInt(number); System.out.print("Enter Your Name"); String f = one.nextLine(); Student1 s = new Student1();...
java,arrays,multidimensional-array,java.util.scanner
Nudge : You do not directly insert number into array, you insert it into some temporary variable, checks it and then decide if you save it or you ask again (while cycle needed) Spoiler 1 : Here is complete solution, if you want to do it yourself, do not look...
The problem is not with entering the character, but rather with printing it to console. Your console does not appear to support the code point \u2227 of ∧, so it prints a question mark instead. You should test if console lets you input ∧ correctly by printing the numeric representation...
java,java.util.scanner,data-validation
Interesting problem! What happens is that the Scanner attempts to translate the non-integer to an integer, and realizes it can't -- so it throws an InputMismatchException. However, it only advances past the token if the translation was successful. Meaning, the invalid string is still in the input buffer, and it...
java,if-statement,java.util.scanner
You probably called scan.next(), or something like that, before entering the do-while loop. That left a next line character in the input, and the call to scan.nextLine() consumed it. To fix it, you could place a scan.nextLine() call right after scan.next() so it will consume the next line before entering...
java,conditional,java.util.scanner
I believe that you do need the input.next() call despite what Vivin says. If you can't read an integer from the next line of stdin then you will end up in an infinite loop. Furthermore, you should handle the case where you run out of lines of stdin to process,...
java,string,int,java.util.scanner
From what I can see it appears that the readLine() is just consuming the newline left after the int was taken from the buffer. A better way to fix this is to use nextLine() to get a string value and convert it: int icNumber = Integer.parseInt(input.nextLine()); ...
The problem appears to be your getHigherLower method, specifically these two while blocks: while (guess > randomNumber) { System.out.println("lower"); guess = getGuess(console); guessIncreaser++; } while (guess < randomNumber) { System.out.println("higher"); guess = getGuess(console); guessIncreaser++; } If the user guessed a number lower than randomNumber, then higher, both while blocks would...
Change scanner.next() To scanner.nextLine() From the javadoc A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Calling next() returns the next word. Calling nextLine() returns the next line. ...
You are doing everything right, but you are not adding the last pair to the list. You can fix this problem by adding this code after the loop: if (current == 2) { temp.add(couple); } Demo 1 Your approach is not ideal, though: rather than reading one integer at a...
java,file,input,java.util.scanner,scan
Try this code with the try-catch block and let me know if it worked or not. // sometimes the compiler complains if there was a scanner opened without a try-catch block around it try { final File FILE1 = new File("text1.txt"); //it is always a good thing to make a...
java,csv,java.util.scanner,reader
hasNext() can also take a pattern, which provides quite a nice way to check this: String pattern = ".*,.*"; while (scan.hasNext(pattern)) { ... } ...
java,arrays,string,for-loop,java.util.scanner
Please note: String java.util.Scanner.next() - Returns:the next token String java.util.Scanner.nextLine() - Returns:the line that was skipped Change your code [do while initial lines] as below: names[i] = keyboard.next(); ...
java,matrix,int,java.util.scanner
If that's the actual file content it looks like you're exceeding the bounds of your array when it reads in 3 20 There is no [3][20] allocated in life, it would only go out to [3][19]. This is being obscured by your try/catch block which catches and drops the ArrayIndexOutOfBoundsException....
java,inputstream,java.util.scanner
Try this instead ByteArrayInputStream is = new ByteArrayInputStream("Hello World!!".getBytes()); if(is.markSupported()){ is.mark("Hello World!!".length()); } System.out.println(getStreamContent(is)); is.reset(); System.out.println("Printed once"); System.out.println(getStreamContent(is)); Things to note: I changed the variable type from InputStream to the instance type so I could call the methods specific to that type (mark, reset and markSupported ). That allows the...
java,string,if-statement,while-loop,java.util.scanner
A suggested improvement although could be re-factored even further; System.out.println("\nEnter item's price"); Scanner newItemPriceSC = new Scanner(System.in); while (true) { System.out.println("Please type \"no more\" if there are no more items"); String answ = newItemPriceSC.nextLine(); if (!answ.equalsIgnoreCase("no more")) { System.out.println(answ.matches("\\d*") ? "Item price: " + answ : "Please enter a numerical...
java,search,text-files,java.util.scanner
Can you once try this method with slight change? public static void parseFile(String s) throws IOException { File file = new File("data.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { final String lineFromFile = scanner.nextLine(); if (lineFromFile.contains(s)) { System.out.println(scanner.nextLine()); // code hangs right here. } } } Once it finds...
Once the object is created, you won't be able to invoke another constructor with it. Instead, create a method that takes care of changing the fields. Put this as your method call to set the attributes: Node n1 = new Node(); n1.set(ticks,jobId,name); And then in Node, use this instead of...
java,string,java.util.scanner,system.in
You want to print "\n" so why don't you print it? while (sc.hasNextLine()){ x+=sc.nextLine() +"\n"; } ...
Alright, let's elaborate with some simplified explanation about the Scanner class. It is a standard Oracle class which you can use by calling the import java.util.Scanner. So let's make a basic example of the class: class Scanner{ InputStream source; Scanner(InputStream src){ this.source = src; } int nextInt(){ int nextInteger; //Scans...
java,floating-point,integer,java.util.scanner,inputmismatchexception
You should type it like 2,5 not 2.5 ( i think this only happens in Netbeans, funny fact that it get parsed to 2.5 ) run: 2,5 Your number is 2.5 Using the notation 2.5 in Netbeans. run: 2.5 Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextFloat(Scanner.java:2345)...
java,methods,menu,java.util.scanner
Remove the in.close(). Your Scanner in wraps the global System.in, once you close() it you will not be able to use nextInt(). You could extract the Scanner to a field (or an argument) like public static int menu(Scanner in) { // Scanner in = new Scanner(System.in); // ... // in.close();...
java,arraylist,java.util.scanner,bluej
next() returns only one token (word), so for data like The Prince first next() will return "The" second next() will return "Prince" (so it will not wait for input from user since it already has its token). If you want to read more then one word read entire line with...
A Scanner can read token by token. A token is a part of the input which is split with the delimiter. From the API: A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of...
What do you think Virus is? It is malicious lines of codes than when executed may result in output that you may not desire. By your code you are simply reading content of a web site and printing it in your console. That should not affect anything....
java,file-io,java.util.scanner
As much as the people above would like you to do this on your own I will answer this question because I remember how difficult it was to learn. As long as you learn from the and don't just copy them this should be useful. Scanner sc = new Scanner(System.in);...
java,methods,input,console-application,java.util.scanner
When you call int userInput = reader.nextInt();, the userInput varable is only defined in the scope of the setInputValue() method, so currently there is no way for you to access the input after it was entered. You could either make userInput an instance variable, or you could just return the...
java,arrays,multidimensional-array,java.util.scanner
You are missing some integers because you do next twice: fileScannerTileMap.nextInt(); and fileScannerTileMap.next(); Try that: if (fileScannerTileMap.hasNextInt()) { tileMap[xCoord][yCoord] = fileScannerTileMap.nextInt(); } else { fileScannerTileMap.next(); } And break the loop when you are done: if (mapWidth - 1 == xCoord) { yCoord++; xCoord = 0; // add this: if (mapWidth...
To make it simple use regex. With pattern "\d+" it will extract all numbers which you can use as you need it. Look at the code. Pattern p matches next digit, Matcher m applies this pattern to the string and then m.find() method extracts next group (digit number with pattern...
java,file,text,java.util.scanner
The scanner is including the carriage return character(s) as part of the next readable token which produces an invalid integer. You could do Scanner scanner = new Scanner(new File("readhere.txt")).useDelimiter("#|\r\n"); ...
java,floating-point,java.util.scanner
Since you're using nextFloat() you must be sure that you enter a floating number, otherwise clear the scanner with next() public static void main(String[] args) throws Exception { while (true) { System.out.print("Enter a float: "); try { float myFloat = input.nextFloat(); if (myFloat % 1 == 0) { throw new...
Change the code in the if block in parsefile to String temp = scanner.nextLine(); System.out.println(temp); System.out .println(" Would you like to update this information ? "); String yellow = forget.nextLine(); if (yellow.equals("yes")) { removedata(temp); // NoSuchElementException // error } else if (yellow.equals("no")) { System.out.println("Have a good day"); // break; }...
It is not mandatory but it is considered best to close it in case you want change your code and want to use stream. It is considered a recommended and a good practice. The Oracle docs says: Closes this scanner. If this scanner has not yet been closed then if...
java,arrays,arraylist,data-structures,java.util.scanner
In order to print an object with System.out.println you need to implement the toString() method the class you want to print.
java,file,text,java.util.scanner
Read your file line-by-line using a BufferedReader, and for each line perform a split on the first occurrence of : within the line (and if there is no : then we ignore that line). Here is some example code - it avoids the use of Scanner (which has some subtle...
java,exception,java.util.scanner
I think you meant to close in your finally. finally{ //finally begins input.next(); } should (almost certainly) be finally{ input.close(); } Or you could use try-with-resources to close your Scanner like public void populateData(String dataFile) { try { URL url = getClass().getResource(dataFile); File file = new File(url.toURI()); try (Scanner input...
java,java.util.scanner,delimiter
You're splitting each line into two values, then creating two new Sales objects with each of them, and each new Sales object is parsing the same value for productCode and quantitySold. Get rid of the strScan in your main method and pass the whole line into the Sales constructor. Then...
Works fine. Try this as a fully working class (save it as myInput.java, then compile it using javac myInput.java , then run it using java myInput): import java.io.*; import java.util.Scanner; class myInput { public static void main(String[] args) { //Retrieve name System.out.println("What name would you like to search for? (Enter...
java,java.util.scanner,console-input
If by running console input as java statements, you mean taking the exact input from the console and run it inside your application, you need to compile and run them. You can do so using the Compiler API
java,java.util.scanner,conditional-statements
I suggest you to use the regular expression in the hasNext() function as follows to have a finer control, for example use the following pattern if you look for the numbers, sc.hasNext("[0-9]+") Here is the documentation for the hasNext(String pattern) function, public boolean hasNext(Pattern pattern) Returns true if the next...
java,java.util.scanner,inputmismatchexception
Blame the French locale: it uses comma as a decimal separator, so 1.9 fails to parse. Replacing 1.9 with 1,9 fixes the problem (demo 1). If you would like to parse 1.9, use Locale.US instead of Locale.FRENCH (demo 2). A second problem in your code is the use of \\n...
Reading input from the command line with the scanner can be done by doing the following Scanner s = new Scanner(System.in); System.out.print("Input name, age, address, city: "); String input = s.next(); ...
Compare String by equals not by == if((input.trim()).equals("y")){ equals compares the value == comapres the reference...
This is most probably a character set issue, caused by the fact that the platform you are running your java code uses by default a different set; it is always a good practice to specify the expected/needed character set to be used when parsing, and with the Scanner class is...
You really should use some kind of html parsing library. A quick google search revealed this http://jsoup.org/. It seems easy to use. Calling Elements divs = doc.select("div[specific-tag]"); should yield the divs and then you can extract the specific-tag attribute....
Although you are not putting the complete code. But it seems you are using the same scanner to read the integer and the strings which is causing you the problem. This line try to read the remainder of the line containing the int which is empty. r.setNameAndTel(in.nextLine()); Add another in.nextLine()...
java,multidimensional-array,java.util.scanner
Add a input.nextLine(); after your int options = input.nextInt(); This is because: nextInt method does not read the last newline character (of your integer input) that newline is consumed in the next call to nextLine causing name 'to be skipped' so you need to 'flush away' the newline character after...
Newline is most likely causing you issues. Try this public class TestScanner { public static void main(String[] args) throws IOException { try { Scanner scanner = new Scanner(new File("data.txt")); scanner.useDelimiter(System.getProperty("line.separator")); while (scanner.hasNext()) { String[] tokens = scanner.next().split("\t"); for(String token : tokens) { System.out.print("[" + token + "]"); } System.out.print("\n"); }...
You should not use the number from input in the for loop for(int i = 0; i < amount; i++){ What if I entered 0? The program would not run a single loop. Try this, it should be valid. I've made some comments for you in the code. int array[]...
java,debugging,while-loop,java.util.scanner
I made it more simpler. Please try this. I removed other unknown methods from my code. Scanner sc = new Scanner(System.in); int bet = 0; do { bet=sc.nextInt(); } while (bet > cash); return bet; Say if you pass cash as 100, then you typed 200 as bet, it will...
java,multithreading,java.util.scanner
I believe the line scan = new Scanner(zf.getInputStream(ze)); is creating the problem. What I understand from you code is scan is an instance variable which you are assigning a new Scanner with every thread. I would suggest to make it as a local variable in your method. Correct me If...
Well, maybe not the best idea, but a simple solution would be to encapsulate parseInt in a try/catch: int theValue = 0; try { Scanner input = new Scanner(file); while (input.hasNextLine()) { String value = input.next(); try{ theValue = Integer.parseInt(value); }catch (Exception e){ //Just ignore it and carry on. }...
java,recursion,java.util.scanner
You're not clearing the squares on the board when you backtrack. So if you recurse down one potential path, fail and then try another path, the squares are still marked from the first attempt so the second attempt fails too, even though it might have been possible. array[x][y] = n;...
java,multithreading,java.util.scanner,nio
Your KeyPressThread is only testing once: This will make it watch constantly. public void run() { while(true) { if (inputReader.hasNext()) { String input = inputReader.next(); if (input.equals("[")) { rand+=100; System.out.println("Pressed ["); } if (input.equals("]")) { rand-=100; System.out.println("Pressed ]"); } if (input.equalsIgnoreCase("Q")) { break; // stop KeyPressThread } } } }...
java,text-files,java.util.scanner
Don't keep closing std input every time you call the getInput method. Scanner::close closes the underlying stream. Create the Scanner outside and keep using it. Create it somewhere where it lives till the last time you call getInput. Pass the Scanner object to the getInput method. Scanner sc = new...
Your code is fine, but it seems you misplaced it within your class. Check where you put your code, it should be placed within a constructor, method or - very unlikely in your case - static initialization block. private void foobar() { // Do some cool stuff... Scanner inputTreeOne =...
java,java.util.scanner,joptionpane
It does appear after the input is read by the Scanner. It's just not appearing as the top level window. See JOptionPane won't show its dialog on top of other windows for how to solve this.
You should not read from the Scanner several times. Just read the number once via nextInt into the variable and check it. Otherwise on every if branch you will be prompted for a new number. public int validateScore(Scanner sc) { int score = 0; System.out.println("Please Enter Student's Score."); for (;;)...
This pattern should be alright: (?i)(date)(?:\/|\s*)(text)(?:\/|\s*)(number) Java string in code: var pattern = "(?i)(date)(?:\\/|\\s*)(text)(?:\\/|\\s*)(number)"; Output: Match 1: 0: [11,32] Date/text number 1: [11,15] Date 2: [16,20] text 3: [26,32] number Match 2: 0: [45,66] Date Text/number 1: [45,49] Date 2: [55,59] Text 3: [60,66] number Match 3: 0: [81,107] Date Text number 1: [81,85] Date 2: [91,95] Text 3: [101,107] number ...
java,exception,java.util.scanner
When you enter "2 3" (Two integers with a space between them) the scanner.nextInt() will pull in the 2 and leave the 3 still in the scanner. Now, when the next nextInt() is called it will pull in the 3 that was left without the user having to enter anymore...
java,csv,java.util.scanner,delimiter
Your code fails when it tries to read the first balance. Since your delimiter is only a comma (,). It tries to read 24.98<new-line>200 as a double. We can use a comma and a new line character as delimiters using a Pattern. import java.util.regex.Pattern; Pattern delimiter = Pattern.compile(",|\\s"); input =...
Assuming that this file will always be in the same format here's a snippet that does what you want with no checking to make sure that anything is in the wrong place/format. //Create a new scanner pointed at the file in question Scanner scanner= new Scanner(new File ("C:\\Path\\To\\something.txt")); //Create a...