Java excercise - checking ID number - java

I have a task with checking ID number and I must check if this ID has 11 characters, if those characters are digits and I must check control number. Number is correct when this equation is correct:
ID = abcdefghijk
(1*a+3*b+7*c+9*d+1*e+3*f+7*g+9*h+1*i+3*j+1*k) % 10 = 0
Sample correct ID is: 49040501580
And here is my program. I don't know how to check if ID is digit and why it isn't correct. Anyone help? XD
Thank you in advance :3
import java.util.*;
public class wat {
public static void main(String[] args) {
char[] weights = {1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1};
System.out.print("Enter next digits your ID number: ");
Scanner keyboard = new Scanner(System.in);
String number = keyboard.nextLine();
char[] ofm = number.toCharArray();
Character[] id = new Character[ofm.length];
for (int i = 0; i < ofm.length; i++) {
id[i] = ofm[i];
System.out.print(id[i] + " ");
int length = id.length;
if (length == 11) {
System.out.println("This ID number has 11 digits");
System.out.println("Checking of the control number");
int amount = 0;
amount = id[i] * weights[i];
System.out.println(amount);
int result = 0;
result = amount % 10;
if (result == 0) {
System.out.println("ID number is correct");
} else {
System.out.println("ID number is not correct");
break;
}
} else {
System.out.print("This ID number hasn't 11 digits.");
break;
}
}
}
}
Sample output

With a minimal number of changes to your original code, I believe this is what you need.
import java.util.*;
public class wat {
public static void main(String[] args) {
char[] weights = {1,3,7,9,1,3,7,9,1,3,1};
System.out.print("Enter next digits your ID number: ");
Scanner keyboard = new Scanner(System.in);
String number = keyboard.nextLine();
char[] ofm=number.toCharArray();
Character[] id=new Character[ofm.length];
if (ofm.length == 11) {
System.out.println("This ID number has 11 characters");
int amount = 0;
for (int i = 0; i < ofm.length; i++) {
id[i]=ofm[i];
System.out.print(id[i]+" ");
int length = id.length;
if (isDigit(id[i])) {
amount = id[i]*weights[i];
} else {
System.out.println("character is not a digit");
break;
}
}
} else {
System.out.print("This ID number hasn't 11 digits.");
return;
}
System.out.println("Checking of the control number");
System.out.println(amount);
int result =0;
result = amount % 10;
if (result == 0) {
System.out.println("ID number is correct");
} else {
System.out.println("ID number is not correct");
}
}
}
As you can see, we're now verifying the string length before the loop starts.
Then we're checking each character is a digit one by one and quitting with a new error message if one of them is not. You'll need to provide the isDigit function yourself (plenty to choose from on StackOverflow!).
We're accumulating the digit values multiplied by the weight into the amount variable, with a new value being added each time the loop iterates.
Finally we verify the result is correct after the loop has finished and all 11 characters have been processed.
NOTE: I don't normally work in Java so I'm not entirely sure if you can get the digit value out of a Character type object (to multiply it with the weight) like this. You might find that you are getting ASCII code values, or something else entirely. If this happens, you'll need to convert 'weights' into an array of integers, and extract the actual numeric value from the Character before multiplying them together.

Related

Checking whether a number is an Unique number or not

