Why isn't the nextInt() method working? - java

I've typed it exactly as shown in Introduction to Java Programming (Comprehensive, 6e). It's pertaining to reading integer input and comparing user input to the integers stored in a text file named "lottery.txt"
An external link of the image: http://imgur.com/wMK2t
Here's my code:
import java.util.Scanner;
public class LotteryNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Defines and initializes an array with 100 double elements called isCovered.
boolean[] isCovered = new boolean[99];
// Prompts user for input and marks typed numbers as covered.
int number = input.nextInt();
while (number != 0) {
isCovered[number - 1] = true;
number = input.nextInt();
}
// Checks whether all numbers are covered.
boolean allCovered = true;
for (int i = 0; i < 99; i++)
if (!isCovered[i]) {
allCovered = false;
break;
}
// Outputs result.
if(allCovered) {
System.out.println("The tickets cover all numbers."); }
else {
System.out.println("The tickets do not cover all numbers."); }
}
}
I suspect the problem lies within the declaration of the array. Since lottery.txt does not have 100 integers, the elements from index 10 to 99 in the array are left blank. Could this be the problem?
Why does the program terminate without asking for user input?
Possible Solution:
After thinking for a while, I believe I understand the problem. The program terminates because it takes the 0 at the EOF when lottery.txt is feed in. Furthermore, the program displays all numbers not to be covered because the elements from 11 to 100 are blank. Is this right?

The program is written to keep reading numbers until a zero is returned by nextInt(). But there is no zero in the input file, so the loop will just keep going to the end of the file ... and then fail when it tries to read an integer at the EOF position.
The solution is to use Scanner.hasNextInt() to test whether you should end the loop.
And, make sure that you redirect standard input from your input file; e.g.
$ java LotteryNumbers < lottery.txt
... 'cos your program expects the input to appear on the standard input stream.

Related

Character.isDigit parameters and line unavailable errors within the isDigit method (clarification)

I'm currently working on a small project for an introductory java class. We're supposed to make a program which can take in an integer from the user and output the number of odds, evens, and zeroes present within the code. This seemed pretty easy to me, and I managed to implement the code, but a class mate, after I criticized his code for incorrectly following the prompt, noted that my code would crash if anything but digits was input.
Out of spite I've tried to go beyond the prompt and have the program output an error message if it encounters characters aside from digits (instead of having my compiler return an error). However I'm returning multiple errors within the Eclipse compiler when using the isDigit method in the Character class.
I don't know exactly what's causing this, and I feel I must be missing something crucial, but my teacher quite frankly isn't qualified enough to understand what's causing the error, and none of my classmates can seem to figure it out either.
package ppCH5;
import java.util.Scanner;
public class PP5_3
{
public static void main(String[]args)
{
int even = 0;
int odd = 0;
int zero = 0;
int num = 0;
int count = 0;
boolean inputError = false;
System.out.println("please provide some integer");
Scanner scan = new Scanner(System.in);
String numbers = scan.next();
scan.close();
Scanner intSeperate = new Scanner(numbers);
intSeperate.useDelimiter("");
while(intSeperate.hasNext())
{
if(Character.isDigit(numbers.charAt(count)))
{
count++;
num = intSeperate.nextInt();
if((num % 2)==1)
odd++;
if((num % 2)==0)
if(num==0)
zero++;
else
even++;
}
else
{
count++;
inputError = true;
}
}
intSeperate.close();
if(!inputError)
{
System.out.println("There are " + even + " even digits.\n" + odd + " odd digits.\nAnd there are " + zero + " zeros in that integer.");
}
else
{
System.out.println("You have provided a disallowed input");
}
}
}
Any help would be appreciated, I'm currently at a loss.
When you enter a single non-digit character, say a, the else branch inside the while loop will get executed, incrementing count, right? And then the loop will start a new iteration, right?
In this new iteration, intSeparator.hasNext() still returns true. Why? Because the input a is never read by the scanner (unlike if you have entered a digit, intSeparator.nextInt would be called and would have consumed the input).
Now count is 1 and is an invalid index for the 1-character string. Therefore, numbers.charAt(count) throws an exception.
This can be avoided if you break; out of the loop immediately in the else block:
else
{
inputError = true;
break;
}
Also, don't close the scan scanner. scan is connected to the System.in stream. You didn't open that stream, so don't close it yourself.

