how to make the input not read a certain number - java

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);
}
}

Related

Why am I getting Output was not found error in 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.

why the count result do not meet the real result

when i run this code and enter first grade 4 and second is 3 the count should be 2 and the avareg is 3
why the result do not be that?
public static void main (String args[]){
Scanner input = new Scanner (System.in);
System.out.println("enter your grade or -1 to exit ");
int grade = 0 , sum = 0 , count = 1;
while (count <= 5 && grade != -1) {
System.out.println("the grade no " + count);
grade = input.nextInt();
sum += grade;
count++;
}
System.out.println("the avareg is = " + sum/count);
System.out.println(sum);
System.out.println(count);
}
Count start at one and it should start at 0.
At first input, count become 2 and at second input it becomes 3.
I did the folowing changes and it works :
public class myClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter your grade or -1 to exit ");
int grade = 0 , sum = 0 ,count = 1 ;
for (; count<=5 && grade!=-1 ;count++) {
System.out.println("Enter " + count + ": ");
grade = input.nextInt();
sum = sum+grade ;
}
System.out.println("the avareg is = " + (sum+1)/(count-2));
System.out.println("sum= "+(sum+1));
System.out.println("count= "+(count-2));
}
}
I just add 1 to sum and taked 2 from count

Find Two largest numbers in a list without using Array

I'm Stuck with my homework. Basically,we need to Create a program to find the largest and smallest integers in a list entered by the user.And stops when the user enters 0. However we are not allowed to user arrays for this problem.
and one more condition : If the largest value appears more than once, that value should be listed as both the largest and second-largest value, as shown in the following sample run.
I have met the first condition of the program however I cannot meet the 2nd condition.
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
if(num >= max1st && num >= max2nd) {
max1st = num;
}
if(num >= max2nd && num < max1st) {
max2nd = num;
}
count++;
}
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
I have tried to use this code.
if(num >= max2nd && num <= max1st) {
max2nd = num;
}
however when I run the program
https://imgur.com/a/YMxj9qm - this shows.
It should print 75 and 45 . What can I do to meet the first condition and meet the second condition?
If you exceed your maximum number (max1st), your new maximum number will be set to num. But your second largest number will be the current maximum number. So try this condition:
if (num > max1st) {
max2nd = max1st;
max1st = num;
} else if (num > max2nd) {
max2nd = num;
}
Please user If else in those cases. You have used two if statements that is replacing the value of max2nd.
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
if(num >= max1st && num >= max2nd) {
max1st = num;
}
else if(num >= max2nd && num < max1st) {
max2nd = num;
}
count++;
}
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
I changed the conditions, please take a look
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
num = sc.nextInt();
while(num != 0) {
System.out.print("Integer No." + count + " ");
if(num > max1st) {
if(max1st > max2nd) {
max2nd = max1st;
}
max1st = num;
} else {
if(num > max2nd) {
max2nd = num;
}
}
count++;
num = sc.nextInt();
}
System.out.println("");
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
Here is a much simpler method.
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
do
{
num = sc.nextInt();
max2nd = (num >= max1st) ? max1st : (num > max2nd) ? num : max2nd;
max1st = num > max1st ? num : max1st;
}
while(num != 0)
System.out.println("\nThe largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
If you need any more explanation I will be happy to help.
You can try below approach, this should solve your issue =>
import java.util.*;
public class BackedList {
private static Scanner sc;
public static void main(String args[]){
sc = new Scanner(System.in);
int num = 1;
List<Integer> integersList = new ArrayList<Integer>();
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
integersList.add(num);
}
Collections.sort(integersList, Collections.reverseOrder());
if(integersList.get(0) == integersList.get(1)){
System.out.println("The number " + integersList.get(0) + " is first largest and "
+ integersList.get(1) + " is the second largest number");
}
else
{
System.out.println("The largest number is :" + integersList.get(0) + " and the smallest one is :"
+ integersList.get(integersList.size()-1));
}
}
}
You can use the collection to get the largest and second largest like :
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(5);
list.add(2);
Collections.sort(list);
int firstLargest = list.get(list.size()-1);
int secLargest = list.get(list.size()-2);
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
if(num > max1st) {
max2nd=max1st;
max1st = num;
}
else if(num == max1st ) {
max2nd = num;
}
count++;
}
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
you are over complicating things with && in your if. if a number is greater than 1st 1sr gets changed if a number is same as first 2nd gets changed if its not bigger or same nothing happens.

Need to prompt user to enter integers until binary number is entered

