UPC Code Problems - java

I have been trying to find out why my output is not what it is supposed to be. The Samples given are
Enter a UPC (enter a blank line to quit): 036000291453 Check digit
should be: 2 Check digit is: 3 UPC is not valid
Enter a UPC (enter a blank line to quit): 036000291452 Check digit
should be: 2 Check digit is: 2 UPC is valid
Enter a UPC (enter a blank line to quit): 014633149077 Check digit
should be: 4 Check digit is: 7 UPC is not valid
Enter a UPC (enter a blank line to quit): 014633149074 Check digit
should be: 4 Check digit is: 4 UPC is valid
Enter a UPC (enter a blank line to quit): 0853911765722 ERROR! UPC
MUST have exactly 12 digits
Enter a UPC (enter a blank line to quit): 085391176572 Check digit
should be: 2 Check digit is: 2 UPC is valid
Enter a UPC (enter a blank line to quit): Goodbye!
The algorithm of getting the that output is this From left to right, add the digits in the odd-numbered positions (starting the count from 1) and multiply the result by 3.
From left to right, add the digits in the even-numbered positions to the total computed in step 1
Take the result from step 2 and compute the remainder when divided by 10 (result modulo 10). If the remainder is not zero, subtract this remainder from 10 to get the check digit. If the remainder is zero, then the check digit should be 0.
String str1 = validinput(in);
int odd1 = odd(str1);
int even1 = even(str1);
int f = (odd1+even1)%10;
if(f != 0){
f = 10-f;
}
System.out.println(odd1);
System.out.println(even1);
System.out.println("Check digit should be: "+f);
System.out.println("Check digit is: "+str1.charAt(11));
int y = Character.getNumericValue(str1.charAt(11));
if (f == y){
System.out.println("UPC is valid");
}
else{
System.out.println("UPC is not valid");
}
}
private static String validinput(Scanner inScanner){
System.out.print("Enter a UPC (enter a blank line to quit): ");
String str = inScanner.nextLine();
while(str.length() != 12){
if (str.length() == 0){
System.out.println("Goodbye");
break;
}
else{
System.out.println("ERROR! UPC MUST have exactly 12 digits");
System.out.print("Enter a UPC (enter a blank line to quit): ");
str = inScanner.nextLine();
}
}
return str;
}
private static int odd(String input){
int i = 1;
char ch;
int sumOdd = 0;
while (i < 11){
ch = input.charAt(i);
int x = Character.getNumericValue(ch);
sumOdd = x +sumOdd;
i += 2;
}
int Mx3=sumOdd*3;
return Mx3;
}
private static int even(String input){
int i = 0;
char ch;
int sumEven = 0;
while (i < 11){
ch = input.charAt(i);
int x = Character.getNumericValue(ch);
sumEven = x +sumEven;
i += 2;
}
return sumEven;
}

charAt() uses null-based indexes, but the instruction wants you to use 1-based indexes. So, in odd() start with i = 0. And in even() start with i = 1.
Secondly, you use Character.getNumericValue(ch) to get the unicode codepoint value of the character, but the instructions ask you to use the digit value. So, use Integer.parseInt(ch.ToString()) instead.
private static int odd(String input){
int i = 0;
char ch;
int sumOdd = 0;
while (i < 11){
ch = input.charAt(i);
int x = Integer.parseInt(ch.ToString());
sumOdd = x +sumOdd;
i += 2;
}
int Mx3=sumOdd*3;
return Mx3;
}
private static int even(String input){
int i = 1;
char ch;
int sumEven = 0;
while (i < 11){
ch = input.charAt(i);
int x = Integer.parseInt(ch.ToString());
sumEven = x +sumEven;
i += 2;
}
return sumEven;
}
Code not tested

Related

printing first 3 digits of decimal number from user input

The prompt says:
Input a double and print the first three digits after the decimal
point with a space between them.
Sample run:
Please input a decimal number:
67.3424
Answer: 3 4 2
What I have so far
Scanner scan = new Scanner(System.in);
System.out.print("Please input a decimal number: ");
double hit_n = scan.nextDouble();
double hit_4 = hit_n % 10;
hit_n /= 10;
double hit_3 = hit_n % 10;
hit_n /= 10;
double hit_2 = hit_n % 10;
hit_n /= 10;
double hit_1 = hit_n % 10;
System.out.println(hit_1);
System.out.println(hit_2);
System.out.println(hit_3);
System.out.println(hit_4);
The problem with this code is that it keeps printing the decimals added when you input them.
Since, it doesn't say how you do it. One way is to ignore all the characters before '.', print three characters following '.', and ignore the rest.
public class Main
{
public static void main(String[] args) throws java.io.IOException {
System.out.print("Please input a decimal number: ");
char c = 0;
int count = 0;
boolean print = false;
while((c = (char) System.in.read()) != '\n'){
if (c == '.') print = true;
else if (print && count++ < 3){
System.out.print(c);
}
}
}
}
Output:
Please input a decimal number: 5234.25234233
252

