Why am I getting Output was not found error in Java? - java

I'm learning java and can't figure out why I keep getting this error. When I run program and type in 0 is outputs NaN.
Exercise: Write a program that asks the user for input until the user inputs 0. After this, the program prints the average of the positive numbers (numbers that are greater than zero). If no positive number is inputted, the program prints "Cannot calculate the average".
What I wrote :
import java.util.Scanner;
public class AverageOfPositiveNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double input = 0;
double sum = 0;
while (true) {
double userInput = Double.valueOf(scanner.nextLine());
if (userInput > 0) {
input = input + 1;
sum = sum + userInput;
}
if (userInput == 0) {
break;
}
if (userInput < 0) {
System.out.println("Cannot calculate the average");
}
}
System.out.println(sum / input);
}
}
error:
When input was:
0
, the expected out put was:
nnot
Output was not found.

You are getting a NaN (Not a Number) error because your variables double input = 0;
and double sum = 0; are set to 0.
If you enter 0 as the first number, your program is dividing 0 by 0 which is not possible.
Here is my solution to this problem:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double input = 0;
double sum = 0;
while (true) {
double userInput = Double.parseDouble(scanner.nextLine());
if (userInput == 0) {
if (sum == 0) {
System.out.println("You cannot enter 0 as the first number");
} else {
break;
}
}
if (userInput > 0) {
input++;
sum = sum + userInput;
}
if (userInput < 0) {
System.out.println("Cannot calculate the average");
}
}
System.out.println(sum / input);
}
}

As mentioned by others, you are attempting to divide by zero. This will throw an exception which you do not catch. You should make sure you don't divide by zero.
Also, since you have this inside the loop:
if (userInput < 0) {
System.out.println("Cannot calculate the average");
}
It will print every time the user enters a negative number but it should only print at the end, if applicable.
Scanner scanner = new Scanner(System.in);
int input = 0;
double sum = 0;
while (scanner.hasNextDouble()) {
double userInput = scanner.nextDouble();
// Only add to sum if > 0
if (userInput > 0) {
input += 1;
sum += userInput;
}
else if (userInput == 0) {
break;
}
// Ignore negative numbers
}
// If input > 0 there was at least one positive number
if (input > 0) {
System.out.println(sum / input);
}
else {
System.out.println("Cannot calculate the average");
}

You're getting NaN(Not a Number). It's not an error, it's a special value. When you trying to divide double type zero by another double type zero you will always get NaN. That is happening, because you assign double input = 0 and double sum = 0, then the while{} loop breaks when user's first input is zero, then your program divides sum by input(0 by 0) and that's it - NaN.

Related

How can I ask the user to re-enter their choice?

I know how to display an Error message if the user enters a number below 10 or higher than 999 but how can I code to make sure the program doesn't end after the users enter a number below 10 or higher than 999 and give them a second chance to enter their valid input over and over again until they give a correct input.
import java.util.Scanner;
public class Ex1{
public static void main(String args[]){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter an integer between 10 and 999: ");
int number = input.nextInt();
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
}
You will need to use a loop, which basically, well, loops around your code until a certain condition is met.
A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start a loop that will continue until the user enters a number between 1 and 10
while (true) {
System.out.println("Please enter a number between 1 - 10:");
num = scanner.nextInt();
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
} else {
// Exit the while loop, since we have a valid number
break;
}
}
System.out.println("Number entered is " + num);
}
}
Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start the loop
do {
System.out.println("Please enter a number between 1 - 10:");
try {
// Attempt to capture the integer entered by the user. If the entry was not numeric, show
// an appropriate error message.
num = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: Please enter only numeric characters!");
num = -1;
// Skip the rest of the loop and return to the beginning
continue;
}
// We have a valid integer input; let's make sure it's within the range we wanted.
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
}
// Keep repeating this code until the user enters a number between 1 and 10
} while (num < 1 || num > 10);
System.out.println("Number entered is " + num);
}
}
Try this, i just include the while loop in your code it will work fine.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = askInput(input);
while(number<10 || number>999) {
System.out.println("Sorry Try again !");
number = askInput(input);
}
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
private static int askInput(Scanner input) {
int number = input.nextInt();
return number;
}