Why is output shown only alternately?

public class Two {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
while(obj.nextInt() > 5)
{
System.out.println(obj.nextInt());
}
}
}
If i input the number ( > 5) for first time there is no output on the console but if i input a number on second try there is output on the console.
So I get an output alternatively.
Can anyone explain why is it so?
The java.util.Scanner.nextInt() method Scans the next token of the input as an int and returns it. After the token is read another nextInt()-Call will read (as the name says) the next Integer.
I think you were expecting something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int read;
while((read = scanner.nextInt()) > 5)
{
System.out.println(read);
}
}
Now the read Integer is stored in the variable read and is printed, if it was greater than five.
The reason you're getting output every other input is because you're prompting the Scanner object to gather input twice within your loop system. Every time you call a next... method on your Scanner you are prompting the user.
So in your condition for the while loop you are asking the user to input a value integer value which is then compared against 5. THEN, in your print statement you call the nextInt() method again, which will then prompt the user again for another value integer input.
So given a series of 6 integer inputs for your current loop, 6 2 10 4, you loop will only print 2 and 4.
Instead, you should prompt and store once outside of your loop, then test with the condition and reprompt after the print within the loop like so...
int input = obj.nextInt();
while (input > 5){
System.out.println(input);
input = obj.nextInt();
}

Get user to input integers

