Java Input method not terminating - java

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.
}

Related

Mooc.fi Part 3 Help,

Confused on this exercise, its asking me to create a loop which remembers multiple integers that the user inputted, and prints them out the exact same way. I'm confused on how to print the input without making it a list and not using any methods. I tried making input equal to i, but that doesn't output anything.
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
int i = 0;
int i2 = 0;
ArrayList <Integer> name_input = new ArrayList<>();
while(true) {
System.out.print("print number:");
int input = Integer.valueOf(scanner.nextLine());
name_input.add(input);
if (input == -1) {
break;
}
i++;
}
while(i2 < i){
System.out.println(i);
i2++;
}
}
Original question: The exercise template contains a base that reads numbers from the user and adds them to a list. Reading is stopped once the user enters the number -1.
Expand the functionality of the program so that after reading the numbers, it prints all the numbers received from the user. The number used to indicate stopping should not be printed.

loop based on user input java

I want to write a program that queries the user for a "number n" and then output the word repetition n times.
For example the word is "Hello".
So far I've got this:
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Zahl 1:");
int number = scanner.nextInt();
}
Which should end in this ->
Number: 3
Hello
Hello
Hell
.
I don't know how to move forward.
I thank you for your time in advance!
You can use functional programming.
IntStream.range(0, n)
.forEach(System.out.println(variable));
Here n is the number of times that string is to be printed and a variable is a string.
This code out print "Hallo" n times (n = numbers)
String s = "Hello";
for (int i = 0; i < number; i++){
System.out.println(s);
}

Java ArrayList: Utilising ArrayList for print message

In my Java program I have an ArrayList. What I want to do is print a number at the bottom that will say 'x amount of people have passed'
System.out.println = ("The amount of people that have more than 40 marks is " + x);
Is it possible to calculate how many numbers of marks will be more than 40 if there are an undetermined amount of marks put in, utilising an ArrayList?
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
// Create a new scanner to use in java
int[] range = { 0,29,39,69,100 };
// A new array is created with the grade boundaries
int[] inRange = new int[boundary.length - 1];
// Indexed from 0 to n-1
int markIn;
// New integer markIn
do {
// This do-while loop calculates the expression after the statements below are exectued at least once
System.out.println("Enter Mark(s):");
// Wait for user input
markIn = input.nextInt();
// markInp value is set as the value entered by user
marks.add(markIn);
for (int a=1 ; a<boundary.length ; a++)
// for loop will take the variable 'a' and compare it with varibale 'boundary', when the condition is satisfied that value of 'a' increments by 1
if (range[a-1] <= markInp && markInp <= range[a]) {
// The boundaries will define the upper and lower limits of the markInp
inRange[a-1]++;
//inRange is incremented by 1
break;
//Exit if
}
} while (markIn <= 100);
// When the mark exceeds 100, the loop is stopped
System.out.println(marks);
input.close();
} // Close the Scanner input
}
You can do something like :
int result = 0;
if(marks != null)
{
Collections.sort(marks);
for(int i=0;i<marks.size();i++)
{
if(marks.get(i) > 40)
{
result = marks.size() - i;
break;
}
}
}
marks is the arraylist and result is desired output.
If the array is already sorted, like you show in your example, then you just have to do a simple search from where you start seeing a particular score, then taking the length of the array and subtracting the position of the element that came from your search.
If the array isn't sorted, sort it and then do the search.

Java while(input.hasnextline) loop not exiting?

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;
}

getting input from stdin

I want to get input from stdin in the for of
3
10 20 30
the first number is the amount of numbers in the second line. Here's what I got, but it is stuck in the while loop... so I believe. I ran in debug mode and the array is not getting assign any values...
import java.util.*;
public class Tester {
public static void main (String[] args)
{
int testNum;
int[] testCases;
Scanner in = new Scanner(System.in);
System.out.println("Enter test number");
testNum = in.nextInt();
testCases = new int[testNum];
int i = 0;
while(in.hasNextInt()) {
testCases[i] = in.nextInt();
i++;
}
for(Integer t : testCases) {
if(t != null)
System.out.println(t.toString());
}
}
}
It has to do with the condition.
in.hasNextInt()
It lets you keep looping and then after three iterations 'i' value equals to 4 and testCases[4] throws ArrayIndexOutOfBoundException.
The Solution to do this could be
for (int i = 0; i < testNum; i++) {
*//do something*
}
Update your while to read only desired numbers as below:
while(i < testNum && in.hasNextInt()) {
The additional condition && i < testNum added in while will stop reading the numbers once your have read the numbers equivalent to your array size, otherwise it will go indefininte and you will get ArrayIndexOutOfBoundException when number array testCases is full i.e. you are done reading with testNum numbers.

Categories