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);
}
}
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
I am having an issue with this unfinished program. I do not understand why this returns a "no Line found exception" when I run it. I have a while loop set up whose purpose is checking for this but I have done something wrong. I am trying to store information from a file into a 2d array for class.
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.util.Arrays;
public class LabProgram {
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int NUM_CHARACTERS = 26; // Maximum number of letters
int MAX_WORDS = 10; // Maximum number of synonyms per starting letter
String userWord = (scnr.next()) + ".txt"; //Get word user wants to search
char userChar = scnr.next().charAt(0); //Get char user wants to search
String[][] synonyms = new String[NUM_CHARACTERS][MAX_WORDS]; // Declare 2D array for all synonyms
String[] words = new String[MAX_WORDS]; // The words of each input line
File aFile = new File(userWord);
Scanner inFile = new Scanner(aFile);
while(inFile.hasNextLine()) {
for(int i = 0; i < synonyms.length; i++) {
words = inFile.nextLine().trim().split(" ");
for(int wordCount = 0; wordCount < words.length; wordCount++) {
synonyms[i][wordCount] = words[wordCount];
}
}
}
}
}
The issue is with this for loop:
for (int i = 0; i < synonyms.length; i++) {
words = inFile.nextLine().trim().split(" ");
....
}
You're iterating from i=0 upto synonym.length-1 times, but that file does not have these much lines, so, as soon as your file is out of lines but the for loop has scope to iterate more, the inFile.nextLine() gets no line and thus throw the exception.
I don't know what you are exactly doing here or want to achieve through this code, but this is what causing you the trouble.
Hope that answers your query.
Basically your problem is that you're only checking hasNextLine() before the for loop starts, and you're actually getting the next line on every iteration of the loop. So if you run out of lines while in the middle of your for loop an exception is thrown.
I'm actually not quite sure what your code is supposed to do but at the very least you need to add a hasNextLine() check every time before you actually run nextLine() to avoid errors like this.
When I run this program, it does not return anything yet no errors occur. I'm trying to create a method that will return the number of words I previously entered into the array once I enter "".
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayCounter {
public static int CountItems(ArrayList<String> list ) {
int i = list.size();
return i;
}
public static void main (String args[]) {
ArrayList<String> Names = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("Hey gimme a word");
String word = input.nextLine();
if (word.equals("")) {
System.out.println("The number of values entered were:");
break;
} else {
Names.add(word);
}
}
CountItems(Names);
input.close();
}
}
You're ignoring the result returned from CountItems.
The println should be:
System.out.println("The number of values entered were: " + CountItems(Names));
As an aside, methods names in Java should start with a lowercase, so CountItems should instead be countItems.
Your CountItems method returns the item count, but you are ignoring the result. You need some kind of System.out.println(CountItems(Names)) to print the result to the console.
Also, please consider renaming CountItems to countItems and Names to names to follow the naming conventions for Java.
I'm doing this really basic Java Programming course.
The aim of the exercise is to ask the user how many times the text has to be printed, and then print it. But as in the comment in the code it was said that ''do not change method definition'' , I have no idea how to proceed to print the text the amount asked. (I was thinking that the i could be added somehow to the method but idk)
Here is the code what I have done so far:
public class ManyPrints {
// NOTE: do not change the method definition, e.g. add parameters to method
public static void printText() {
System.out.println("In the beginning there were the swamp, the hoe and Java.");
// Write your code here
}
public static void main(String[] args) {
// ask the user how many times the text should be printed
// use the while structure to call the printText method several times
Scanner reader = new Scanner(System.in);
System.out.println("How many?");
int number = Integer.parseInt(reader.nextLine());
int i = 0;
while (i <= number) {
i++;
printText();
}
}
}
Thanks in advance if you have the time to help me !:)
As i see your given code, you take a variable int i = 0; and make a condition i <= number in a while loop. Which is counting from 0 to given number. Suppose given number is 10. So the loop is counting 0 to 10 and the text is printing 11 time.And you also need a Scanner class.So your code should look like,
import java.util.Scanner;
public class ManyPrints {
// NOTE: do not change the method definition, e.g. add parameters to method
public static void printText() {
System.out.println("In the beginning there were the swamp, the hoe and Java.");
// Write your code here
}
public static void main(String[] args) {
// ask the user how many times the text should be printed
// use the while structure to call the printText method several times
Scanner reader = new Scanner(System.in);
System.out.println("How many?");
int number = Integer.parseInt(reader.nextLine());
int i = 1;
while (i <= number) {
i++;
printText();
}
}
}
There is nothing wrong with the code except a few points, you did great.
you need to import Scanner
change i = 0;toi = 1;
So you get this
import java.util.Scanner;//Add this line
public class ManyPrints {
public static void printText() {//no problems here
System.out.println("In the beginning there were the swamp, the hoe and Java.");
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("How many?");
int number = Integer.parseInt(reader.nextLine());
int i = 1;//it should be i = 1; and not i = 0;
while (i <= number) {
i++;
printText();
}
}//done
}
Now if you want to proceed further(I take it that you are a complete beginner).
Get a simple IDE like BlueJ. Create a class. Write the code. Compile it. Run it.
You get the output.
Happy Coding.
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);
}