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;
// }
}
}
}
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
Explanation:
if the input string is 'hello worlds', output will be 2.
Length of the word "hello" = 5
Length of the word "worlds" = 6
add their length to get total length = 5+6 = 11
which is not a single digit, so continuously add all digits till we get single digit i.e. 1+1=2
Therefore, the single digit is = 2 (as answer/output).
I tried with my code as follows:
import java.util .*;
class Codestring {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter word");
String word = sc.nextLine();
int len2 = 0, len1 = 0, count = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == ' ') {
len2 = count;
System.out.println(len2);
count = 0;
} else {
count++;
}
}
len1 = count;
System.out.println(len1);
int c = len1 + len2;
System.out.println(c);
ArrayList<Integer> array = new ArrayList<Integer>();
do {
array.add(c % 10);
c /= 10;
}
while (c > 0);
System.out.println(array);
while (array.size() >= 2) {
array = reduce(array);
return array;
}
}
private static ArrayList<Integer> reduce(ArrayList<Integer> array) {
for (int i = 0; i < array.size(); i++) {
array = array[i] + array[i + 1];
}
return array;
}
}
I reached to my output as:
Enter word
hello worlds
5
6
11
[1, 1]
Below is the code that might answer your question
import java.util .*;
class Codestring {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter word");
String word = sc.nextLine();
String strSplits[] = word.split(" ");
int length = 0;
for (String strTmp : strSplits) {
System.out.println("Word: " + strTmp + ", Length: " + strTmp.length());
length += strTmp.length();
}
System.out.println("Total words: " + strSplits.length);
System.out.println();
System.out.println("Consolidated Length: " + reduce(length));
sc.close();
}
public static long reduce(long length) {
while (length > 9) {
System.out.println("Initial Length: " + length);
long y = 0, factor = 1;
// go through each digit from the bottom and calc the diff.
while (length > 9) {
y += factor * Math.abs(length % 10 - length / 10 % 10);
length /= 10;
// each digit is worth 10x the last.
factor *= 10;
}
length = y;
}
return length;
}
}
import java.util.*;
public class Main
{
public int digit(int num)
{
int s=0;
while(num>0)
{
int r=num%10;
s+=r;
num=num/10;
}
if(s>9)
{
s=digit(s);
}
return s;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String input1=sc.nextLine();
String a[]=input1.split("\\s");
int num=0;
for(int i=0;i<a.length;i++)
{
int n=a[i].length();
num+=n;
}
Main ob=new Main();
int n=ob.digit(num);
System.out.println(n);
}
SIMPLE METHOD TO SOLVE THIS :).IN this we first add the length of the string and then add that sum up to a single digit.
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);
}
I'm making a program that counts the frequency of letters from a user-entered string, and have recently encountered the 'Arithmetic Exception' error.
I cannot for the life of me figure out what's causing it, even though I know it's because something is being divided by 0.
Here's my code:
package day1.examples;
import java.util.Scanner;
public class rl_frequency_count {
public static int input;
public static void main(String[] args) {
System.out
.println("Please enter some text that you would like to work out the occurence for.");
System.out
.println("However, do remember that any other characters outside of the alphabet will NOT be counted.");
Scanner stringUser = new Scanner(System.in);
String input = stringUser.nextLine();
input = input.replaceAll("\\s+", "");
input = input.toLowerCase();
// counting occurrence of character with loop
int i;
int charCountA = 0;
int charCountB = 0;
int charCountC = 0;
int charCountD = 0;
int charCountE = 0;
int charCountF = 0;
int charCountG = 0;
int charCountH = 0;
int charCountI = 0;
int charCountJ = 0;
int charCountK = 0;
int charCountL = 0;
int charCountM = 0;
int charCountN = 0;
int charCountO = 0;
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'a') {
charCountA++;
getOccurence(charCountA, "A");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'b') {
charCountB++;
getOccurence(charCountB, "B");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'c') {
charCountC++;
getOccurence(charCountC, "C");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'm') {
charCountM++;
getOccurence(charCountM, "M");
}
}
}
// method for the occurrence
public static void getOccurence(int number, String letter) {
double occ = number / input * 10; //
System.out.println();
System.out.println("Number of " + letter + "'s - " + number);
System.out.println("Occurence of " + letter + " - " + occ + "%");
}
}
I know that I only have ABC and M in at the moment but was gonna work those in later.
This is the first time i've posted on here and i'm still newish to Java so any help whatsoever is greatly appreciated!
I ran it and it says line 67. here is the total:
public static void getOccurence(int number,String letter){
double occ = number / input *10; //
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
To fix:
double occ = (number > 0) ? number/input * 10 : 0;
This sets occ to 0 in case of number being set to 0. Good luck.
Hope this helps.
The line of code causing the error is in your method:
public static void getOccurence(int number,String letter){
double occ = number / input *10; // <------ERROR FROM HERE (input is always 0)
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
The input variable is declared in your class here:
Line 6: public static int input;
Since you didn't initialize it nor does the value is being changed in your codes, the value of input remains as 0 through out the entire program. (Default value for an uninitialized int variable is 0)
Since it is always 0, you are always dividing a number with 0.
double occ = number / 0*10;