I have written a program to check if a number is an Unique number.
[A Unique number is a number with no repeating digits and no leading zeros.]
I have written the following code:
Scanner sc=new Scanner(System.in)
System.out.println("Enter the number to be checked: ");
String num=sc.nextLine();
if(num.charAt(0)!='0')
{
Outer:
for(int i=0;i<num.length();i++)
{
for(int j=0;j<num.length();j++)
{
if(num.charAt(i)==num.charAt(j))
{
System.out.println("No, "+num+" is not a Unique number.");
break Outer;
}
}
if(i==num.length()-1)
{
System.out.println("Yes, "+num+" is a Unique number.");
}
}
}
else
System.out.println("No, "+num+" is not a Unique number as it has leading zeros.");
The problem is that is shows any number as NOT Unique, even 12345.
I would like to know where I have gone wrong.
Your code will always find "duplicate" characters when i == j.
You should change the indices of the loop in order not to compare a character to itself:
for(int i=0;i<num.length();i++) {
for(int j=i+1;j<num.length();j++) {
if(num.charAt(i)==num.charAt(j))
...
Besides, you should only output the "...is a Unique number." message after you are done with the outer loop.
Lets assume , length of input number to be 10 and "i" has reached the value of 5 in the for loop.
Now "j" will have the values 0 to 9.
So when "j" is equal to 5 , the if condition becomes true as you are comparing the digit at 5th position with itself (which is always true).
If you add i != j condition , it will fix the issue :-
if(num.charAt(i)==num.charAt(j) and i != j)
Alternatively, you can modify the loop for j to start from i + 1 so
that there are no overlaps.
for(int j=i+1;j<num.length();j++)
The second option is much better as it will reduce the number of comparisons from (n*n)
to (n * (n - 1))/2) , where n is the number of digits in the input number.
A possible solution is to use Stream to convert your String in a Set of char, then if the size of the set is the same as the length of your string, it is unique:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to be checked: ");
String num = sc.nextLine();
boolean unique = Stream.of(num.split(""))
.map(s -> new String(s))
.collect(Collectors.toSet()).size() == num.length();
// With "1234" -> print true
// With "12342" -> print false
System.out.println(unique);
You can use below short and handy approach:
String a = "123452";
String[] split = a.split("");
List<String> list = Arrays.asList(a.split(""));
Set<String> set = new HashSet<>(list);
System.out.println("Unique: " + (list.size() == set.size()));
import java.util.*;
public class spnum
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
String num = sc.next();
int ctr = 0;
boolean isNumUnique = true;
for(int i = 0; i < num.length(); i++)
{
for(int j = 0; j < num.length(); j++)
{
if(num.charAt(i) == num.charAt(j))
{
ctr++;
}
}
if(ctr > 1)
{
isNumUnique = false;
}
ctr = 0;
}
if(isNumUnique == true)
{
System.out.println("Number is a unique number");
}
else
{
System.out.println("Number is not a unique number");
}
}
}
this code would give the right answer

Using scanner input to make a for loop

