In this below program, I'm trying to check whether the number is ISBN or not. I'm giving input with spaces (eg: 0 3 0 6 4 0 6 1 5 2) because array only accepts it like this. I don't know how to give input without space to read. Can anyone help me how to read the number eg: 0306406152 and also it will read 10 numbers only like if(i==10) else it says it's not ISBN number to give output.
public class ISBN {
int digits[];
int dig = 11;
int sum;
int isbn1;
public void CheckISBN() {
for (int digit : digits) {
// System.out.println(digit);
if (dig >= 1) {
dig--;
digit = digit * dig;
// System.out.println(dig);
}
sum = sum + digit;
isbn1 = sum % 11;
}
if (isbn1 == 0) {
System.out.println(isbn1);
System.out.println("it's valid ISBN number");
} else {
System.out.println("sorry it's not valid ISBN");
}
}
public static void main(String[] args) {
ISBN aa = new ISBN();
aa.digits = new int[10];
Scanner scan = new Scanner(System.in);
int i = 0;
while (scan.hasNextInt()) {
aa.digits[i] = scan.nextInt();
i++;
if (i == 10) // aa.CheckISBN();
{
break;
}
for (int j = 0; j < aa.digits.length; j++) {
// System.out.print(aa.digits[j]);
}
//System.out.println();
}
aa.CheckISBN();
}
}
SAMPLE OUTPUT: 0 3 0 6 4 0 6 1 5 2
it's valid ISBN number
When the number is given without spaces,
import java.io.*;
import java.util.*;
public class ISBN {
int digits[];
int dig = 11;
int sum;
int isbn1;
public void CheckISBN() {
if(this.digits.length != 10)
{
System.out.println("sorry it's not valid ISBN");
return;
}
for (int digit : digits) {
// System.out.println(digit);
if (dig >= 1) {
dig--;
digit = digit * dig;
// System.out.println(dig);
}
sum = sum + digit;
isbn1 = sum % 11;
}
if (isbn1 == 0) {
//System.out.println(isbn1);
System.out.println("it's valid ISBN number");
} else {
System.out.println("sorry it's not valid ISBN");
}
}
public static void main(String[] args) {
ISBN aa = new ISBN();
Scanner scan = new Scanner(System.in);
String num = scan.next(); //take input as a string
int[] digits = new int[num.length()];
for(int i = 0; i<digits.length; i++)
digits[i] = num.charAt(i) - '0';
aa.digits = digits;
aa.CheckISBN();
}
}
Or scan it as int to get number format validation for free:
public class ISBN {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
if (scan.hasNextInt()) {
checkISBN(scan.nextInt());
}
}
public static void checkISBN(int isbn) {
int sum = sum(digits(isbn));
int isbn1 = sum % 11;
if (isbn1 == 0) {
System.out.println(isbn1);
System.out.println("it's valid ISBN number");
} else {
System.out.println("sorry it's not valid ISBN");
}
}
private static int sum(int[] digits) {
return IntStream.rangeClosed(1, digits.length)
.map(i -> i * digits[digits.length - i])
.sum();
}
private static int[] digits(int isbn) {
return Integer.toString(isbn)
.chars()
.map(c -> c - '0')
.toArray();
}
}
N.B.: It works for ISBN both with or without leading zeros.
Related
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.
Need to write a program to calculate sum of all digits and then give results when the total sum vaue ends with 5 or 8.Please help correct this code!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int customerID = in.nextInt();
while(customerID > 0)
{
int Reminder = customerID % 10;
int sum = sum+ Reminder;
customerID = customerID / 10;
}
if(sum%5||sum%8)
{
System.out.println("Lucky Customer");
}else
{
System.out.println("Unlucky Customer");
}
if(sum <0)
{
System.out.println("Invalid Input");
}
}
}
instead of doing
if(sum%5||sum%8)
{
System.out.println("Lucky Customer");
}
where sum%8 will be true for the value 16 so you can try this
int rem=sum%10;
if(rem==5||rem==8)
{
System.out.println("Lucky Customer");
}
Apart from the fact that this code doesn't produce the error you've mentioned, there are other issues with the code. I've tried to address them instead.
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int customerID = in.nextInt();
int sum = 0;
// sum needs to be initialized outside the while loop
// or else you wouldn't be able to use it outside it
while(customerID > 0) {
int Reminder = customerID % 10;
sum = sum+ Reminder;
customerID = customerID / 10;
}
if(sum%5 == 0 || sum%8 == 0) {
//You cannot use int as a condition in if
System.out.println("Lucky Customer");
} else {
System.out.println("Unlucky Customer");
}
if(sum <0) {
System.out.println("Invalid Input");
}
}
This code throws this exception only if your input would contain a dot (e.g.: "3.0"). So either pass the int value (e.g.: "3") or use scanner.nextDouble() and then convert it to int.
Also look into Yash's answer, because your code has other problems too.
+never write variable names with capital letter ("Reminder")!!!!
Please correct your code to remove some compilation errors...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int customerID = in.nextInt();
int sum = 0;
while(customerID > 0) {
int Reminder = customerID % 10;
sum = sum + Reminder;
customerID = customerID / 10;
}
if(sum % 5 == 0 || sum % 8 == 0) {
System.out.println("Lucky Customer");
} else {
System.out.println("Unlucky Customer");
}
if(sum <0) {
System.out.println("Invalid Input");
}
}
}
I have created a program using Java that generates emirps by user input, but I need help on stopping the user when entering zero or a negative integer. I have tried many things but when I run the program with zero or a negative number it will go crazy and give me infinite amount of numbers. I would appreciate it if someone could help me on this.
Here is what I got so far...
import java.util.Scanner;
public class GenerateEmirps {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.print("Enter number of desired emirps: ");
int emrips = scanner.nextInt();
int count = 1;
for( int i = 2; ; i++){
if ((isPrime(i)) && (isPrime(reverseIt(i))) && (!isPalindrome(i))) {
System.out.print(i + " ");
if (count % 10 == 0) {
System.out.println();
}
if (count == emrips){
break;
}
count++;
}
}
}
public static boolean isPrime(int num){
for (int i = 2; i <=num / 2; i++){
if (num % i == 0) {
return false;
}
}
return true;
}
public static int reverseIt(int num){
int result = 0;
while (num != 0) {
int lastDigit = num % 10;
result = result * 10 + lastDigit;
num /= 10;
}
return result;
}
public static boolean isPalindrome(int num){
return num == reverseIt(num);
}
}
Solution:
You just need to test the input before you process it.
int emrips = scanner.nextInt();
if (emrips <= 0) { System.exit(0); }
I am trying to write a program to find the prime numbers from n to m, but I do not know what I am doing wrong.
For example, if I enter in 2 for n and 9 for m, I just get back
2
when the correct output should be
2
3
5
7
Here's my code:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
PrintStream output = System.out;
output.print("Enter a number to test: ");
int n = input.nextInt();
int m = input.nextInt();
boolean isPrime = true;
int i = 2;
while (n > 0 && n < m)
{
isPrime &= n % i != 0;
if (isPrime)
{
output.println(n);
}
n++;
}
}
I have implemented it my way. Hope this helps.
import java.util.Scanner;
class PrimeNumbers
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
System.out.println("Enter the value of m:");
int m = scanner.nextInt();
for (i = n; i <= m; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from m to n are :");
System.out.println(primeNumbers);
}
}
Basically I need to write a program that takes user input up to and including 2^31 -1 in the form of an integer and returns the amount of odd, even, and zero numbers in the int. For example,
Input: 100
Output: 1 Odd, 0 Even, 2 Zeros // 1(Odd)0(Zero)0(Zero)
or
Input: 2034
Output: 1 Odd, 2 Even, 1 Zero // 2(Even)0(Zero)3(Odd)4(Even)
I'm pretty sure I'm over thinking it but I can't slow my brain down. Can anyone help?
This is the third iteration of the code, the first two were attempted with for loops.
import java.util.Scanner;
public class oddEvenZero
{
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int value;
int evenCount = 0, oddCount = 0, zeroCount = 0;
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value > 0) {
value = value % 10;
if (value==0)
{
zeroCount++;
}
else if (value%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
System.out.println();
System.out.printf("Even: %d Odd: %d Zero: %d", evenCount, oddCount, zeroCount);
}
}
Sorry, the code formatted weirdly in the textbox.
value = value % 10;
Probably the end-all-be-all of your problems.
If value is 2034, then value % 10 returns 4... and then assigns that value to value, you go through your if else block, then do 4/10 get 0, and exit the while loop without addressing the other 3 digits.
I suggest something more like this:
while (value > 0) {
if ((value%10)==0) {
zeroCount++;
}
else if (value%2==0) { //As per comment below...
evenCount++;
}
else {
oddCount++;
}
value /= 10;
}
Or, int thisDigit = value % 10, then replace value in your current if else block with thisDigit.
value = value % 10;
This statement will override your original value with a reminder i.e value % 10.
If value = 2034 and value % 10 = 4, then value = 4 which isn't what you want.
Instead use a temporary variable
int lastDigit = value % 10;
Then your code becomes;
while (value > 0) {
int lastDigit = value % 10;
if (lastDigit==0)
{
zeroCount++;
}
else if (lastDigit%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
import java.util.Scanner;
public class oddEvenZero
{
public int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null)
{
int k= sarray.length-1;
int intarray[] = new int[k];
for (int i = 1; i < sarray.length; i++) {
intarray[i-1] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String value;
System.out.print("Enter an integer: ");
value = scan.next();
String words[] = value.split("");
oddEvenZero obj = new oddEvenZero();
try{
int intarray[]= obj.convertStringArraytoIntArray(words);
int even_number =0;
int odd_number =0;
int zero_number =0;
for (int h: intarray)
{
if(h==0)
{
zero_number++;
}
else if(h%2==0)
{
even_number++;
}
else{
odd_number++;
}
}
System.out.println("even numbers are"+ even_number);
System.out.println("odd numbers are"+odd_number);
System.out.println("Zero numbers are"+zero_number);
}
catch(Exception ex)
{
System.out.println("Please enter number");
}
}
}
If some of you are still unable to figure this code out, I found this while searching around for a bit, and works just fine:
import java.util.*;
public class Java_1
{
public static void main (String[] args)
{
String string;
int zero = 0, odd = 0, even = 0, length, left = 0;
Scanner scan = new Scanner(System.in);
System.out.print ("Enter any positive number: ");
string = scan.next();
length = string.length();
while (left < length)
{
string.charAt(left);
if (string.charAt(left) == 0)
zero++;
else if (string.charAt(left) % 2 == 0)
even++;
else
odd++;
left++;
}
System.out.println ("There are: "+ zero + " zeros.");
System.out.println ("There are: "+ even + " even numbers.");
System.out.println ("There are: "+ odd + " odd numbers.");
}
}