how to make the input not read a certain number

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number (0 to quit): ");
//largest to-do
double largest = scan.nextDouble();
double count = 0;
while (largest != 0) {
double input = scan.nextDouble();
//max
if (input > largest) {
// not zero
// while (input > largest){
//
// }
largest = input;
//counter
count = 0;
}
//counter start
if(input==largest){
count++;
}
if (input == 0) {
System.out.println("Largest #: " + largest);
System.out.println("Occurance: " + count);
}
}
}
}
This program works! however, its not that complete I think...
Like if a user tries to enter
-17 -5 -2 -1 -1 -1 0
it outputs:
Max: 0
Occurrence: 1
Though: in my mind I want it to be:
Max: -1
Occurrence: 3
how would I do this WITHOUT using arrays? I know its in that part of the code I started above the counter.
Thanks in advance.
Why not something like that?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number (0 to quit): ");
double largest = 0, nextDouble;
int count = 0;
while ((nextDouble = scan.nextDouble()) != 0) {
if (nextDouble > largest || largest == 0) {
largest = nextDouble;
count = 1;
}
else if (nextDouble == largest) count++;
}
scan.close();
if (count == 0) {
System.out.println("No number entered!");
return;
}
System.out.println("Largest #: " + largest);
System.out.println("Occurance: " + count);
}
}

Check if the input number is in a valid binary format

i tried to make a simple program,which check if the input number from the user is a binary number and that number is in correct binary format -> without leading zeros. That below is my code,but it doesn't work. I would appreciate if someone could help.
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
num = sl.nextInt();
int firstDigit = Integer.parseInt(Integer.toString(num).substring(0, 1));// i want to get the first digit from the input
if (firstDigit>0||firstDigit==1 ){
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
} else System.out.printf("WARNING: The number starts with 0");
}
}
There are a better solution, you can check if your input contain only 0 and 1 and the input great then 0 then valide number, so instead you can use String for example :
String num;
Scanner sl = new Scanner(System.in);
num = sl.next();
if (num.matches("[01]+") && !num.startsWith("0")) {
System.out.println("Correct number :" + num);
}else{
System.out.println("Not Correct number!");
}
num.matches("[01]+") will check if your input contain only 0 and 1.
!num.startsWith("0") this to answer this part without leading zeros
Test:
10010 -> Correct number :10010
00001 -> Not Correct number!
11101 -> Correct number :01101
98888 -> Not Correct number!
You can try something like this:
public static void main(String args[]) {
boolean binary=true; // boolean for final decision
String input;
int counter=0; // to count how many leading zeros there are in the input
int target = 5; // specify how many leading zeros allowed!!
Scanner in = new Scanner(System.in);
input = in.nextLine(); // take the entire line as a String
//first loop through the whole input to check for any illegal entry (i.e. non digits)
for(char digit : input.toCharArray()){
if(!Character.isDigit(digit)){ // catch any non-digit !
System.out.println("Illegal Input Found!"); // inform user and exit
System.exit(0);
}
if(digit!='0' && digit!='1'){ // check if it's not 1 and not 0
binary = false;
}
}
// now if there are no illegal inputs, check if it starts with leading zeros
if(input.charAt(0)=='0'){ // potential leading zeros, check the rest
while(input.charAt(counter)=='0'){ // while there are followed zeros
counter++;
if(counter>target && binary){ // leading zeros only in case it's a binary
System.out.println("Illegal Leading Zeros!");
System.exit(0);
}
}
}
// now if your program reach this point that means the input is valid and doesn't contain leading zeros in case it's a binary
if(binary){
System.out.println("It is a binary number");
}
else{
System.out.println("It is NOT a binary number");
}
}
Test:
01010101 -> It is a binary number
01010105 -> It is NOT a binary number
0000001 -> Illegal Leading Zeros!
0000005 -> It is NOT a binary number
000000A -> Illegal Input Found!
Why not simply use the standard library methods?
static boolean isValidBinary(final int input) {
final String binary = String.valueOf(input);
return binary.replaceAll("[01]", "").isEmpty() && !binary.startsWith("0");
}
you should not use sl.nextInt(); it will transfer '011' to 11, so when user input '011', the variable 'num' get the int value 11.
You should simply use sl.next() to get the input of user.
I think you need to check your "if" condition before the while, because you don't want that the number starts with 0, right? so... just ask for it, I have tryied and worded fine to me:
public class CheckNumberBinary {
public static void main(String args[]) {
int r = 0, c = 0, num, b;
Scanner sl = new Scanner(System.in);
String input = sl.next();
num = Integer.parseInt(input);
String firstDigit = (input.length() > 0 ? input.substring(0, 1) : "" );
if (firstDigit.equals("0")) {
System.out.printf("WARNING: The number starts with 0");
} else {
while (num > 0) {
if ((num % 10 == 0) || (num % 10 == 1))
c++;
r++;
num = num / 10;
}
if (c == r) {
System.out.println(true);
} else
System.out.println(false);
}
}
}
The rest of your code Fulfills its mission! It tells you if the number is binary or not, and now plus tells you if your code begins with useless zeros
import java.util.*;
public class BinaryTest {
public static void main(String [] args){
Scanner input=new Scanner(System.in);
int count=0;
boolean check=true;
System.out.print("Enter a number: ");
int num=input.nextInt();
for(int i=0; i<=num; i++){
count=num%10;
if(count>1) {
check=false;
break;
}
else {
check=true;
}
num=num/10;
}
if(check)
System.out.println("Binary");
else
System.out.println("Not Binary");
}
}

