Here are the instructions for what I am supposed to be doing.
Write a program that inputs a string that represents a binary number.
The string can contain only 0s and 1s and no other characters, not
even spaces.
Validate that the entered number meets these requirements. If it does
not, display an error message. If it is a valid binary number,
determine the number of 1s that it contains. If it has exactly two 1s,
display "Accepted". Otherwise, display "Rejected".
All input and output should be from the console. Here are some sample
inputs to test:
abc 10102011 10101FF 0000 1111 (note the space in this test case)
00000000 1111 01110000001 1000001
What I have so far is written here:
import java.util.Scanner;
import java.util.Set;
class ValidateBinary1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
boolean notCorrect = false;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
isCorrect = true;
}
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
}
}
if(isCorrect)
System.out.println("Accepted");
else if(notCorrect)
System.out.println("Rejected");
}
}
What can I write to have the program output the "rejected" line?
Try this ( you are using bitwise operator & instead of logical operator &&) but I dont think using && either is correct; you have to use bitwise or ||. Also you are not check for the number of ones, the number of ones in the input string must be exactly 2 according to your problem description.
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
short numberOfOnes = 0;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
numberOfOnes++;
}
else if(! (binary.charAt(i) == '0' || binary.charAt(i) == '1'))
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
break;
}
}
if(isCorrect && numberOfOnes == 2)
System.out.println("Accepted");
else
System.out.println("Rejected");
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
boolean isCountCorrect = true;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1' || binary.charAt(i) == '0') {
continue;
} else {
isCorrect = false;
break;
}
}
if (isCorrect == true) {
int count = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
count++;
}
}
if (count > 2) {
isCountCorrect = false;
}
}
if (isCorrect = true && isCountCorrect == true) {
System.out.println("Approved");
} else
System.out.println("Rejected");
}
Here we go. I took one of the answers and used it to modify my code and came up with this:
import java.util.Scanner;
import java.util.Set;
class ValidateBinary1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
short numberOfOnes = 0;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
numberOfOnes++;
}
else if(binary.charAt(i) != '0' && binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
}
}
if(isCorrect && numberOfOnes == 2)
System.out.println("Accepted");
else
System.out.println("Rejected");
}
}
This is exactly what I needed. Thanks!
Related
I've read that I would need to put "continue" after an "if" statement, but every I tried this with my if statement and it states that "continue cannot be used outside of a loop."
Set it in the loop. EX:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true){
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
String s = input.nextLine();
if (thepassword(s)) {
System.out.println("Valid Password");
break;
} else {
System.out.println("Invalid Password");
}
}
}
See more : Java Break and Continute
Use an outer infinite loop with a lable, then break the loop using break loop_lable. Check until a valid input is made.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
loop:for(;;)
{
String s = input.nextLine();
if (thepassword(s))
{
System.out.println("Valid Password");
break loop;
}
else
{
System.out.println("Invalid Password");
continue loop;
}
}
input.close();
}
public static boolean thepassword(String password) {
boolean thepassword = true;
if (password.length() < 8) {
thepassword = false;
} else {
int totaldigits = 0;
for (int n = 0; n < password.length(); n++) {
if (thedigit(password.charAt(n)) || theletter(password.charAt(n))) {
if (thedigit(password.charAt(n))) {
totaldigits++;
}
} else {
thepassword = false;
break;
}
}
if (totaldigits < 2) {
thepassword = false;
}
}
return thepassword;
}
public static boolean theletter(char c) {
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
public static boolean thedigit(char c) {
return (c >= '0' && c <= '9');
}
}
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.");
}
}
}
package pureTest;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class test3 {
public static void main(String[] args) {
/* Enter your code here. */
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 2; i< n; i++){
if( n <= 3){
System.out.println("Prime");
break;
}else if( n%i ==0){
System.out.println("Not Prime");
break;
}else{
System.out.println("Prime");
}
}
}
}
the input of 7; the out put is repetitions of Prime:
7
Prime
Prime
Prime
Prime
Prime
Just wondering why the if condition doesn't work out here.
your code will print prime until it finds divisor !
for (int i = 2; i< n; i++){
if( n <= 3){
System.out.println("Prime");
break;
}else if( n%i ==0){
System.out.println("Not Prime");
break;
}else{
System.out.println("Prime"); --> this line will be printed every time in your loop!
}
}
Also you don't need to iterate till n, as after n/2 there would be no number which can divide n :-)
Check this code...
private static boolean checkPrime(int n) {
int i = 2;
while(i<=n/2){
if(n%i++ == 0){
return false;
}
}
return true;
}
Your else clause is wrong. It prints "Prime" each time n is not divisible by i. It will even print prime for non prime inputs (for example, it will print "Prime" for 21 before printing "Not Prime", since 21%2 != 0).
Change your loop to something like :
for (int i = 2; i < n; i++) {
if( n <= 3){
System.out.println("Prime");
return;
} else if(n%i == 0){
System.out.println("Not Prime");
return;
}
}
System.out.println("Prime");
public static void main(String[] args) {
/* Enter your code here. */
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean isPrime = true;
for (int i = 2; i< n; i++){
if( n <= 3){
break;
}else if( n%i ==0){
System.out.println("Not Prime");
break;
}
}
if (isPrime) {
System.out.println("Prime");
} else {
System.out.println("Not prime");
}
}
If you want to simply check in the main function the above is ok. If you want to do that well try the following:
public static void main() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (isPrime(n)) {
System.out.println("Prime");
} else {
System.out.println("Not prime");
}
}
boolean isPrime(int n) {
if (n < 2) {
return false;
if (n == 2)
return true;
if (n%2 == 0)
return false;
for (int i = 3; i*i<=n; i+=2){
if (n%i == 0)
return false
return true;
}
boolean isPrime = true;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 2; i< n; i++){
if(n%i==0) {
System.out.println("Not Prime");
isPrime=false;
break;
}
}
if(isPrime) {
System.out.println("Prime");
}
I am trying to find if a phone number fits the format (xxx)xxx-xxxx where x is a digit. First, I have the program for the length and the '(',')', and '-'. When I type in something that doesn't work, I get the logical output. However, when I type in a properly formatted number, my program doesn't return anything.
import java.util.Scanner;
public class Program04 {
public static void main(String args[])
{
Scanner stdIn = new Scanner(System.in);
String pN;
System.out.print("Please enter a phone number (ddd)ddd-dddd :");
pN = stdIn.nextLine();
char a = pN.charAt(1);
char b = pN.charAt(2);
char c = pN.charAt(3);
char d = pN.charAt(5);
char e = pN.charAt(6);
char f = pN.charAt(7);
char g = pN.charAt(9);
char h = pN.charAt(10);
char i = pN.charAt(11);
char j = pN.charAt(12);
if (pN.length() == 13 && pN.charAt(0)=='(' && pN.charAt(4)== ')' && pN.charAt(8)=='-')
{
if (a>=0 && a<=9)
{
if (b>=0 && b<=9)
{
if (c>=0 && c<=9)
{
if (d>=0 && d<=9)
{
if (e>=0 && e<=9)
{
if (f>=0 && f<=9)
{
if (g>=0 && g<=9)
{
if (h>=0 && h<=9)
{
if (i>=0 && i<=9)
{
if (j>=0 && j<=9)
{
System.out.print("This is a valid phone number!");
}
}
}
}
}
}
}
}
}
}
}
else System.out.println("Not a vaid phone number.");
}
}
It's easier to use pattern-matching (regex) for validation:
...
pN = stdIn.nextLine();
System.out.println(pN.matches("\\(\\d{3}\\)\\d{3}-\\d{4}"));
Even if you want to have it check if each character is a digit, using so many nested if's is not the way to go. Instead, define a simple method that applies the check, say:
private static boolean isDigit(char x) {
return x>=0 && x<=9;
}
and then do:
if ( isDigit(a) && isDigit(b) && ...) {
return true;
}
else {
return false;
}
If you're not allowed to use RegEx or if it is too difficult to understand, try simplifying your nested if's by a simple switch inside a loop, it is much more readable and maintenance is the easiest :
public static void main(String[] args) {
String pn = scan.nextLine();
boolean valid = true;
if (pn.length() == 13){
for (int i = 0 ; i < 13 ; i++){
switch(i){
case 0 : valid = pn.charAt(0) == '(';break;
case 4 : valid = pn.charAt(4) == ')';break;
case 8 : valid = pn.charAt(8) == '-';break;
default : valid = Character.getNumericValue(pn.charAt(i)) >= 0 && Character.getNumericValue(pn.charAt(i))<= 9 ; break;
}
if (!valid) break;
}
if (!valid) System.out.println("Invalid number");
}else{
valid = false;
System.out.println("Invalid length");
}
if (valid){
System.out.println(pn + " is a valid telephone number");
}
}
Also, to avoid working with the ASCII value of a char, try using the Character.getNumericValue(Char c) method. It returns a numeric that you can use for your tests, like above.
It is better to use regex in this case:
You can use following :
String pattern = "(\\(\\d{3}\\)\\d{3}-\\d{4})";
Pattern r = Pattern.compile(pattern);
pN = stdIn.nextLine();
Matcher m = r.matcher(pN);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}
I have the user entering a single character into the program and it is stored as a string. I would like to know how I could check to see if the character that was entered is a letter or a digit. I have an if statement, so if its a letter its prints that it's a letter, and the same for a digit. The code I have so far doesn't work but I feel like I'm close. Any help you can offer is appreciated.
System.out.println("Please enter a single character: ");
String character = in.next();
System.out.println(character);
if (character.isLetter()){
System.out.println("The character entered is a letter.");
}
else (character.isDigit()){
Syste.out.println("The character entered is a digit.");
You could use:
if (Character.isLetter(character.charAt(0))){
....
You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) {
...
} else if (Character.isLetter(c)) {
...
}
...
If you ever want to know exactly how this is implemented, you could always look at the Java source code.
Ummm, you guys are forgetting the Character.isLetterOrDigit method:
boolean x;
String character = in.next();
char c = character.charAt(0);
if(Character.isLetterOrDigit(charAt(c)))
{
x = true;
}
This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0)
now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.
here is a code for your program:
import java.util.Scanner;
class Practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Input a letter");
String line = in.nextLine();
char c = line.charAt(0);
if( Character.isDigit(c))
System.out.println(c +" Is a digit");
else if (Character.isLetter(c))
System.out.println(c +" Is a Letter");
}
}
By using regular expressions:
boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}");
char charInt=character.charAt(0);
if(charInt>=48 && charInt<=57){
System.out.println("not character");
}
else
System.out.println("Character");
Look for ASCII table to see how the int value are hardcoded .
This is the way how to check whether a given character is alphabet or not
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
char temp = yourString.charAt(0);
if(Character.isDigit(temp))
{
..........
}else if (Character.isLetter(temp))
{
......
}else
{
....
}
import java.util.*;
public class String_char
{
public static void main(String arg[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value");
String data;
data = in.next();
int len = data.length();
for (int i = 0 ; i < len ; i++){
char ch = data.charAt(i);
if ((ch >= '0' && ch <= '9')){
System.out.println("Number ");
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
System.out.println("Character");
}
else{
System.out.println("Symbol");
}
}
}
}
You need to convert your string into character..
String character = in.next();
char myChar = character.charAt(0);
if (Character.isDigit(myChar)) {
// print true
}
Check Character for other methods..
You could do this by Regular Expression as follows
you could use this code
EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();
if (Number.matches(NumberPattern) && s.length() > 0)
{
//code for number
}
else
{
//code for incorrect number pattern
}
I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.
public class test {
public static void main(String[] args) {
String c;
boolean b;
System.out.println("Enter the value");
Scanner s = new Scanner(System.in);
c = s.next();
b = containsNumber(c);
try {
if (b == true) {
throw new CharacterFormatException();
} else {
System.out.println("Valid String \t" + c);
}
} catch (CharacterFormatException ex) {
System.out.println("Exception Raised-Contains Number");
}
}
static boolean containsNumber(String c) {
char[] ch = new char[10];
ch = c.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 48) && (ch[i] <= 57)) {
return true;
}
}
return false;
}
}
CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.