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);
}
Related
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
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);
}
}
Here is an example of such input.
A 3
B 1
A 2 etc.
As shown above, each input is separated by a line and appears an indeterminate amount of times.
How do I only read the numbers next to the 'A' and convert it all into a string using Scanner?
You can write something like:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main29 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String string = scanner.next();
int number = scanner.nextInt();
System.out.println(number);
}
}
}
output:
3
1
2
As you can see I just write a loop which works until scanner can read token from STDIN. Inside of loop I read String tokens use next method and then read Integer tokens use nextInt method.
I think now you can add and required logic to the loop i.e. print numbers after A as you wish.
So I am doing some problems on the UVa online problem judge, but on a relativity easy problem, I keep on getting a ArrayIndexOutOfBoundsException. To understand the code, here is the problem.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
The error message is:
reportException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Main.main(Main.java:16)
And I am using the sample input given.
Edit:
I have already tried added println statements in the code and figured out that the number is not being read. I am trying to understand why.
OK, after some messing around on my machine I think I found what might be at least part of the problem. The issue is that I'm not sure what the precise input is, so I'm going off of what I could get working on my machine.
So you start up your program, and it waits for a prompt at this line:
int t = scan.nextInt();
You enter your integer, and the program moves on as expected:
Input: 100 // Then press enter to continue
The input is parsed, and now t is set to 100.
Then when your program enters your for loop, it comes across this line:
String d = scan.nextLine();
Yet for some reason the program doesn't wait for input! (Or at least it didn't on my machine)
I believe the issue lies here:
Input: 100 // Then press enter to continue
^^^^^^^^^^^
What I think is happening is that your input is really
Input: 100\n
^^
That character (\r\n on Windows) is what's input when you hit enter. It's a newline character that tells the console to go to the next line.
So as a result, what I think happens is this:
Input: 100\n
Scanner parses 100, leaving the \n in the input stream
Then at the nextLine() call, the scanner sees \n on the input stream, which denotes end of line, so it thinks you already input the entire line! Because what it thought was your input was only the newline character, it returns an empty string, because your "input" was an empty string and the newline character. Your program then goes to split the newline character by spaces, rightly returns an array with a single element, and then your program promptly crashes when accessing an out-of-bounds index.
What might work better is reading an entire line first and parsing the integer so your scanner doesn't get ahead of itself, like this:
int t = Integer.parseInt(scan.nextLine());
Just as a warning: This is what I've been able to come up with based on using OP's code as-is on my machine. I was unable to get a situation where the only element in parts was "donate". I will update further as I get more info.
The error message means the array parts's length less than 2, sometimes.
It means the variable d does not always contain the string BLANK SPACE, " ", what you split by.
try this code:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int sum = 0;
for (int i = 0; i <= t; i++){
String d = scan.nextLine();
if (d.equals("report")) {
System.out.println(sum);
} else {
String[] parts = d.split(" ");
/*
* Add IF statement,
*/
if (parts.length() > 1) {
int z = Integer.parseInt(parts[1]);
sum+=z;
}
}
}
}
}