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

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

Related

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.

Prompting user to re-enter integers until binary number is entered

I am new with JAVA (computer programming by the way). The following program checks if the input is binary or not. And it should prompt user to re-enter integers until binary number is entered. But this program is doing exactly opposite.
It is asking me to re-enter integers if input is binary, and the program terminates when non-binary is entered.
I need a serious help, please.Here is my output
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 not a Binary Number.");
break;
} else {
System.out.println(value + " is a Binary Number.");
}
}
}
It might be too late for the answer. But the code can be simplified much if you make use of the method.
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Please enter positive integers: ");
int userValue = scan.nextInt();
if (isBinary(userValue)) {
System.out.println(userValue + " is a Binary Number.");
break;
} else {
System.out.println(userValue + " is a not Binary Number.");
}
}
}
public static boolean isBinary(int input) {
while (input > 0) {
if ((input % 10 != 0) && (input % 10 != 1)) {
return false;
}
input = input / 10;
}
return true;
}
}
Change your code
from this
if (notBinaryDigit > 0) {
System.out.println(value + " is a not a Binary Number.");
break;
} else {
System.out.println(value + " is a Binary Number.");
}
to this
if (notBinaryDigit > 0) {
System.out.println(value + " is a not a Binary Number.");
notBinaryDigit--;
} if(binaryDigit >0 {
System.out.println(value + " is a Binary Number.");
binaryDigit--;
break;
}
and it will ask for values and tell if it is binary or not and it terminates if it is binary
Error coming due to Scanner class.
you can run your program and check your logic by removing the Scanner class like this.
public class Test{
public static void main(String []args){
int value, userValue=34;
int binaryDigit = 0, notBinaryDigit = 0;
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 not a Binary Number.");
} else {
System.out.println(value + " is a Binary 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);
}
}

I need a Java Scanner 'reset' on invalid character fix

I am a new human learning to code!
I had a problem with my Scanner, which is that I need it to 'reset' on an invalid character.
My code:
public class Lemonade {
static int m = 150;
private static Scanner scan;
public static void main(String[] args) {
int day = 1;
for(int gameover = m; gameover > 0; day++) {
int Random = (int) (Math.random() * 100);
if(Random <= 25) {
System.out.println("Great Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 50) {
System.out.println("Good Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 75) {
System.out.println("Bad Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 100) {
System.out.println("Awful Chance!");
System.out.println("--------------------------------");
}
int count = 0;
int none = 0;
scan = new Scanner(System.in);
System.out.println("Enter a number between 0 and " + m + "!");
count = scan.nextInt();
if(count >= none && count <= m) {
System.out.println("You entered " + count + "!");
System.out.println("--------------------------------");
day = day + 1;
m = m - count;
System.out.println("Day " + day);
}
else {
System.out.println("Enter a number between 0 and " + m + ".");
count = scan.nextInt();
}
}
}
}
Now is my question how to get this to 'reset' on an invalid character like 'f', as Scanner only accepts numbers.
Thanks for the help!
If I understand you correctly then this is something you're looking for,
InputMismatchException will thrown if user enters invaild characters instead of int. You may use looping until the user enters an integer
import java.util.Scanner;
import java.util.InputMismatchException;
class Example
{
public static void main(String args[])
{
boolean isProcessed = false;
Scanner input = new Scanner(System.in);
int value = 0;
while(!isProcessed)
{
try
{
value = input.nextInt();
//example we will now check for the range 0 - 150
if(value < 0 || value > 150) {
System.out.println("The value entered is either greater than 150 or may be lesser than 0");
}
else isProcessed = true; // If everything is ok, Then stop the loop
}
catch(InputMismatchException e)
{
System.out.print(e);
input.next();
}
}
}
}
If this is not you're looking for please let me know!

Need to output all prime numbers [duplicate]

This question already has answers here:
Java Display the Prime Factorization of a number
(7 answers)
Closed 9 years ago.
for the example 60 the answer should be 2 2 3 5 but it only comes up with 2 3 5.
import java.util.Scanner;
public class PrimeFactor {
public static void main(String[] args) {
System.out.print("Enter a positive number: ");
Scanner scanner = new Scanner (System.in);
int number = scanner.nextInt();
int count;
for (int i = 2; i<=(number); i++) {
count = 0;
while (number % i == 0) {
number /= i;
count++;
}
if (count == 0) {
continue;
}
System.out.print(i + " ");
}
}
}
The problem is that once it finds that 60 is divisible by 2, it keeps dividing it by 2 (in this case twice).
place the final bracket of the while statement AFTER the System.out.print and it works:
public static void main(String[] args) {
System.out.print("Enter a positive number: ");
Scanner scanner = new Scanner (System.in);
int number = scanner.nextInt();
int count;
for (int i = 2; i<=(number); i++) {
count = 0;
while (number % i == 0) {
number /= i;
count++;
if (count == 0) {
continue;
}
System.out.print(i + " ");
}
}
}
If you'd like a different way to do it:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.print("Enter a positive number: ");
Scanner scanner = new Scanner (System.in);
int number = scanner.nextInt();
int divisor = 2;
while(number != 1) {
if(number % divisor == 0) {
System.out.println(divisor + " ");
number /= divisor;
}
else {
divisor++;
}
}
}
}

Categories