Java search for number sequence - java

Here are the exact words of my project
"Write a class and test program that prompts the user to enter a three-digit number
such that the digits are in order. For example 123, 567. The program will loop until a
correct value is entered. ( 576 is incorrect)"
I have written this program that searches for a specific password but what i need is one that searches for any numerical value where the numbers are in order and im having trouble writing a program that searches for something thats not a specific value, heres what i have so far.
import java.util.Scanner;
public class pass {
public static void main(String[] args) {
int passw;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter 3 digits in sequence");
passw = sc.nextInt();
if(passw != 567) {
System.out.println("Access Denied");
}
else {
System.out.println("Access Granted");
}
}
while(passw != 567);
}
}

You could use a method to check for whether the given digits are in order.
private boolean isInOrder(int number){
int digit = -1;
while(number > 0){
if (digit != -1 && digit != (number % 10) + 1)
return false; // Since the number is not in order
digit = number % 10;
number /= 10;
}
return true; // If the number is in order
}
This method can check whether a number (of any length, not only 3), is in the order specified in the question.

Since you know that your "password" will be an integer with only three digits, you can easily accomplish whether the digits are ordered or not with an if statement. Try out the following code and see if it works for you!
public class ThreeDigitPasswordTest {
public static boolean testPassword(int number) {
char[] cArr = String.valueOf(number).toCharArray();
if((cArr[2] == cArr[1] + 1) && cArr[1] == cArr[0] + 1)
return true;
return false;
}
public static void main(String[] args) {
System.out.println(testPassword(567)); //prints "true"
System.out.println(testPassword(576)); //prints "false"
}
}

Related

Why does my Validare Zip Code(boolean) program return false?

The instruction to the program is: Zip codes consist of 5 consecutive digits. Prompt the user for a five digit zip code as a String. Create a Java method called isValid and pass the String as a parameter to the method. In the method determine whether the input is a valid zip code. A valid zip code is as follows:
Must only contain numbers (no non-digits allowed).
Must not contain any spaces.
Must not be greater than 5 digits in length.
If the zip code is valid return true to the main method, else return false.
Everytime I put in a valid zip code it still says false
this is my code:
import java.util.Scanner;
public class Main
{
public static void main (String[]args)
{
Scanner input = new Scanner (System.in);
System.out.println ("Enter a zip code: ");
String zipCode = input.nextLine ();
System.out.println (isValid (zipCode));
}
public static boolean isValid (String zipCode)
{
boolean yes = false;
int i = 0;
for (i = 0; i < zipCode.length (); i++)
{
int digit = zipCode.charAt (i);
//if only contains number
if (digit > 48 && digit < 57)
{
System.out.println (digit);
}
else
{
return false;
}
int len = zipCode.length ();
if (len == 4)
{
System.out.println (len);
}
else
{
return false;
}
}
return yes;
}
}
You should include both 0 and 9 , Hence, please change this line
if (digit > 48 && digit < 57)
to
if (digit >= 48 && digit <= 57)
On the other hand, the length of a zip should be 5 instead of 4, Hence, please change this line:
if (len == 4)
to
if (len == 5)
You can refactor the code and use a matcher in order to reduce the validations.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a zip code: ");
String zipCode = input.nextLine();
System.out.println(isValid(zipCode));
}
public static boolean isValid(String zipCode) {
boolean yes = false;
// Check that only digits are accepted and the length is equals to 4
if (zipCode.matches("[0-9]+") && zipCode.length() == 4) {
yes = true;
}
return yes;
}
}
boolean yes = false;
return yes;
if (len == 4) {
...
} else {
return false;
}
Your two specific mistakes.
More generally, you need to learn how to debug. Eventually you'll get some basic skill in eyeballing errors, but only the most simple errors are eyeballable. (It's surely a word, no?)
Take out pen and paper if you have to, but the name of the game is: You calculate what you think the code should do in your head. Then you let the computer do it and compare notes: What should every variable be, what is the result of every call? Crosscheck with what you think. Where you and computer disagree? Bug.
Then it's just a matter of picking some inputs and off you go. A debugger makes this a lot simpler, but some System.out.println statements and some sweat will take care of it too.
Do that next time instead of asking on SO. It's good exercise, and you'll never be worth a can of beans as a programmer if you can't do this.