Java ISBN checksum generator -- infinite loop?

I need to build this ISBN checksum generator (for both ISBN-10 and ISBN-13) for my CS class using strings, chars, and a bunch of nested loops and conditional statements. Somewhere in this mess, I think something is triggering an infinite loop because when I am prompted for an input, I give the input and press enter and it just goes to a new line and expects me to enter a bunch more data I guess when instead it should be prompting me again to enter another one after each successful entry and otherwise tell me it's incorrect and then still again ask for another input. And when I type in quit it doesn't end the program and display the checksum results like it's supposed to, instead it exhibits the same behavior as other inputs do. If I type in quit the first time without giving the program any numbers it does end the program properly but of course, the values of the output variables are null.
My code thus far:
/******************************************************************************
* Program Name: Lab05A - ISBN
* Program Description: Calculate ISBN-10 AND ISBN-13
* Program Author: xxxxxxxxx
* Date Created: 10/10/2018
* Change# Change Date Programmer Name Description
* ------- ------------ ------------------- ---------------------
******************************************************************************/
package lab05a;
import java.util.Scanner;
public class Lab05A {
public static void main(String[] args) {
// Input for s
Scanner input = new Scanner(System.in); // Create new scanner
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: "); // our ever-lasting prompt
String s = input.next(); // declare string variable "s" and set it equal to next input from user.
String output10 = null; // Declaring string output10
String output13 = null; // Declaring string output13
// main while loop
while (!"QUIT".equals(s)) { //this will run as long as the program does not receive an input of "QUIT", not case sensitive.
char checkDigit;
char checkSum = '0';
if (s.length() == 9) { //if the length of the inputted string is 9 characters...
int sum = 0; // initialize sum variable
for (int i=0; i <= s.length();) {
sum = sum + ((s.charAt(i) - '0') * (i + 1));
}
if (sum % 11 == 10) {
checkDigit = 'X';
}
else {
checkDigit = (char) ('0' + (sum % 11));
}
output10 = output10 + "\n" + s + checkDigit;
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
else if (s.length() == 12) {
int sum = 0;
for (int i=0; i <= s.length();) {
if (i % 2 == 0) {
sum = sum + (s.charAt(i) - '0');
}
else {
sum = sum + (s.charAt(i) - '0') * 3;
}
checkSum = (char) (10 - sum % 10);
if (checkSum == 10) {
checkSum = 0;
}
output13 = "\n" + output13 + checkSum;
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
}
else if (!s.toUpperCase().equals("QUIT")) {
System.out.println(s + " is invalid input.");
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
}
System.out.println("The 10 digit ISBNs are \n" + output10);
System.out.println("The 13 digit ISBNs are \n" + output13);
}
}
Instructions
Flowchart as a separate image since it's kinda small in the instructions doc
Thanks for your help.
Yes, you are missing the incrementor in this for loop
for (int i=0; i <= s.length();) {
change to
for (int i=0; i <= s.length(); i++) {
I am sure that you do not want <=, maybe just <
so
for (int i=0; i < s.length(); i++) {
BTW this is easy to solve if you debug your code - an essential skill --
edit
If you have the below code (and s.length == 12)
for (int i=0; i < s.length(); i++) {
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
Then it will execute 12 times. Fix your loop
UPDATED CODE since I implemented some of the suggestions here:
package lab05a;
import java.util.Scanner;
public class Lab05A {
public static void main(String[] args) {
// Input for s
Scanner input = new Scanner(System.in); // Create new scanner
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: "); // our ever-lasting prompt
String s = input.next(); // declare string variable "s" and set it equal to next input from user.
String output10 = ""; // Declaring string output10
String output13 = ""; // Declaring string output13
// main while loop
while (!"QUIT".equalsIgnoreCase(s)) { //this will run as long as the program does not receive an input of "QUIT", not case sensitive.
char checkDigit;
char checkSum = '0';
if (s.length() == 9) { //if the length of the inputted string is 9 characters...
int sum = 0; // initialize sum variable
for (int i=0; i < s.length(); i++) {
sum = sum + ((s.charAt(i) - '0') * (i + 1));
}
if (sum % 11 == 10) {
checkDigit = 'X';
}
else {
checkDigit = (char) ('0' + (sum % 11));
}
output10 = output10 + "\n" + s + checkDigit;
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
else if (s.length() == 12) {
int sum = 0;
for (int i=0; i < s.length(); i++) {
if (i % 2 == 0) {
sum = sum + (s.charAt(i) - '0');
}
else {
sum = sum + (s.charAt(i) - '0') * 3;
}
checkSum = (char) (10 - sum % 10);
if (checkSum == 10) {
checkSum = 0;
}
output13 = "\n" + output13 + s + checkSum;
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
}
else if (!"QUIT".equalsIgnoreCase(s)) {
System.out.println(s + " is invalid input.");
System.out.println("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");
s = input.next();
}
}
System.out.println("The 10 digit ISBNs are \n" + output10);
System.out.println("The 13 digit ISBNs are \n" + output13);
}
}

Assign of user input number to array in char data type

I'm trying to ask the user to input a three digit number, then have the code assign a new variable to the char of each digit using charAt() and put each digit into an array. So far it allowed me to input a number, but then it stops and doesn't do anything else, so I think it is a problem with this part. How would you do that?
The purpose is so that the computer with generate a three digit number, ask the user to input a number, then analyze the numbers to see how many digits of the guessed number are the same as in the generated number and how many of the correct digits are in the correct place. So if the generated number is 180, and you guess 481, then the digits correct would be 2 and the places correct would be 1.
import java.util.Scanner;
public class Main {
public static void main(String[] args){
char[] array = new char [3];
for (int i = 0; i < array.length; i++){
array[i] = (char)(Math.random() * 9);
}
char[] guess = {0, 0, 0};
System.out.println("I have a three digit number with no repeating digits. Guess the number.");
while (guess != array){
Scanner input = new Scanner(System.in);
char number1 = input.next().charAt(0);
char number2 = input.next().charAt(1);
char number3 = input.next().charAt(2);
guess[0] = number1;
guess[1] = number2;
guess[2] = number3;
int digit = 0;
int place = 0;
for(int n = 0; n < array.length; n++){
for(int d = 0; d < array.length; d++){
if(array[n] == guess[d]){
digit++;
}
}
}
for(int r = 0; r < array.length; r++){
if(array[r] == guess[r]){
place++;
}
}
System.out.println("Correct digits: " + digit);
System.out.println("Correct places: " + place);
}
System.out.println("Congratulations, you got it");
}
}
Scanner input = new Scanner(System.in);
String num = input.next();
char number1 = num.charAt(0);
char number2 = num.charAt(1);
char number3 = num.charAt(2);
To fix the problems you'll run into after this:
array[i] = (char) (Math.random() * 9 + '0');
You need to store the character correctly. Before, you were storing the ascii codes 0 - 9.
while (guess[0] != array[0] || guess[1] != array[1] || guess[2] != array[2]){
You need to compare each value of the array individually.
You need to store the number before sampling the characters.

Create a java application that displays the sum of the digits of a number

I am relatively new to Java and I'm currently learning while, do while and for loops. I want to create an application that displays the sum of the digits of a number using these concepts but I have no idea how. I previously created an application that displayed ONLY THE DIGITS of a number. Here it is.
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
}
I'm trying to think of a possible way to expand on this program, but I have no idea why. Once again, this program is not what I need, what I need is somehow to sum the digits of a number using for or while loops. Thank you!
not much code has to be added for summing the digits :
First solution : using a substract with '0' character
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
sum = sum + (sdigit.charAt(i) - '0');
}
System.out.println("Sum is : "+sum);
Second solution : using Integer.parseInt which converts String to int :
int digit;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a positive integer: ");
digit = input.nextInt();
} while (digit <= 0);
input.close();
String sdigit = digit + "";
int sum=0;
for (int i = 0; i < sdigit.length(); i++){
System.out.println(sdigit.charAt(i));
sum = sum + Integer.parseInt(sdigit.subString(i,i+1));
}
System.out.println("Sum is : "+sum);
int digit;
System.out.println("Enter a positive integer: ");
number= Integer.parseInt(System.console().readLine());
int sum=0;
int currDigit = 0;
while( number / 10 > 0) {
currDigit = number % 10; //fetching last digit
System.out.println(currDigit);
sum = sum + currDigit;
number = number / 10;
}

Java - How to add separated numbers

This is my code:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
String happyNumber = input.nextLine();
int happyNum = Integer.parseInt(happyNumber);
happyNum *= happyNum;
int answer = 0;
for (char ch : Integer.toString(happyNum).toCharArray()) {
int digit = ch - '0';
answer = digit * digit;
System.out.print(answer);
}
For example:
Enter a number:7
The output is:
16
81
Now guys, I want to add 16 and 81. The sum will be 97. I have tried research and all but still, I can't solve this simple problem.
Use a sum to keep track of your total =)
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
String happyNumber = input.nextLine();
int happyNum = Integer.parseInt(happyNumber);
happyNum *= happyNum;
int answer = 0;
int sum = 0; //NEW
for (char ch : Integer.toString(happyNum).toCharArray()) {
int digit = ch - '0';
answer = digit * digit;
sum = sum + answer;//NEW
System.out.print(answer);
}
System.out.print("Sum: " + sum);//NEW
Try and understand the change of code. I added //NEW to each line I added

Categories