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);
}
Related
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();
}
}
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;
// }
}
}
}
i have a problem writing guess the word game java code .
i'll show you my current code and till you the problem .
import java.util.Scanner;
class Q
{
public static void main(String argss[])
{
String strs[] = { "kareem", "java", "izz", "tamtam", "anas" };
Scanner input = new Scanner(System.in);
int index = ((int) (Math.random() * 5));
int points = 50;
String c;
boolean result = false;
boolean finalResult = false;
boolean tempResult = false;
String word = strs[index];
System.out.println(
"\t *** Enter a character and guess the world*** \n\t ***You will loose if your points become 0 *** \n ");
System.out.println(stars(word));
System.out.println("Your points: " + points);
System.out.print("Enter and guess a character! ");
String temp = stars(word);
String oldTemp = temp;
c = input.next();
while (points > 0)
{
for (int i = 0; i < word.length(); i++)
{
result = (word.charAt(i) + "").equals(c);
if (result == true)
{
temp = toChar(i, temp, c);
}
}
finalResult = temp.equals(word);
tempResult = temp.equals(oldTemp);
System.out.println(temp);
if (finalResult == true)
{
System.out.println("\n \n YOU HAVE GUESSED THE WORLD,YOU WON ! ");
break;
}
if (tempResult == true)
{
points = points - 5;
System.out.println("False and now your points are " + points);
}
else if (tempResult == false)
{
System.out.println("True and now your points are " + points);
}
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
System.out.print("Guess another time,enter a character: ");
c = input.next();
}
}
public static String stars(String word)
{
String temp = "";
for (int i = 0; i < word.length(); i++)
temp = temp + "*";
return temp;
}
public static String toChar(int index, String temp, String c)
{
char[] tempChar = temp.toCharArray();
char s = c.charAt(0);
tempChar[index] = s;
temp = String.valueOf(tempChar);
return temp;
}
}
now as you can see in line number 39 , i have a little problem here because when its false it'll be no longer right .
do you know another way to compare if the entry is right or not ?
Doesn't look like you are changing oldTemp inside the while loop. Try setting it to equal to temp after all of the if statements.
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
oldTemp = temp; // add this here
System.out.print("Guess another time,enter a character: ");
c = input.next();
How can I display ZERO, POSITIVE, NEGATIVE string with corresponding array in one JOptionPane message?
Here is the code....
String display="";
int z = 0;
String size = JOptionPane.showInputDialog("Enter Your Prefered Size Of Your Array");
int newsize = Integer.parseInt(size);
JOptionPane.showMessageDialog(null,"You Entered "+newsize+".");
int array[] = new int [newsize];
for (int a=0; a<array.length;a++)
{
array[a] = Integer.parseInt(JOptionPane.showInputDialog("Enter Value For Array["+a+"]."));
}
for (int a=0;a<array.length;a++)
{
display=display+array[a]+"\n";
if (z == array[a])
{
String c=array[a]+" ZERO";
JOptionPane.showMessageDialog(null,"Arrays\n"+display+c);
}
else if (z < array[a])
{
String c =array[a]+" POSITIVE";
JOptionPane.showMessageDialog(null,"Arrays\n"+display+c);
}
else if (z != array[a])
{
String c =array[a]+" NEGATIVE";
JOptionPane.showMessageDialog(null,"Arrays\n"+display+c);
}
JOptionPane.showMessageDialog(null,"Arrays\n"+display+c);
}
Is this what you are after:
public class SO2{
public static void main(String[] args) {
String display="";
int z = 0;
String size = JOptionPane.showInputDialog("Enter Your Prefered Size Of Your Array");
int newsize = Integer.parseInt(size);
JOptionPane.showMessageDialog(null,"You Entered "+newsize+".");
int array[] = new int [newsize]; //Sets array
for (int a=0; a<array.length;a++){//Puts values in array
array[a] = Integer.parseInt(JOptionPane.showInputDialog("Enter Value For Array["+a+"]."));
}
for (int a=0;a<array.length;a++){
display=display+array[a]+"\n";
}
String toShow = ""; //String to build up
for(int i = 0; i < array.length; i++){
if(array[i] == 0){
display = "ZERO";
} else if(array[i] < 0){
display = "NEGATIVE";
} else if(array[i] > 0){
display = "POSITIVE";
}
toShow += "Array element " + i + " is " + array[i] + " and it is " + display + "\n"; //Build string
}
JOptionPane.showMessageDialog(null,"Your numbers...\n\n"+toShow);//show
}}
It shows all the numbers from the array with their POS/NEG/ZERO values next to them. I have added some comments to try and explain a little
Good luck!