I want to write a while-loop with (hasNextLine()) to run the code, and I hope that it can break when I input successive two new-line(with the button "Enter" of the keyboard).
Can I break the loop without any break condition like string.equals(quit) etc;
Scanner sc = new Scanner(System.in);
int[] input_Num = new int [3000] ;
int i = 0 ;
while ( sc.hasNextLine() ){
input_Num[i] = sc.nextInt();
System.out.println(input_Num[i]);
System.out.println(sc.hasNextLine());
}
however, the System.out.println(sc.hasNextLine()); will always return true to break the loop.
It will always turn true until end of file, and while it does the loop will not be broken.
But all you have to do is test for an empty line.
This can do something along the lines of what you want.
Basically, if you want to read lines, you need to read lines. You can't use hasNextLine and then nextInt, they don't work well together.
Scanner scn = new Scanner(System.in);
String line;
int empty = 0;
int input;
while(true)
{
line=scn.nextLine().trim();
if(line.equals(""))
{
++empty;
if(empty==2) break;
}
else
{
empty=0;
input = Integer.parseInt(line);
// ... do stuff with input
}
}
Related
I need to accept some positive integers for which I use a for loop as follows:
Scanner in = new Scanner(System.in);
for(int i=0; i<n; i++) {
num = in.nextInt();
//do something with num
}
This requires me to (a) know number of integers n beforehand (b) Use a counter i
I know Java does not accept non-Boolean expressions in loop conditions. But how can I do the same without n and i?
For example, something like:
while( (num = in.nextInt()) ) {
//do something with num
}
Any type of loop (for/while/do-while) will do.
What you can do is something like:
boolean loop = true;
while (loop) {
int num = in.nextInt();
... do something with n
if (whatever) loop = false;
}
for example.
Or you use while (true) together with if (whatever) break.
In other words: you need a boolean condition, but you can control that condition within your loop body as shown above.
Loop until end of input -or- non-integer input (e.g. "exit", blank line):
while(in.hasNextInt()) {
int num = in.nextInt();
}
If you're testing in IntelliJ and want to indicate EOF explicitly: Ctrl+D or ⌘+D
If you want to read a file as your input: java MyClass < numbers.txt
Here is an example on how to use the scanner class: https://www.tutorialspoint.com/java/util/scanner_nextint.htm
You should use the hasNext() method to end the loop and check for integers with the hasNextInt() method:
public class ScannerDemo {
public static void main(String[] args) {
String s = "Hello World! 3 + 3.0 = 6.0 true ";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// find the next int token and print it
// loop for the whole scanner
while (scanner.hasNext()) {
// if the next is a int, print found and the int
if (scanner.hasNextInt()) {
System.out.println("Found :" + scanner.nextInt());
}
// if no int is found, print "Not Found:" and the token
System.out.println("Not Found :" + scanner.next());
}
// close the scanner
scanner.close();
}
}
I know Java does not accept non-Boolean expressions in loop conditions.
To my knowledge no programing language allows that. The loop either continues or it does not, this is a boolean decision and that requires a boolean conditional. There is no "the loop maybe continues, we don't know".
With that said Java - of course - requires a boolean condition to continue or not. The question you need to answer is: When shall the loop terminate?
There are three options:
The loop continues forever
while (true)
The loop stops at a special input value
while ((num = in.readInt()) != 0)
The loop is broken from outside
while (running) {
// ...
}
public void stopLoop() {
running= false;
}
same as thisquestion I want to get input from user while he/she give me strings. but the difference is that now before I get strings , I must get 26 numbers. so this code works wrong in getting myStrings. what should I do?
Wrong code:
for (int i = 97; i < 123; i++) {
alphabet[i] = scan.nextFloat();
}
String infix;
int i = 0;
String[] myStrings = new String[100];
while (scan.hasNextLine()) {
infix = scan.nextLine();
if (infix.length() > 0) {
myStrings[i] = infix;
i++;
} else {
break;
}
}
edit: wrong means , when I debug it, before I give strings as an input (after giving numbers) , this line :(" while (scan.hasNextLine()) ") passes , and infix in this line( infix = scan.nextLine(); is "") so the while , doesn't work correct. and break after that.
The issue is that after reading a float from the scanner, a newline "\n" is left in the scanner, this means that when the first scan.nextLine() runs, it gets that leftover newline, which results in your code hitting the else block, and breaking out of the loop.
You can either get the next line before your loop:
String infix;
int i = 0;
String[] myStrings = new String[100];
infix = scan.nextLine(); //Get it here to throw away the new line
while (scan.hasNextLine()) {
infix = scan.nextLine(); //Should contain whatever the user entered
//code
}
Or, when you get the float from the loop, you can use Float.parseFloat() combined with scan.nextLine(), like so:
for (int i = 97; i < 123; i++) {
alphabet[i] = Float.parseFloat(scan.nextLine());
}
Which will stop there from being a new line left in the scanner after you receive the last float
That's a common issue in Java. After getting the input from user using Scanner like nextInt();, nextDouble(); etc, you need to consume a line with a empty scan.nextLine();, because those methods doesn't consume the new line expression "\n". , before you can get some strings.
I have a class that takes input from the Scanner class and outputs via the PrintWriter class. When the program hits the for loop it automatically runs the first iteration without waiting to get input from the user.
It should read Insert item 1:
However it reads Insert Item 1 Insert Item 2.
After the first iteration everything runs fine.
Any help in regards to why this is happening would be greatly appreciated.
InputSplicer(Scanner input)
{
this.input = input;
array = new ArrayList<String>();
}
void splice()
{
System.out.println("What is the output file destination?");
outputFile = input.next();
outputFileFile = new File(outputFile);
try {
output = new PrintWriter(outputFileFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("How many items are in the query?");
lengthOf = input.nextInt();
for(int i = 1; i <= lengthOf; i++)
{
System.out.println("Insert item " + i);
//spaces in output are not working for example item 1 cannot equal jason tavano can equal jasontavano
s = input.nextLine();
s.trim();
if(s.equalsIgnoreCase("null"))
{
s = "";
}
if(i != lengthOf)
array.add(s + pipe);
else
array.add(s);
}
for(int i = 0; i < array.size(); i++)
output.print(array.get(i));
output.close();
}
}
Scanner.nextInt() does not read the remaining new line character that follows it. Later Scanner.nextLine() reads in characters from the stream until a new line character is found. You should use Scanner.nextLine() after using Scanner.nextInt() to begin read the lines following the number.
problem:
s = input.nextLine();
When you input the number from the nextInt it will consume the newLine character from it thus iterating to the second loop in your for loop
solution:
consume the newLine character first before going to the loop
sample:
System.out.println("How many items are in the query?");
lengthOf = input.nextInt();
input.nextLine(); //will consume the newLine character from the input lengthOf
The nextInt() method doesn't remove the enter char from the stream, so you should clear the stream after that to clear the remaining of that line.
The simplest way to clear it would be to call a nextLine() before starting the loop
SO I'm supposed to determine the number of lines in a text file (a 100 lines containg numbers) and then create an array with the the number of lines, but the first while loop used to find out the number of lines in the text file never exits. The second loop which is the exacts same one works just fine. Please help me out!
static void main(String[] args) throws Exception{
java.io.File file = new java.io.File("seriesOfNumbers.txt"); //file instance
Scanner input = new Scanner(file); //Scanner
int M =0 ;
while (input.hasNextLine() && !input.equals(null))// ** Loop never exits, tried almost everything
{
k++;
}
double[] numberArray = new double[k];
int V = 0;
while (input.hasNextLine())// When I exit the first loop this one exits just fine
{
numberArray[j] = (double) input.nextInt();
j++;
}
You are never consuming your input in the first loop, do that with input.nextLine().
You are now looping until input.hasNextLine() becomes false, but that never happens, because you do not consume the input.
Use input.next() to move to next line. In While condition you are checking the has next line and not null. Thats y it is in infinite loop.
In this below code,
this is initialising
Scanner input = new Scanner(file); //Scanner
This is reading
int M =0 ;
while (input.hasNextLine() && !input.equals(null))
{
input.nextLine(); // Use this to advance the lines from scanner
k++;
}
It seems to me that you could use FileUtils class from apache.commons.io project to do the trick.
static void main(String[] args) throws Exception{
List<String> lines = FileUtils.readLines(new File("..."));
Now, if you really need the numberArray for some other computation, you can
double[] d = new double[lines.size()];
Or you can use the Collection to iterate
for (String line : lines) {
double n = Double.parseDouble(line);
To use FileUtils, take a look at http://commons.apache.org/proper/commons-io/
But, iof all that you want is to know what is wrong with your code, you should call the method Scanner.nextLine() inside your first while loop.
In order to stop the infinite looping of the while loop even after consuming the required inputs, we can use a break statement.
Here is an example,
while (scanner.hasNextLine()) {
String[] arr = scanner.nextLine().split(" ");
long[] ar = new long[n];
for (int i = 0; i < n; i++) {
ar[i] = Long.parseLong(arr[i]);
}
long result = sum(ar);
System.out.println(result);
break;
}
I'm doing an school exercise and I can't figure how to do one thing.
For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.
This is the problem.
The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.
I've done this:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please insert text:");
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
But this is not working properly and I can't figure it out.
Ideally, if the user enters:
This is line one
This is line two
and now press enter, wen printing the array it should give:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Can you help me?
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
Here's the typical readline idiom, applied to your code:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
text[i] = line;
i++;
}
The code below will automatically stop when you try to input more than 10 strings without prompt an OutBoundException.
String[] text = new String[10]
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++){ //continous until 10 strings have been input.
System.out.println("Please insert text:");
string s = sc.nextLine();
if (s.equals("")) break; //if input is a empty line, stop it
text[i] = s;
}