Is it possible to return a user-input declared double within an if statement for use in the main?

I am wishing to prompt the user again if a double outside of the accepted range (0-100) is input, until the input is valid. When the input is considered valid, I am wanting to return correct input value, yet, returned instead is the first incorrect value. How can I return the correct input, as accepted by the if statement?? Many thanks!
public class examscore {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
double sumfin = finalscore(console);
System.out.println(sumfin); // if user input is initially invalid, but then corrected, the first, incorrect, value is printed
}
public static double finalscore (Scanner console) {
System.out.println();
System.out.println("Input final exam score: ");
while(!console.hasNextDouble()) { //prompts the user, if invalid input, to input again, until a valid value is input
System.out.println("Please input a mark between 0 and 100. ");
console.next();
}
double examscore = console.nextDouble();
if (examscore >=0 && examscore<= 100) {
System.out.println();
System.out.println("Exam Score = "+examscore);
} else {
System.out.println("Error:");
finalscore (console);
}
return examscore; //an attempt to return the VALID exam score: fails
}
}
A do-while loop would be a perfect fit. Example:
Scanner console = new Scanner(System.in);
double userInput = 0;
do {
System.out.println("Please input a mark between 0 and 100. ");
try {
userInput = console.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Your input could not be interpreted as a floating-point number.");
}
} while (userInput <= 0D || userInput >= 100D);
You missed to assign result of finalscore(console) to examscore inside the else block.
if (examscore >= 0 && examscore <= 100) {
System.out.println();
System.out.println("Exam Score = " + examscore);
} else {
System.out.println("Error:");
examscore = finalscore(console);
}
You can either use a loop or a recursive call to accomplish this. I prefer a recursive call:
private static double getValidScore(Scanner console) {
System.out.println();
System.out.println("Input final exam score: ");
try {
double score = Double.parseDouble(console.nextLine());
if (score >= 0 && score <= 100) {
return score;
}
} catch (NumberFormatException nfe) {}
System.out.println("Please input a mark between 0 and 100.");
return getValidScore(console);
}

test for data type errors in loops java

Yes, this is a homework problem. I am a beginner in programming. I am good at using if/else with for loops, since my professor asked us to while loop. I am confused.This is the question...
Q1) Suppose you are writing a game-playing program that involves 2-digit numbers, each number being composed of 2 different digits. Test if whether numbers entered in a sequence are accepted to be used in this game. Test for errors in input (including type).
My while loop to check the data type works fine at first, but after an int has been entered and I can't check the data type. Can anyone explain the problem to me please? Thank you...
public static void main(String[] args){
int num = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a 2-digit number. The digits should be different. zero to stop");
while(!input.hasNextInt()){
System.out.println("Not an integer,try again " + num);
input.next();
}
num = input.nextInt();
while(num != 0){
while(num < 10 || num >= 99){
System.out.println("NOT good for your game! " + num );
System.out.println("Enter a 2-digit number. The digits should be different. Zero to stop");
num = input.nextInt();
}
System.out.println("Good for your game! Play! " + num);
num = input.nextInt();
}
}
}
The while loop in the first checked the System.in is entering a digit (int) or not: while(!input.hasNextInt()), but when you first input a digit, the loop exit and it enter into the next 2 loops:
while(num != 0){
while(num < 10 || num >= 99){
and then in the end of the inner loop you have:
num = input.nextInt();
This means you already assume the next input would be an int. So if you enter a non-digit input, program will throw an exception.
I would suggest you to change the whole loop into:
public static void main(String[] args) {
int num = 1;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a 2-digit number. The digits should be different. zero to stop");
if (!input.hasNextInt()) {
System.out.println("Not an integer,try again " + num);
} else {
num = input.nextInt();
if (num < 10 || num >= 99) {
System.out.println("NOT good for your game! " + num);
} else {
System.out.println("Good for your game! Play! " + num);
}
}
} while(num != 0);
input.close();
System.out.println("game stop");
}
import java.util.Scanner;
public class Number1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String prompt = "Enter a 2-digit number. The digits should be different. Zero to stop:";
getInt(sc,prompt);
}
public static void getInt(Scanner sc,String prompt) {
System.out.println(prompt);
int num;
while (!sc.hasNextInt())
{
System.out.println("Not an integer, Try again");
sc.next();
}
num = sc.nextInt();
while(num != 0) {
if (num < 10 || num >= 99 || num == 0)
{
System.out.println("Not good for your game!");
}
else
{
System.out.println("Good for your game! Play!");
}
System.out.println(prompt);
num = sc.nextInt();
}
}
}

Categories