Why do i get a NumberFormatException error? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
So the code is supposed to continually give fibonacci values for any given number until you enter "q", but for some reason instead of stopping, I get an error, anyone know why? I know that if you try to parse a string, it will cause the error but I have "if(input != "q")" to stop that so why is it still happening?
Tester class:
import java.util.Scanner;
public class FibonacciTester
{
public static void main(String[] args)
{
String input = "1";
System.out.println("Input a positive integer that you want to find the fibonacci number for");
System.out.println("Type 'q' to quit");
Scanner in = new Scanner(System.in);
while (input != "q"){
System.out.print("Type in the positive integer");
input = in.next();
if(input != "q"){
int number = Integer.parseInt(input);
FibonacciV fibonacci = new FibonacciV(number);
number = FibonacciV.fibonacci(number);
System.out.println("The Fibonacci number: " + number);
}
}
}
}
Class
public class FibonacciV
{
FibonacciV(int x)
{
}
public static int fibonacci(int x)
{
if (x == 0) //Base case
{
return 0;
}
else if (x == 1) //Second base case
{
return 1;
}
else
{
return fibonacci(x-1)+ fibonacci(x-2); // recursive call
}
}
}
Change input != "q" to !input.equals("q").
Read more about how to compare strings in java.
You are getting NumberFormatException because it's running Integer.parseInt(input) when the input is "q", which is not a number. And the code was able to reach this statement because your string comparison is incorrect.

Java password checking, code modification

