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;
}
Related
I am making program that add all the number from user input until 0 comes. when 0 comes as input, I want to show all the numbers that are saved. When I run the program I got the "java.lang.OutOfMemoryError: Java heap space" this error and I want to know what part is wrong.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> myList = new ArrayList<Integer>();
int a = scanner.nextInt();
while(a!=0) {
myList.add(a);
}
for(int i=0;i<myList.size();i++) {
System.out.println(myList.get(i));
}
You need to keep reading a new number from stdin. Otherwise, a will not change value, and will lead to said error:
while (a !=0) {
myList.add(a);
a = scanner.nextInt();
}
IMHO a for loop is more appropriate:
for (int a = scanner.nextInt(); a != 0; a = scanner.nextInt()) {
myList.add(a);
}
This has the desirable effect of limiting the scope of a to the loop (one should always limit the scope of everything as much as possible).
I cannot get out of while loop.
I do not why sc.hasNextInt() does not return false after last read number.
Should I use another method or is there a mistake in my code?
public static void main(String[] args) {
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.println("Length of array: ");
int[] numbers = new int[sc.nextInt()];
System.out.printf("Type in integer elements of array ", numbers.length);
int index = 0;
**while ( sc.hasNextInt()) {**
numbers[index++] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
sc.close();
}
Do the following:
Use the input length as the end of the loop.
// Creating an array by user keyboard input
Scanner sc = new Scanner(System.in);
System.out.println("Length of array: ");
int len = sc.nextInt();
int[] numbers = new int[len]; // use len here
System.out.printf("Type in integer elements of array ", numbers.length);
int index = 0;
for (index = 0; index < len; index++) { // and use len here
numbers[index] = sc.nextInt();
}
// created method for printing arrays
printArray(numbers);
sc.close();
And don't close the scanner.
When you are receiving your input from the console, the Scanner hasNextInt() method placed inside a while loop condition will continue to read (meaning the loop will continue), until one of the following happens:
You submit a non-numeric symbol (e.g. a letter).
You submit a so-called "end of file" character, which is a special symbol telling the Scanner to stop reading.
Thus, in your case you cannot have the hasNextInt() inside your while loop condition - I am showing a solution below with a counter variable that you can use.
However, the hasNextInt() method inside a while loop has its practical usage for when reading from a different source than the console - e.g. from a String or a file. Inspired from the examples here, suppose we have:
String s = "Hello World! 3 + 3.0 = 6 ";
We can then pass the string s as an input source to the Scanner (notice that we are not passing System.in to the constructor):
Scanner scanner = new Scanner(s);
Then loop until hasNext(), which checks if there is another token of any type in the input. Inside the loop, perform a check if this token is an int using hasNextInt() and print it, otherwise pass the token to the next one using next():
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
System.out.println("Found int value: " + scanner.next());
} else {
scanner.next();
}
}
Result:
Found int value: 3
Found int value: 6
In the example above, we cannot use hasNextInt() in the while loop condition itself, because the method returns false on the first non-int character that it finds (so the loop closes immediately, as our String begins with a letter).
However, we could use while (hasNextInt()) to read the list of numbers from a file.
Now, the solution to your problem would be to place the index variable inside the while loop condition:
while (index < numbers.length) {
numbers[index++] = sc.nextInt();
}
Or for clarity`s sake, make a specific counter variable:
int index = 0;
int counter = 0;
while (counter < numbers.length) {
numbers[index++] = sc.nextInt();
counter++;
}
I'm trying to work out this problem:
Input
The input stream contains a set of integer numbers Ai (0 ≤ Ai ≤ 1018). The numbers are separated by any number of spaces and line breaks. A size of the input stream does not exceed 256 KB.
Output
For each number Ai from the last one till the first one you should output its square root. Each square root should be printed in a separate line with at least four digits after decimal point.
Sample:
input:
1427 0
876652098643267843
5276538
output:
2297.0716
936297014.1164
0.0000
37.7757
And here's my code:
public class ReverseRoot
{//start class
public static void main(String[] args)
{//start main
Scanner in = new Scanner(System.in);
ArrayList<Long> array = new ArrayList<Long>();
array.add(in.nextLong());
while(in.hasNextLong())
{
array.add(in.nextLong());
}
in.close();
for (int i = array.size(); i > 0; i--)
System.out.printf("%.4f%n", Math.sqrt((double)array.get(i)));
}//end main
}//end class
Anybody know what the deal is?
Your for loop doesn't work because you try to access non existing elements in your list.
Change the loop to this:
for (int i = array.size() - 1; i >= 0; i--)
System.out.printf("%.4f%n", Math.sqrt((double)array.get(i)));
}
Why do you have array.add(in.nextLong()); outside the loop? You can delete this.
To exit your input just type any non-long character into your console.
As I observer, we should have 2 loops. The first loop is for 'multiple lines' and the second loop is for 'multiple long value' of a single line.
Here is an example
public static void main(String[] args) throws Exception {
Scanner console = new Scanner(System.in);
Scanner lineTokenizer;
// this is to handle all 'lines'
while (console.hasNextLine()) {
String lineContent = console.nextLine();
if (lineContent == null || lineContent.isEmpty()) {
// this is to exit the program if there is no input anymore
break;
}
lineTokenizer = new Scanner(lineContent);
// this is to handle a 'line'
while (lineTokenizer.hasNext()) {
if (lineTokenizer.hasNext()) {
long number = lineTokenizer.nextLong(); // consume the valid token
System.out.printf("%.4f%n", Math.sqrt((double) number));
}
}
lineTokenizer.close(); // discard this line
}
console.close(); // discard lines.
}
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
}
}
Here is my code which just reads the lines from input stream and displays them but to my surprise its not reading all the lines. Its reading only upto second last line.
Here is my code :-
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
short n = scan.nextShort();
short m = scan.nextShort();
byte[][] topics = new byte[n][m];
for(short i = 0; i < n; i++){
char[] arr = scan.nextLine().toCharArray();
display(arr);
}
}
private static void display(char[] arr){
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i]);
}
System.out.println();
}
}
The input is given in this format
4 5
10101
11100
11010
00101
My output is this :-
10101
11100
11010
Its not having the third line. Why?
Add a scan.nextLine() before your for loop, to read the end of the first line (that contains "4 5"). Without it, the first call to scan.nextLine() inside the loop returns an empty String.
The problem is that the first call to nextLine() is reading the empty "line" between the end of "5" (read for m) and the line break.
Personally, I would either stop using Scanner entirely (in favour of BufferedReader) - there's a huge number of questions a bit like this, with it not behaving exactly as you'd like - or only just nextLine(). Either way, basically process a line at a time:
Read the first line
Split it on space and parse the two substrings as n and m
Read the next n lines
Basically, Scanner is "token-oriented" whereas your input format is more "line-oriented".
If you do want to use Scanner.nextShort() you could always read the first line (either with a BufferedReader or a Scanner) and create a new scanner just from that string:
String firstLine = ...;
Scanner firstLineScanner = new Scanner(firstLine);
short n = firstLineScanner.nextShort();
short m = firstLineScanner.nextShort();
...
The problem is scan.nextLine() just remove this and put
scan.next() if you read about nextLine method this might help
public String nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
public class Solution
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
short n = scan.nextShort();
short m = scan.nextShort();
short[][] topics = new short[n][m];
for(short i = 0; i < n; i++){
char[] arr = scan.next().toCharArray();
display(arr);
}
}
private static void display(char[] arr){
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i]);
}
System.out.println();
}
}