I want to make a program which keeps prompting the user to input integers(from CUI) until it receives a 'X' or 'x' from the user.
The program then prints out the maximum number, minimum number and average value of the input numbers.
I did manage to get the user to input numbers until someone types 'X', but I can't seem to get it to stop if someone types 'x' and the second bit.
This is the code that I have managed to work out:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!in.hasNext("X") && !in.hasNext("x"))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Any hints on how I proceed further?
You will need to do something like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!(in.hasNext("X") || in.hasNext("x")))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Whenever you use while loop you have to use the {} in case the arguments in the while block are more than 1 line, but if they are just of a line then you can just go on without using the {}.
But the problem, you had I suppose is the use of && instead of ||. What the && (AND) operator does is execute if both the statements are true but a || (OR) Operator works if any of the conditions are true.
If you say while(!in.hasNext("X") && !in.hasNext("x")) it makes no sense as the user input is not both at the same time, but instead if you usewhile(!in.hasNext("X") || !in.hasNext("x"))` it makes sense. Understood?
And about sorry, im really new at this. but ive added the code No problem, you need not say sorry but there are a few things to keep in mind before asking a question. You must read this https://stackoverflow.com/help/how-to-ask and yeah one more thing, you should use proper English Grammar while framing your question.
Last of all, about how to calculate the average..., for that what you need to do is store all the input variables into an array and then take out the mean of that or alternatively you could think about it and code something up yourself. Like to take out mean, you could make a variable sum and then keep adding the integers the user enters and also keep a variable count which will keep the count of the number of integers entered and then at last you could divide both of them to have your answer
Update: For checking the minimum and the maximum, what you can do is make 2 new variables like int min=0, max=0; and when the user enters a new variable you can check
//Note you have to change the "userinput" to the actual user input
if(min>userinput){
min=userinput;
}
and
if(max<userinput){
max=userinput;
}
Note: At stackoverflow we are there to help you out with the problems you are facing BUT you cannot exploit this. You cannot just post your homework here. But if you are trying to code something up and are stuck at it and cannot find a answer at google/stackoverflow then you can ask a new question and in that you need to tell what all you have already tried. Welcome to SO! :D Hope you have a nice time here
This would fit your needs:
public void readNumbers() {
// The list of numbers that we read
List<Integer> numbers = new ArrayList<>();
// The scanner for the systems standard input stream
Scanner scanner = new Scanner(System.in);
// As long as there a tokens...
while (scanner.hasNext()) {
if (scanner.hasNextInt()) { // ...check if the next token is an integer
// Get the token converted to an integer and store it in the list
numbers.add(scanner.nextInt());
} else if (scanner.hasNext("X") || scanner.hasNext("x")) { // ...check if 'X' or 'x' has been entered
break; // Leave the loop
}
}
// Close the scanner to avoid resource leaks
scanner.close();
// If the list has no elements we can return
if (numbers.isEmpty()) {
System.out.println("No numbers were entered.");
return;
}
// The following is only executed if the list is not empty/
// Sort the list ascending
Collections.sort(numbers);
// Calculate the average
double average = 0;
for (int num : numbers) {
average += num;
}
average /= numbers.size();
// Print the first number
System.out.println("Minimum number: " + numbers.get(0));
// Print the last number
System.out.println("Maximum number: " + numbers.get(numbers.size() - 1));
// Print the average
System.out.println("Average: " + average);
}

Program Output Problems (Java)

I was given an assignment to write a program which will accept any number of input data until 999 has been read. Then the program should type out total number of zero's and various other requests, but the problem is I don't know the output command to tell it to read the number of zeros. All I have so far is
import java.util.Scanner;
public class MidtermI {
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
int numbers = console.nextInt();
and then from there I'm lost.
Break it down into small steps, and check that each step works before going further:
The first thing you need to sort out is to be able to read multiple inputs, by looping. Your current code only reads a single number from the Scanner.
Next, you need to check for the special value 999, and stop looping when that is received.
When you have got that working, figure out how to count the zeros - either by counting them as they arrive, or collecting all the values and counting them afterwards.
You can then print out the required results using System.out.println() - but you'll probably want to use that for testing and debugging your code as you go along, anyway.
Create ArrayList to hold the zero values the print its size.
ArrayList<Integer> zeroValues = new ArrayList<Integer>();
Then loop n time to input n numbers:
for(int i=0; i<999; i++) {
int numbers = console.nextInt();
if(number == 0) {
zeroValues.add(number);
}
}
Then you could print the total of zero's values like:
System.out.println(zeroValues.size());

Printing binary digits of a number

Need to write a java program from pseudo code, I've got a bit of code written, its not working and I'm not sure if i've done it right or not as I simply tried to follow the pseudo code -
Read i
While i > 0
Print the remainder i % 2
Set i to i / 2
import java.util.Scanner;
import java.util.Scanner;
public class InputLoop
{
public static void main(String[] args)
{
int i = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
while (!scan.hasNextInt()) // while non-integers are present
{
scan.next();
System.out.println ("Bad input. Enter an integer.");
}
while (i>0) // while greater than 0
{
int input = scan.nextInt();
System.out.println (i%2);
i = (i/2);
}
}
}
Frankly speaking, you didn't(Ah missed it earlier) exactly followed the pseudo-code. The pseudo code tells you to read i, whereas you are reading input. That's one problem.
Second problem is that, you should read the input outside the while loop where you are doing the processing with the input. That is the 2nd thing you didn't followed.
Currently your while loop is: -
while (i>0) // while greater than 0
{
int input = scan.nextInt();
System.out.println (i%2);
i = (i/2);
}
This is read input from user on every iteration which you don't want.
So, you need to modify your code a little bit: -
int i = scan.nextInt(); // Read input outside the while loop
while (i>0) // while greater than 0
{
System.out.println (i%2);
i = i/2; // You don't need a bracket here
}
How about:
System.out.println(Integer.toBinaryString(i));
The pseudo code reads first (outside the loop), but in your code you read second (inside the loop)

Categories