I am quite new to java (and programming in general) and have the following code that I am studying and using to make an ISBN checker, but I get the message "cannot find symbol" for the method isISBN. Can you help me understand why is it and what can be done to make it work?
//isISBN.java class
public class isISBN {
// method to check number is ISBN
public static boolean isISBN(String number) {
// declare variable
int length = 0;
// remove all hyphens
number = number.replace("-", "");
// remove all spaces
number = number.replace(" ", "");
// check result string is a number or not
try {
// except for the case where
// ISBN-10 ends with X or x
char ch = number.charAt(9);
ch = Character.toUpperCase(ch);
if( ch != 'X') {
// don't store, only check
Long.parseLong(number);
}
} catch(NumberFormatException nfe) {
// not a number
return false;
}
// find length
length = number.length();
if(length==13)
return isISBN13(number);
else if(length==10)
return isISBN10(number);
return false;
}
// method to check ISBN-10
private static boolean isISBN10(String number) {
// declare variables
int sum = 0;
int digit = 0;
char ch = '\0';
// add upto 9th digit
for(int i=1; i<=9; i++) {
ch = number.charAt(i-1);
digit = Character.getNumericValue(ch);
sum += (i* digit);
}
// last digit
ch = number.charAt(9);
ch = Character.toUpperCase(ch);
if(ch =='X')
sum += (10*10);
else {
digit = Character.getNumericValue(ch);
sum += (digit * 10);
}
// check sum
if(sum % 11 == 0)
return true;
return false;
}
// method to check ISBN-13
private static boolean isISBN13(String number) {
// declare variables
int sum = 0;
int multiple = 0;
char ch = '\0';
int digit = 0;
// add digits
for(int i=1; i<=13; i++) {
if(i % 2 == 0)
multiple = 3;
else multiple = 1;
// fetch digit
ch = number.charAt(i-1);
// convert it to number
digit = Character.getNumericValue(ch);
// addition
sum += (multiple*digit);
}
// check sum
if(sum%10 == 0)
return true;
return false;
}
}
//Main.java
class Main {
public static void main(String[] args) {
// declare variables
String number = null;
boolean result = false;
//create Scanner class object to take input
Scanner scan = new Scanner(System.in);
// take input from end-user
System.out.print("Enter number::");
number = scan.nextLine();
int id = Integer.parseInt(scan.nextLine());
// check number is isbn number or not
result = isISBN(number);
// display result
if(result)
System.out.println(number +
" is an isbn number.");
else
System.out.println(number +
" is not an isbn number.");
// close Scanner class object
//scan.close();
}
}
Related
Write a program that will read a line of text String and display all the letters that occur in the text, one per line and in alphabetical order, along with the number of times each letter occurs in the text.
For this purpose, you must use an array of type int of length 26, so that the element at index 0 contains the number of a’s, the element at index 1 contains the number of b’s, and so forth.
Allow both uppercase and lowercase letters as input, but treat uppercase and lowercase versions of the same letter as being equal.
Hint: Use the method chatAt(int index) in the String class to get the individual character in a string at the specified index.
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] letters = new int[26];
char choice;
while (true) {
// taking user input
System.out.println("Please enter text ending with period:");
String text = sc.nextLine();
// converting it lowercase
text = getActualText(text).toLowerCase();
char c = 'a';
for (int i = 0; i < letters.length; i++)
// increasing character by 1
letters[i] = countLetters(text, c++);
System.out.println("\nThe frequency of the letters");
c = 'a';
for (int i = 0; i < letters.length; i++) {
// showing only those letters whose frequnecy is greater than 0
if (letters[i] != 0)
System.out.println(c + ": " + letters[i]);
c++;
}
System.out.print("Would you like to try another text?(Y/N) ");
choice = sc.nextLine().charAt(0);
if (choice == 'n' || choice == 'N')
break;
}
}
private static int countLetters(String text, char c) {
int count = 0;
for (int i = 0; i < text.length(); i++)
// counting the frequency
if (text.charAt(i) == c)
count++;
return count;
}
/**
* This method will extract the first sentence from a text ending with full stop(.)
*/
private static String getActualText(String text) {
String newText = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '.')
// breaking out of the loop if the full stop is found
break;
// adding it to the text
newText += text.charAt(i) + "";
}
return newText;
}
}
Try to change existing condition to below new condition:
Existing Condition: (Allowing frequencies which are not equal to 0):
if(letters[i] != 0) {//showing only those letters whose frequency is greater than 0
New Condition: (Allowing frequencies which are greater than or equal to 0):
if(letters[i] >= 0) {
It's enough to go through the text one time and count the occurrence of each letter. And then just show only letters with count >0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
do {
System.out.print("\nEnter the text: ");
String str = scan.nextLine();
print(histogram(str));
} while (shouldContinue(scan));
}
private static int[] histogram(String str) {
int[] letters = new int[26];
for (int i = 0; i < str.length(); i++)
if (Character.isLetter(str.charAt(i)))
letters[Character.toLowerCase(str.charAt(i)) - 'a']++;
return letters;
}
private static void print(int[] letters) {
System.out.println("The frequency of the letters:");
for (int i = 0; i < letters.length; i++)
if (letters[i] > 0)
System.out.println((char)('a' + i) + ": " + letters[i]);
}
private static boolean shouldContinue(Scanner scan) {
while (true) {
System.out.print("Would you like to try another text (Y/N)? ");
String str = scan.nextLine();
if (str.length() != 1)
continue;
if ("Y".equalsIgnoreCase(str))
return true;
if ("N".equalsIgnoreCase(str))
return false;
}
}
I am trying to compare two different strings, one character at a time. I need to return the correct number of digits until they do not equal each other anymore. However, I can't include the character of '.' in the return statement. How would I go about doing this?
import java.util.Scanner;
import java.math.BigDecimal;
public class PiEstimate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a;
String b;
char y;
char c;
char d;
String userInput;
do {
System.out.print("Enter a number of randomly generated points:");
userInput = in.nextLine();
if (!isValid(userInput)) {
System.out.print("\n" + "You entered an invalid integer. Please enter a valid integer greater than 0: ");
userInput = in.nextLine();
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
} else {
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
}
System.out.println("\n" + "Would you like to play again? Enter 'Y' for yes or 'N' for no: ");
String optionToPlay = in.nextLine();
c = optionToPlay.charAt(0);
d = Character.toUpperCase(c);
if (d == 'n' || d == 'N') {
BigDecimal estimate2= new BigDecimal( (Math.PI / 4) * 4);
System.out.println("\n" + "The best estimate is: " + estimate2);
}
} while (d == 'Y');
} // end psvm
public static boolean isValid(String a) {
boolean isFlag = true;
char holder;
for (int i = 0; i < a.length(); i++) {
holder = a.charAt(i);
if (!Character.isDigit(a.charAt(i))) {
return false;
} if (i == 0 && holder == '-') {
return false;
}
} // end for
return isFlag;
} // end isValid
public static double calculation(String a) { // String a means 'looking for a string
double calc = Double.parseDouble(a);
int i;
double x;
double y;
double c = 0;
double runningCounter = 0;
double totalCounter;
for (i = 0; i < calc; i++) {
x = Math.random();
y = Math.random();
c = Math.sqrt((x * x) + (y * y));
if (c <= 1) {
runningCounter++;
}
} // end for
totalCounter = ((runningCounter / calc) * 4);
calc = totalCounter;
return calc;
}
public static int comparison (String bear, String userInput) {
int i = 0;
String s = calculation(userInput) + "";
int b;
int counter2 = 0;
for (i=0; i < s.length(); i++) {
if (s.charAt(i) != bear.charAt(i)) {
return i;
}
}
return i;
} // end comparison
} // end class
Code from IDE
I'm a first year in Computer Science Engineering, and I'm currently taking a Java programming course. It's the first programming language I've ever tried learning and I'm completely stuck. I had to design a program for class that takes a credit card number input from the user and determines whether or not it is valid. I've somehow messed up my loops, and now the whole thing keeps repeating at least 5 times more than I need it to. How could I fix this? It's due by 3:00 and I'm freaking out. Here is my code:
package osu.cse1223;
import java.util.Scanner;
public class Project07 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("Enter a credit card number (enter a blank line to quit):");
String cardNumber = in.nextLine();
int length = cardNumber.length();
if (length != 16 && length > 0) {
System.out.print("ERROR! Number MUST have exactly 16 digits");
}
else if (length <= 0) {
System.out.println("Goodbye!");
}
else {
char checkDigitChar = cardNumber.charAt(15);
int checkDigit = Character.getNumericValue(checkDigitChar);
int pos = 0;
while (pos < 16) {
char digit = cardNumber.charAt(pos);
int number = Character.getNumericValue(digit);
int doubled = number * 2;
pos = pos + 2;
int sum = 0;
if (doubled > 9) {
String sub = Integer.toString(doubled);
char one = sub.charAt(0);
char two = sub.charAt(1);
int numOne = Character.getNumericValue(one);
int numTwo = Character.getNumericValue(two);
int doubleAdjusted = numOne + numTwo;
sum = sum + doubleAdjusted;
}
else {
}
int newPos = 1;
int newSum = 0;
while (newPos < 16) {
char digitForSum = cardNumber.charAt(newPos);
int individualNum = Character.getNumericValue(digitForSum);
newPos = newPos + 2;
newSum = individualNum + newSum;
}
int total = sum + newSum;
String subTwo = Integer.toString(total);
char onesPlace = subTwo.charAt(1);
int ones = Character.getNumericValue(onesPlace);
int realCheckDigit = 10 - ones;
System.out.println("Check digit should be: " + realCheckDigit);
System.out.println("Check digit is: " + checkDigit);
if (checkDigit == realCheckDigit) {
System.out.println("Number is valid");
}
else {
System.out.println("Number is not valid");
}
}
}
}
}
You are not ending your first loop in the right place.
int doubleAdjusted = numOne + numTwo;
sum = sum + doubleAdjusted;
}
else {
}
}// ADD THIS TO END THE FIRST WHILE LOOP
And remove a } from the bottom of the code.
This loop repeats 8 times, but in fact it should be stoped after the first cycle. There are two ways to do this. First, you can add "break;" in the end of the last cycle. Second, you can not use "while (pos < 16) {}" loop at all. Both variants will give you the same result.
Here is the variant:
public class Various {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Enter a credit card number (enter a blank line to quit):");
String cardNumber = in.nextLine();
int length = cardNumber.length();
if (length != 16 && length > 0) {
System.out.print("ERROR! Number MUST have exactly 16 digits");
}
else if (length <= 0) {
System.out.println("Goodbye!");
}
else {
char checkDigitChar = cardNumber.charAt(15);
int checkDigit = Character.getNumericValue(checkDigitChar);
int pos = 0;
// while (pos < 16) {
char digit = cardNumber.charAt(pos);
int number = Character.getNumericValue(digit);
int doubled = number * 2;
// pos = pos + 2;
if (doubled > 9) {
String sub = Integer.toString(doubled);
char one = sub.charAt(0);
char two = sub.charAt(1);
int numOne = Character.getNumericValue(one);
int numTwo = Character.getNumericValue(two);
int doubleAdjusted = numOne + numTwo;
sum = sum + doubleAdjusted;
}
else {
}
int newPos = 1;
int newSum = 0;
while (newPos < 16) {
char digitForSum = cardNumber.charAt(newPos);
int individualNum = Character.getNumericValue(digitForSum);
newPos = newPos + 2;
newSum = individualNum + newSum;
}
int total = sum + newSum;
String subTwo = Integer.toString(total);
char onesPlace = subTwo.charAt(1);
int ones = Character.getNumericValue(onesPlace);
int realCheckDigit = 10 - ones;
System.out.println("Check digit should be: " + realCheckDigit);
System.out.println("Check digit is: " + checkDigit);
if (checkDigit == realCheckDigit) {
System.out.println("Number is valid");
}
else {
System.out.println("Number is not valid");
}
// break;
// }
}
}
}
So I have been given a project in where I must validate ISBN-10 and ISBN-13 numbers. My issue is that I want to use an ArrayList based on what the user inputs(the user adds as many numbers as they want to the ArrayList). Here is my code (without an ArrayList). How can I modify this so that the user can put as many ISBN number as they want?
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
//Get the ISBN
System.out.print("Enter an ISBN number ");
isbn = input.nextLine();
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
}else{
isValid = false;
}
//Print check Status
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{
System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
//
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
}
public static List<String> scanNumberToListUntilAppears(String end) {
if(end == null || end.isEmpty())
end = "end";
List<String> numbers = new ArrayList<>();
String message = "Enter an ISBN number: ";
try (Scanner input = new Scanner(System.in)) {
System.out.print(message);
while(input.hasNext()) {
String isbn = input.nextLine();
if(isbn.equalsIgnoreCase(end)) {
if(!numbers.isEmpty())
break;
} else {
numbers.add(isbn);
if(numbers.size() == 1)
message = "Enter the next ISBN number or '" + end + "': ";
}
System.out.print(message);
}
}
return numbers;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
String ans;
ArrayList<String> isbns = new ArrayList<String>();
// user will enter at least 1 ISBN
do{
//Get the ISBN
System.out.println("Enter an ISBN number ");
isbns.add(input.nextLine());
//loops till answer is yes or no
while(true){
System.out.println("Would you like to add another ISBN?");
ans = input.nextLine();
if(ans.equalsIgnoreCase("no"))
break;
else if (!(ans.equalsIgnoreCase("yes"))
System.out.println("Please say Yes or No");
}
}while(!(ans.equalsIgnoreCase("yes"));
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
for(int i = 0; i<isbns.size(); i++)
isbns.set(i, isbns.get(i).replaceAll("( |-)", ""));
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
for(String isbn : isbns){
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
print(isbn, isValid);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
print(isbn, isValid);
}else{
isValid = false;
print(isbn, isValid);
}
}
public static void print(String isbn, boolean isValid){
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{ System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
How can I add a statement that allows me to check if the credit card number inputted by the user is a palindrome? I am checking for the appropriate length already so how can i Input the new palindrome checker into this code:
import java.util.Scanner;
public class DT18 {
public static void main(String[] args) {
String number;
Boolean debug = false;
if (args.length == 0) { // no command line
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Credit Card number to validate.");
number = keyboard.next();
} else { // command line input
number = args[0];
}
if (debug) System.out.println("String Length " + number.length());
if (number.length() < 10) {
System.out.println("Not Valid");
}
int sum = 0;
int oddDigit = 0;
for (int i = number.length() - 1; i >= 0; i--) {
if (debug) System.out.println("i = " + i);
if ((Character.getNumericValue(number.charAt(i)) < 0) || (Character.getNumericValue(number.charAt(i)) > 9)) {
System.out.println("Not Valid");
break;
}
if (i % 2 == 0) { //Even Digit
sum += Character.getNumericValue(number.charAt(i));
} else { //Odd Digit
oddDigit = (2 * Character.getNumericValue(number.charAt(i)));
if (oddDigit > 9) oddDigit = (oddDigit % 10) + 1;
sum += oddDigit;
}
if (debug) System.out.println(sum);
}
if (sum % 10 == 0) {
System.out.println("Valid");
} else {
System.out.println("Not Valid");
}
}
}
From an answer I once gave here:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}
This post should give you for loop logic:
http://www.programmingsimplified.com/java/source-code/java-program-check-palindrome
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
You can write a simple function to check if a string is a palindrome or not.
private static boolean checkPalindrome(String input) {
int i = 0, j = input.length() - 1;
for (; i < j; i++) {
if (i == j) {
return true;
}
if (input.charAt(i) == input.charAt(j)) {
j--;
}
else
return false;
}
return true;
}
This is a crude method; you may want to modify it according to your requirement, but it will get the job done in most of the cases.
I've looked over the other answers and all of them have bad performance and working with String instead of just using the given number. So I'll add the version without conversion to String:
public static boolean isPalindrome(int n) {
int[] digits = new int[length(n)];
for (int i = 0; n != 0; ++i) {
digits[i] = n % 10;
n /= 10;
}
for (int i = 0; i < digits.length / 2; ++i) {
if (digits[i] != digits[digits.length - i - 1]) {
return false;
}
}
return true;
}
public static int length(int n) {
int len = 0;
while (n != 0) {
++len;
n /= 10;
}
return len;
}
Not sure, if that's the best implementation, but I got rid of Strings :-)