This is the program that checks if the input integer is binary or not, now I need to create a loop that will prompt the user to renter integers until binary number is entered.
import java.util.Scanner;
public class BinaryNumbers {
public static void main(String[] args) {
int value, userValue;
int binaryDigit = 0, notBinaryDigit = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter positive integers: ");
userValue = scan.nextInt();
value = userValue;
while (userValue > 0) {
if ((userValue % 10 == 0) || (userValue % 10 == 1)) {
binaryDigit++;
} else {
notBinaryDigit++;
}
userValue = userValue / 10;
}
if (notBinaryDigit == 0) {
System.out.println(value + " is a Binary Number.");
} else {
System.out.println(value + " is not a Binary Number.");
}
}
}
Why not using Regular Expressions?
All those checking on user inputs by assuming them as numbers (by calling Scanner#nextInt or Scanner#nextFloat or ...) are very breakable. How can be so sure user won't enter anything wrong?
It's better to hold the user input in a String variable and check it against being binary integer (which has to be 32 bit at most as defined in many languages such as java) using Regex is more safe:
import java.util.Scanner;
public class CheckBinaryInteger {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean isValid = false;
String userInput = "";
do {
System.out.print("Please Enter a binary integer: ");
userInput = sc.next();
isValid = userInput != null && !userInput.trim().isEmpty()
&& userInput.matches("[01]{1,32}");//assume every digit as one bit
if(!isValid)
System.out.println("invalid binary integer entered! ");
}while(!isValid);
System.out.println("Valid input: "+userInput);
}
}
Hope this helps.
import java.util.Scanner;
public class BinaryNumbers {
public static void main(String[] args) {
int value, userValue;
Scanner scan = new Scanner(System.in);
while(true){
int binaryDigit = 0, notBinaryDigit = 0;
System.out.println("Please enter positive integers: ");
userValue = scan.nextInt();
value = userValue;
while (userValue > 0) {
if ((userValue % 10 == 0) || (userValue % 10 == 1)) {
binaryDigit++;
} else {
notBinaryDigit++;
}
userValue = userValue / 10;
}
if (notBinaryDigit == 0) {
System.out.println(value + " is a Binary Number.");
return; //does the trick ;)
} else {
System.out.println(value + " is not a Binary Number.");
}
}
}
}
A simple return can end the program then and there :)
import java.util.Scanner;
class calculatePremium
{
public static void main(String[] args) {
int value, userValue;
int binaryDigit = 0, notBinaryDigit = 0;
Scanner scan = new Scanner(System.in);
while(true) /*use a while loop to iterate till you get the binary number*/
{
binaryDigit = 0; notBinaryDigit = 0;
System.out.println("Please enter positive integers: ");
userValue = scan.nextInt();
value = userValue;
while (userValue > 0) {
if ((userValue % 10 == 0) || (userValue % 10 == 1)) {
binaryDigit++;
} else {
notBinaryDigit++;
}
userValue = userValue / 10;
}
if (notBinaryDigit == 0) {
System.out.println(value + " is a Binary Number.");
break; /* breaks out of loop when gets the correct input */
} else {
System.out.println(value + " is not a Binary Number.\n");
}
}
}
}
You just need to use a loop till you get a binary number.
Hope it helps.
import java.util.Scanner;
public class BinaryNumbers {
public static void main(String[] args) {
int value, userValue;
int binaryDigit = 0, notBinaryDigit = 0;
Scanner scan = new Scanner(System.in);
while(true)
{
System.out.println("Please enter positive integers: ");
userValue = scan.nextInt();
value = userValue;
while (userValue > 0)
{
if ((userValue % 10 == 0) || (userValue % 10 == 1))
binaryDigit++;
else
notBinaryDigit++;
userValue = userValue / 10;
}
if (notBinaryDigit == 0)
{
System.out.println(value + " is a Binary Number.");
break;
}
else
System.out.println(value + " is not a Binary Number.");
}
}
}

Multiple of an Integer inside range

I am doing a school project and I kinda got blocked.
I am looking forward building a javascript that asks the user of a number between 1 and 20 and then finds and lists all the multiples of that number inside range 0 and 100.
Here is what it looks like at the moment:
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%100) == 0) {
System.out.println(n1);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
I am obviously bad at math cause I can't get the formula to work.
Thank you in advance!
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%i) == 0) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
All multiples that fall between 0 and 100? That's the kind of thing for-loops are made for. After performing your IO and reading the number n1, change that while loop to the following.
for (int i = n1; i >= 0 && i <= 100; i = i + n1) {
System.out.println(i);
}
In case you aren't familiar with for loops, this basically says, set i to the value of n1, and keep adding n1 to it, printing each value as you go. When it leaves the range of 0..100, it terminates. So for instance, if 8 is entered it goes 8, 16, 24, 32, ..., 80, 88, 96.
If you really want to use a while loop, then try:
int i = n1;
while(i >= 0 && i <= 100) {
System.out.println(i);
i = i + n1;
}
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1*i) <= 100) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
This should work. You were just finding if the number n1 was divisible by 100.

Categories