Password should consist of minimum 8 characters.
Password should consist both numbers and letter.
No special characters are allowed.
The output of this code is always "Invalid Password"
What should be modified to get the correct output?
import java.util.*;
import java.lang.String;
import java.lang.Character;
public class password {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
if (password.length() < 8) {
return false;
} else {
for(int i = 0; i <= password.length() - 1; i++) {
char c = password.charAt(i);
if (!Character.isLetter(c) | !Character.isDigit(c)) {
return false;
}
}
}
return true;
}
}
| is a bitwise or, || is a logical or. You should know the difference.
Work this way though:
if(!Character.isLetter(c) && !Character.isDigit(c))
return false;
=> If the character is not a letter nor a digit return false
You have only one | in your code when doing the OR in your if statement. It should be || . I was stumped on the same thing for an hour yesterday :l
| is a bitwise operator, || is a logical operator. Also, there is a problem with the logic. A Character can't be a Letter and Digit at the same time, so this condition is always true. Try using &&
if(!Character.isLetter(c) && !Character.isDigit(c))
return false;
I feel that I should mention a few mistakes in your approach, as it might help save you time in the future.
If your method isValid, you have a loop which iterates over all the characters in the string. This is the right way to do this, so you clearly know what you need to do to achive the aim.
However, logically, what this method does next is as follows.
Get the first character in the string
Check if the character is a digit or a char
If that character is not a digit or char, return false
Your method will fall over if the first character is not a char, or not a digit. Rationally, you have the right idea, but a letter is not a number, and vise versa.
Suppose the first letter is 'A' - it's not a number, so return false.
If the first character is '1' - it's not a letter, so return false.
As you have seen, changing the operator to && will stop the program failing if you enter only numbers or letters, but will return false if you add any non alphanumeric value.
If you need to enforce at least one digit and at least one number, you have to store the number of digits and chars you have in the string as you iterate over it.
Have two variables, one to store the total number of digits, and one to store the number of chars, and increment them as you step through the string.
If the total number of digits found is greater than zero, and the total number of letters found is greater than zero, your password is valid.
import java.util.*;
import java.lang.String;
import java.lang.Character;
public class password {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
if(password.length()<8) {
return false;
} else {
int dCount = 0;
int cCount = 0;
for (int i=0; i<=password.length()-1; i++) {
char c=password.charAt(i);
if(Character.isLetter(c) {
cCount++;
}
if(Character.isDigit(c)) {
dCount++;
}
}
return dCount > 0 && cCount > 0;
}
}

Homework Write a test program that prompts the user to enter an integer and reports whether the integer is a palindrome [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
Objective:
(Palindrome integer) Write the methods with the following headers:
// Return the reversal of an integer, i.e., reverse(456) returns 654
public static int reverse(int number)
// Return true if number is a palindrome
public static boolean isPalindrome(int number)
Use the reverse method to implement isPalindrome. A number is a palindrome
if its reversal is the same as itself. Write a test program that prompts the
user to enter an integer and reports whether the integer is a palindrome.
My code is below... My attempt is below. I've collapsed and I don't know what else to do BUT come here. I'm stuck on the Boolean portion of the code and do not know if the rest of this code is right. I've scoured the internet and seen very few examples but none of them made any sense. I'm a visual learner, so none of this really makes sense to me. Started Java 2 months ago so please don't expect me to produce gold with extremely limited knowledge. I need help-help, not petty or witty comments. If you don't want to offer help, don't comment.
public class NewClass {
public static int reverse(int number) {
int remainder = 0;
while (number != 0) {
remainder = number % 10;
number = number / 10;
System.out.print(remainder);
}
System.out.println(" is the reverse number.");
return remainder;
}
//I don't really know what to do here.
public static boolean isPalindrome(int number, int remainder) {
return number == remainder;
}
//Nor do I know what I'm doing here. I'm supposed to make the result from 'reverse' either true or false but I don't know what it write, considering the 'Boolean' portion is unfinished.
public static void main(String[] args) {
System.out.print("Enter an integer: ");
java.util.Scanner input = new java.util.Scanner(System.in);
int number = input.nextInt();
reverse(number);
int remainder = 0;
if ( remainder == ture)
}
}
Revised:
public class NewClass {
public static int reverse(int number) {
int reverse = 0;
while (number != 0) {
reverse = (reverse * 10) + number % 10;
number = number / 10;
System.out.print(reverse);
}
System.out.println(" is the reverse number.");
return (reverse);
}
public static boolean isPalindrome(int number) {
return (number == reverse(number)); //Still being asked to introduce this line. I don't know what that means. My book says nothing and the internets isn't helping.
}
public static void main(String[] args) {
System.out.print("Enter an integer: ");
java.util.Scanner input = new java.util.Scanner(System.in);
int number = input.nextInt();
reverse(number);
if (number == reverse(number)) {
System.out.println(number + " is a palindrome");
}
else{
System.out.println(number + " is not a palindrome");
}
}
}
**Results:
run:
Enter an integer: 121
112121 is the reverse number.
112121 is the reverse number.
121 is a palindrome
BUILD SUCCESSFUL (total time: 2 seconds)**
My question: I don't know what I'm doing with the true and false portion of this code. The point is to check the number, compare it to the reversed number checking whether it is a palindrome or not. The second issue is with the reverse number repeating itself with double the number... I don't know what I'm doing wrong or how to fix it.
Query:
public static boolean isPalindrome(int number) {
return (number == reverse(number));
}
I'm being asked to introduce this line but I don't know what it means. It's the only error I have. It's supposed to return the true or false, correct? What do I do with it because it seems like I created a code that doesn't need that specific line, even though it is required.
If you're talking about how to implement isPalindrome in terms of reverse, it's simply figuring out if the number and its reverse are the same.
So, for example, 767 is a palindrome because, when reversed, it's equal to the original. However, 314159 is not a palindrome because its reversal is a totally different number, 951413.
That means pseudo-code like this should suffice (I've included reverse because your current implementation, while close, returns the final remainder rather than the reversed number):
def reverse(num):
rnum = 0
while num != 0:
rnum = (rnum * 10) + (num % 10)
num = num / 10
return rnum
def isPalindrome(num):
return (num == reverse(num))
If you want to nut it out yourself, don't look below. This is how I'd approach it for this level of skill and I'm providing it just for completeness.
public class Test {
public static int reverse (int num) {
int rnum = 0;
while (num > 0) {
rnum = (rnum * 10) + (num % 10);
num = num / 10;
}
return rnum;
}
public static boolean isPalindrome (int num) {
return (num == reverse (num));
}
public static void main(String args[])
{
System.out.println(isPalindrome (767));
System.out.println(isPalindrome (12321));
System.out.println(isPalindrome (4));
System.out.println(isPalindrome (314159));
}
}
I personally use my two methods for doing it, but the guy who did the StringBuilder thing did good too :).
Here is my code for reversal and then I call that and check if it a palindrome.
public static String reverseString(String str)
{
String blank = "";
for(int i = str.length()-1; i >= 0; i--)
{
blank = blank + str.charAt(i);
}
return blank;
}
// NOW you can call isPalindrome("Whatever string you wanna check.");
public static boolean isPalindrome(String str)
{
String reverse = reverseString(str);
if(str.equalsIgnoreCase(reverse))
{
return true;
}
else
{
return false;
}
}
Here is example for check the given number is palindrome or not .
public static void main(String [] args) {
System.out.println("Please Enter a number : ");
int palindrome = new Scanner(System.in).nextInt();
if(isPalindrome(palindrome)){
System.out.println("Number : " + palindrome + " is a palindrome");
}else{
System.out.println("Number : " + palindrome + " is not a palindrome");
}
}
/*
* Java method to check if number is palindrome or not
*/
public static boolean isPalindrome(int number) {
int palindrome = number; // copied number into variable
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and reverse of number is equal means
// number is palindrome in Java
if (number == reverse) {
return true;
}
return false;
}
}

binary to base10 in java with main method and TWO classes/method (boolean and

I am a beginner programmer. This is what I have so far. The directions for the question are kind of difficult. Here is what I am trying to accomplish..
You will write a program that converts binary numbers to base 10 numbers. This program will ask the user to enter a binary number. You will have to verify that what is entered by the user only has 0s and 1s. In the case the user entered letters, you have to keep asking the user for another input. When the input is valid, you will convert the binary number to a base 10 number. Please use the Question1.java file provided in the A2.zip file.
Valid input - In order to check if the input is valid your program should call the CheckInputCorrect method, which takes a String as an input parameter and returns a boolean value. An input string is considered valid if it corresponds to a number in binary representation.
More specifically, in the CheckInputCorrect method, you should scan this string to make sure it only contains ‘0’ or ‘1’ characters. As soon as you find a character that is not ‘0’ or ‘1’, the method should returns false. If the method reaches the end of the input string (i.e. all characters are ‘0’ or ‘1’) the method should return true.
Converter - At this point we assume that the input string is valid (checked with the CheckInputCorrect method). To convert the input from binary to base 10, you must implement the BinaryToNumber method. The BinaryToNumber method should take as parameter a String and return an integer, which corresponds to converted value in base 10.
The binary conversion should work as follows. For each digit in the binary number, if the digit is ‘1’ you should add the corresponding decimal value ( 20 for the rightmost digit, 21 for the next digits to the left, 22 for the next one, and so on) to a variable that will hold the final result to be returned. This can be easily accomplished by using a loop.
1) Am I on the right path?
2) I don't exactly know what I am doing and need you to help me figure that out....
Update1:
When I run this vvvv: It says "Please enter a binary number for me to convert: and then a place for me to type in my answer but whatever i put it just returns another box for me to type in but stops and doesn't evaluated anything.
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
boolean BinaryNumber = false;
String inputString = "";
while (!BinaryNumber){
inputString = inputKeyboard.next();
BinaryNumber = CheckInputCorrect(inputString);
System.out.println("You have given me a " + BinaryNumber + "string of binary numbers.");
}
int finalNumber = BinaryToNumber(inputString);
System.out.println("Congratulations, your binary number is " + finalNumber + ".");
}
public static boolean CheckInputCorrect(String input)
{
for (int i = 0; i < input.length(); i++)
{
while (i < input.length());
if (input.charAt(i) != '0' && input.charAt(i) != '1')
{return false;}
i++;
}
return true;
}
public static int BinaryToNumber(String numberInput)
{
int total = 0;
for (int i = 0; i < numberInput.length(); i++){
if (numberInput.charAt(i)=='1')
{
total += (int)Math.pow(2,numberInput.length() - 1 - i);
}
}
return total;
}
}
Original:
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
int binarynumber;
int arraySize = {0,1};
int[] binaryinput = new int[arraySize];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a binary number");
binarynumber = in.nextInt();
if (binarynumber <0)
{
System.out.println("Error: Not a positive integer");
}
if (CheckInputCorrect) = true;
{
System.out.print(CheckInputCorrect);
}
public static boolean CheckInputCorrect(String input);
{
boolean b = true;
int x, y;
x = 0
y = 1
b = x || y
while (b >= 0 {
System.out.print("Please enter a binary number")
for (int i = 0; i < binarynumber.length; i++)
{
binaryinput[i] = in.nextInt();
if (binaryinput[i] = b.nextInt();
System.out.printl("Binary number is:" + binaryinput);
break outer;
if (binarynumber != b)
{
System.out.println("Error: Not a binary number")
}
return true;
}
}
public static int BinaryToNumber(String numberInput)
{
int remainder;
if (binarynumber <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number %2;
printBinaryform(number >> 1);
System.out.print(remainder);
return 0;
}
}
}
As mentioned in my comments, your updated code contains two errors
while (i < input.length()); is an infinite loop, because it has no body. Therefore i cannot be increased and will stay lower than input.length().
inputString = inputKeyboard.next(); request another input after the first one and the first input will be ignored.
This is a fixed and commented version of your updated code:
public class Question1 {
public static void main(String[] args) {
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
//boolean BinaryNumber = false; // not needed anymore
//String inputString = ""; // not needed too
while (!checkInputCorrect(inputUser)) { // there is no reason for using a boolean var here .. directly use the returned value of this method
System.out.println("You have given me an invalid input. Please enter a binary number: "); // changed this message a little bit
inputUser = inputKeyboard.nextLine(); // re-use the "old" variable inputUser here
}
int finalNumber = binaryToNumber(inputUser);
System.out.println("Congratulations, your decimal number is " + finalNumber + ".");
}
public static boolean checkInputCorrect(String input) { // method names should start with a lower case letter
for (int i = 0; i < input.length(); i++) {
//while (i < input.length()); // this loop is deadly. Please think about why
if (input.charAt(i) != '0' && input.charAt(i) != '1') {
return false;
}
//i++; // what is the purpose of this? The "for" loop will increment "i" for you
}
return true;
}
public static int binaryToNumber(String numberInput) { //method name ... lower case letter ;)
int total = 0;
for (int i = 0; i < numberInput.length(); i++) {
if (numberInput.charAt(i) == '1') {
total += (int) Math.pow(2, numberInput.length() - 1 - i);
}
}
return total;
}
}

Categories

Resources