can somebody explain, why does this loop run endlessly?
I thought that the boolean **hasNext() ** is only true if there are no elements anymore. So when I type something in the loop runs like I typed something that goes endless too.
And what are these nmbers? please explain
import java.util.Scanner;
public class Vocabulary {
public static void main(String[] args) {
Scanner standardInput = new Scanner(System.in);
for(int i = 0; standardInput.hasNext(); i++){
System.out.print(i);
}
}
}
I researched in Internet about hasNext(). I know what it makes and I know how the for-loop works. But I don´t know why hasNext in for-loop makes the programm run endlessly.
Edit:
On the other hand, this code works. Why does this code work?
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner standardInput = new Scanner(System.in);
double sum = 0;
while(standardInput.hasNext()) {
double nextNumber = standardInput.nextDouble();
sum += nextNumber;
}
System.out.println("The Sum is " + sum + ".");
}
}
hasNext() returns true if there is something waiting on the Scanner standardInput for being picked up. But you never pick it up, so it stays there and waits – endlessly, same as your loop.
standardInput.hasNext() is always true which is why you have an infinite loop.
hasNext() only checks if there is another token in the scanner and never moves from the start. For example when putting in the string "StackOverflow", the next token is always "StackOverflow".
One problem with using hasNext() in your case is that using Scanner halts the program and waits for an input, so it's always true so long as it has taken an input.
In this case, it looks like you're trying to iterate over the length of the scanner input and print the current character count each time - it might be better to assign the output of nextLine() to a variable and iterate over that instead. See below for an example:
import java.util.Scanner;
class Vocabulary {
public static void main(String[] args) {
Scanner standardInput = new Scanner(System.in);
String input = standardInput.nextLine();
System.out.println("Scanner hasNext:" + standardInput.hasNext()); // we can see that hasNext pauses our program
for (int i=0;i<input.length();i++) {
System.out.print(i + " ");
}
}
}
The output looks like this:
StackOverflow
hasNext
Scanner hasNext:true
0 1 2 3 4 5 6 7 8 9 10 11 12
Related
I have specified the size of the array using user input but my for loop is taking input only size-1 time.
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int time=sc.nextInt();
String input[]=new String[time];
for(int i=0;i<time;i++)
{
input[i]=sc.nextLine();
}
for(int i=0;i<time;i++)
{
int len=input[i].length();
if(len>4)
{
System.out.println(input[i].charAt(0)+ Integer.toString(len-2)+input[i].charAt(len-1));
}
else
System.out.println(input[i]);
}
}
}
i changed my code and it is working fine
changed
int time=sc.nextInt();
with
int time=Integer.parseInt(sc.nextLine());
but i don't know the reason behind this . Please can anyone explain me
The Scanner.nextInt() method scans the next token of the input as an int, not the line. For example, if you give an int input and then hit enter, then it takes only the int, not the carriage return.
If you give a sample input like this:
2 xyz //hit enter and give the next input
abc
You'll see the nextInt() will take the 2 as input from that line and the upcoming first iteration for Scanner.nextLine() will consider the xyz as first input and in the next iteration, as we gave abc, it will be considered as the second. All these time you're code was working, but you couldn't see as it was taking the empty string as the first input due to the carriage return from the previous line.
However, The Scanner.nextLine() takes the whole line as input, along with the carriage return and then parses the int to the integer, so, you get the next lines for the string input for your array.
Hope that makes everything clear.
The problem is with the nextLine() method used in the first for loop. Because the method advances the scanner to the next line and returns the input that was skipped, it kind of "eats" one of your loop iterations and it ends up allowing you to input time - 1 elements into the array instead of time amount of elements. If you just use sc.next() instead, the program works perfectly fine, so you don't need to use
int time=Integer.parseInt(sc.nextLine());
as it may be a bit more complicated (in my opinion) than just replacing nextLine() with next(). Here is the code:
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int time = sc.nextInt();
String input[] = new String[time];
for(int i = 0;i < time;i++)
{
input[i] = sc.next();
}
for(int i = 0;i < time;i++)
{
int len = input[i].length();
if(len > 4)
{
System.out.println(input[i].charAt(0) + Integer.toString(len - 2) + input[i].charAt(len - 1));
}
else
System.out.println(input[i]);
}
sc.close();
}
}
The following program is to display the word with maximum number of vowels.But it does not work until i have given 10 variables as input even though it is supposed to end after giving a null input.How can I fix this problem ( I already tried using different inputs like "." and " ")
**
import java.util.*;
public class hw1{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String w,temp="";
int c=0,max=0;
for(int i=0;i<10;i++)
{
w=sc.next();
w=w.toUpperCase();
if(w.equals(""))
break;
for(int j=0;j<w.length();j++)
{
if(w.charAt(j)=='A'||w.charAt(j)=='E'||w.charAt(j)=='I'||w.charAt(j)=='O'||w.charAt(j)=='U')
c++;
}
max=Math.max(max,c);
if(max==c)
temp=w;
c=0;
}
System.out.println(temp);
}
}
**
sc.next()
does not trigger if you give empty input (or press enter).
For allowing your exit condition to work you should use
w=sc.nextLine();
After that, if you hit enter, the for is broken and the app prints the result
I've been googling this but I still don't understand why this doesn't work. The user would enter an array of integers and I need to find how many elements are in that array.
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt()) {
n++;
s.next();
}
System.out.println(n);
I looked up if using variable outside the scope works, and I've been answers saying that if you're gonna use the variable outside the scope, you should declare and initialize outside the scope (in this case, the while loop). However, this still doesn't work for me. My code right now won't even print "0". Any help would be greatly appreciated.
When you read from command line you have to signal EOF (end of file), otherwise how will your program know if you have stopped entering your elements or not? On windows you can press Ctrl-D and your scanner will stop reading, for example.
You can break out of the loop with the condition that a word is entered, such as "exit" since you want to get an int count. Your code works to count the number of integers entered into a scanner, but you never declared an array to hold all the values.
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList array = new ArrayList(); //declare your array
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt())
{
n++;
s.next();
array.add(s);//store the array value
if (s.hasNext("exit"))//allow an exit to the loop
break;
}
System.out.println(array.size()); //better, use the size of the array
}
}
Your code works fine.
Check this link. https://ideone.com/vrnoEz
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt()) {
n++;
s.next();
}
System.out.println(n);
}
}
This should be a very basic program but I'm new to Java. I want to be able to input multiple strings into the console using Scanner to detect them. So far I've been able to get the input part right, I wanted the program to run in such a way that the results are displayed when an empty space is entered as opposed to a string. Strangely enough I've only been able to get results when i hit return twice, however, when there are more than 4 inputs hitting return once works. My counter should count the number of "Courses" entered and display them in the results but it gives inaccurate readings.
import java.util.Scanner;
public class Saturn
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("For each course in your schedule, enter its building");
System.out.println("code [One code per line ending with an empty line]");
String input;
int counter = 0;
while (!(userInput.nextLine()).isEmpty())
{
input = userInput.nextLine();
counter++;
}
System.out.println("Your schedule consits of " + counter + " courses");
}
}
You're calling Scanner#nextLine twice - once in the while loop expression and again in the body of the loop. You can just assign input from the while loop expression. In addition you can use Scanner#hasNextLine to defend against NoSuchElementException occurring:
while (userInput.hasNextLine() &&
!(input = userInput.nextLine()).isEmpty()) {
System.out.println("Course accepted: " + input);
counter++;
}
Please have a look at the following code. It is my attempt to manage the given numbers in ascending order.
import java.io.*;
import java.util.*;
import java.util.ArrayList;
public class TurboSort
{
public static void main(String[]args)
{
List<Integer> numbers = new ArrayList();
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt())
{
numbers.add(scan.nextInt());
}
Collections.sort(numbers);
System.out.println(numbers);
}
}
insert the input as 2,1,6,7,3
Hit enter.
Now, the scanner hasn't exited from the while loop because it is not giving any output. What am I doing here wrong? Even if you manage to get it, the output is surrounded by brackets like " [1] [2] [3] ". Why is that? Is that is because I didn't call 'Integer.parseInt()' ?. Please help me with those 2 questions.
Thanks.
The result of hitting enter will be a line separator, whose characters are treated as delimiters (by default, see Character.isWhitespace()) and are skipped. Thus the Scanner is waiting for further input, which never arrives and the hasNextInt() will block. Enter something which is not an integer, like a . for example, to cause the loop to terminate:
1 2 5 3 7 .
This loop will never exit (as long as you enter integers) as there is no break condition
while(scan.hasNextInt()){
numbers.add(scan.nextInt());
}
If you want your loop to stop, say for example you need to acquire only 5 integers then you could do this:
while(scan.hasNextInt()){
numbers.add(scan.nextInt());
if(numbers.size() == 5) break;
}
The Scanner continues to scan until the end of input has reached, or until it fails to read (e.g. when a non integer is detected in the text).
Hit ctrl + D after you hit enter.
You can separate the numbers any white space.
If you want to have the input on only 1 line like 2,1,6,7,3, probably would be easier to use nextLine() of the scanner:
Scanner scan = new Scanner(System.in);
String consoleInput = scan.nextLine();
This will terminate the scanner, once you hit enter. At this point, you have the input in a String, you have to parse that string and get out all the numbers.
Also note that you have forgotten to parameterize your ArrayList().
Here's a possible adaptation of your source code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String consoleInput = scan.nextLine();
List<Integer> numbers = new ArrayList<Integer>();
if (consoleInput.length() > 0 && consoleInput.contains(",")) {
String[] numbersAsStrings = consoleInput.split(",");
for (String tNumberAsString : numbersAsStrings) {
try {
int tNumber = Integer.parseInt(tNumberAsString);
numbers.add(tNumber);
} catch (NumberFormatException nfe) {
System.out.println(tNumberAsString + " is not a number");
}
}
Collections.sort(numbers);
System.out.println(numbers);
} else {
System.out.println("Nothing to sort!");
System.out.println(numbers);
}
}
}
Your code should work. You just need to add a way to break out of the loop. It also is a good idea to keep your scanned value in a local variable in case you need to reference it again.
maybe add:
while(scan.hasNextInt()){
int i=scan.nextInt();
if(i==-1)
break;
numbers.add(i);
}