I am trying to make a sort of ATM. I want the program to do the following: If a user enters a number, the number gets multiplied by 12.
I already have the following code:
import java.util.Scanner;
public class DisplayMultiples {
public static void main(String args[]) {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
keyboardInput.nextLine();
int b = 12;
if() {
for (int i = 1; i < b; i++) {
System.out.println(i*b);
}
else {
System.out.println("Error, this value is never used");
}
}
}
Convert the input to a number.
If the input is not a number, show error message, and exit.
If the input is a number, multiply it by 12, show result, and exit.
The easiest way is to get an int from the Scanner and then check if it's between 1 and 12, and if so, multiply it by 12.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
int number = keyboardInput.nextInt();
if (number > 0 && number < 13) {
System.out.println(number * 12);
} else {
System.out.println("Error, this value is never used");
}
Note that as you are likely a beginner, entering anything but an int in the console will result in an error but I assume that's not entirely necessary for you. If it is, read up on try...catch.
This way will avoid exceptions when entering non numbers.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
String inpStr = keyboardInput.nextLine();
int b = 12;
int inpVal = -1;
try {
inpVal = Integer.parseInt(inpStr);
} catch (NumberFormatException nfe) {
}
if (inpVal >= 1 && inpVal <= 12) {
System.out.println(inpVal * b);
} else {
System.out.println("Error, this value is never used");
}

How to split an input of numbers (student ID) from user to implement into formula

I'm having trouble with this beginner java program that was assigned to me, I'm completely new to java and I'm having a lot of trouble with this particular program. These are the instructions:
Your program should prompt users to enter an n-digit number as a student ID, and then display the
validity of the entered ID. You can assume n will be in the range of 6 and 10 inclusive. The checksum
digit is part of student ID. Your algorithm is to match the rightmost digit in the entered ID with the
computed checksum digit. If there is no match, then your program shall report the entered ID being
invalid.
For example, the entered ID 1234567 is invalid because the computed 7th digit is 1 (= (1 * (digit1) + 2 *
(digit 2) + 3 * (digit 3) + 4 * (digit 4) + 5 * (digit 5) + 6 * (digit 6)) % 10) and is different from the actual 7th digit which is
7. However, if the entered ID is 1234561 your program shall display a message of acceptance.
The first step I'm trying to do is to read each number from the user's input that doesn't have spaces, as if it were to have spaces. Then I'm trying to get each of those numbers assigned to the variable that is digit 1, digit 2, ... etc. to compute.
import java.util.Scanner;
public class H4_Ruby{
public static void main(String[] args){
// this code scans the the user input
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a student ID between 6-10 digits");
String nums = scan.nextLine();
String[] studentIdArray = nums.split(" ");
int[] studentID = new int [studentIdArray.length];
for (int i = 0; i < studentIdArray.length; i++)
{
studentID[i]= Integer.parseInt(studentIdArray[i]);
System.out.print(studentID[i] + ",");
}
}
That is my code so far...
You can't split by nums.split(" ") to get a String array. You already got a String Id from user without spaces.
So iterate through the String and keep calculating the sum of products with multiplier like below. I've added comments in the code itself.
public static void main(String[] args) {
// this code scans the the user input
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a student ID between 6-10 digits");
String nums = scan.nextLine();
int multiplier = 1, totalProductSum = 0;
for (int i = 0; i < nums.length() - 1; i++) {
// if the character is not digit, its not a valid id
if (!Character.isDigit(nums.charAt(i))) {
System.out.println("Invaild Id");
return;
}
// maintain the sum of products and increment the multiplier everytime
totalProductSum += (multiplier * (nums.charAt(i) - '0'));
multiplier++;
}
// the condition for validity i.e totalProduct sum mod 10 and last digit in input Id
if ((totalProductSum % 10) == (nums.charAt(nums.length() - 1) - '0'))
System.out.println("Valid Id");
else
System.out.println("Invaild Id");
}
Here, you can use this one also:
final class H4_Ruby {
public static void main(final String... args) {
System.out.printf("%s student ID%n", (H4_Ruby.isValid(H4_Ruby.read())) ? "Valid" : "Invalid");
}
private static String read() {
final Scanner scan = new Scanner(System.in);
// [start] do-while here for input validation: length and all characters must be digits
System.out.print("Please, enter a student ID between 6-10 digits: ");
final String input = scan.nextLine();
// [end] do-while here for input validation: length and all characters must be digits
return input;
}
private static boolean isValid(final CharSequence studentId) {
int partial = 0;
for (int i = 0; i < (studentId.length() - 1); i++) {
partial += ((i + 1) * Character.getNumericValue(studentId.charAt(i)));
}
return (partial % 10) == Character.getNumericValue(studentId.charAt(studentId.length() - 1));
}
}

Checking if String entered is a binary numer, getting incorrect output

I am trying to write a program that will check if the user-entered string is a binary number, and if it is, it will output the number of 1s in the number. I had this working fine with an integer value, but since an int can't hold more than 2 billion or whatever the max value is, I am trying to rewrite it to work with Strings.
As of right now, any number I enter will output "Number entered is not binary." and when I enter 0, I will get a StringIndexOutofBoundsException. I am a fairly novice programmer, so forgive any obvious errors I may have missed, I am just asking for a possible solution to my problem or a push in the right direction. Here is my code (after trying to make it work with Strings rather than integers):
import java.util.*;
public class BinaryHW {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String bin = kb.nextLine();
//the method I used to check whether or not user entered a binary
//number requires changing the value of 'bin'.
//Therefore, 'origBin' set equal to 'bin' for later use.
String origBin = bin;
int count = 0;
boolean isBinary = true;
/* if bin = 0, then this loop will be skipped because
* 0 is a binary number and need not be checked.
*/
while (Integer.parseInt(bin) != 0) {
int lastDigit = bin.charAt(bin.length() - 1);
if (lastDigit > 1) {
System.out.println("Number entered is not binary.");
isBinary = false;
break;
} else {
bin = bin.substring(bin.length() - 2);
}
}
//Again, the method I used to count the 1s in the bin number
//requires changing the value of origBin, so origBin2 is introduced
String origBin2 = origBin;
for (int i = 0; i < origBin.length(); i++) {
if (origBin.charAt(origBin.length() - 1) == 1) {
count ++;
origBin2 = origBin.substring(origBin2.length() - 2);
} else {
origBin2 = origBin.substring(origBin2.length() - 2);
}
}
if (isBinary)
if (count == 1)
System.out.println("There is "
+ count + " 1 in the binary number entered.");
else
System.out.println("There are "
+ count + " 1s in the binary number entered.");
}
}
I think you are overcomplicating things... simply iterate through your binary string, and keep track of the number of 1's reached. If a number other than 0 or 1 is found, report that input is a non-binary number. Below is a snippet which accomplishes this:
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String bin = kb.nextLine();
int oneCount = 0;
boolean validBinaryNum = true;
for (int i = 0; i < bin.length() && validBinaryNum; i++) {
char currentChar = bin.charAt(i);
if (currentChar == '1') oneCount++;
else if (currentChar != '0') {
validBinaryNum = false;
}
}
if (validBinaryNum && bin.length() != 0) {
System.out.println("Number of 1's: " + oneCount);
} else {
System.out.println("Number is not binary");
}
}

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