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.
Related
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;
// }
}
}
}
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.
I have to make an array whose 10 numbers are chosen by the user through a scanner. The program orders the 10 numbers in ascending order, then prints out the new list. Then It asks the user to enter any number and then uses a binary search to see if the number is in the list of 10 numbers.
Here is what I have so far:
import java.util.Scanner;
public class lab11 {
public static void main(String[] args){
double[] numbers = new double[10];
System.out.println("Please enter 10 double values:");
for (int i=0;i<10;i++){
numbers[i] = inputArray();
}
System.out.println("sorting");
print(selectionSort(numbers));
System.out.println("Please enter a search key:");
}
public static double inputArray(){
Scanner input = new Scanner(System.in);
System.out.print(">");
double d = input.nextInt();
return d;
}
public static double[] selectionSort(double[] list){
double temp;
for(int i=0; i < (list.length-1); i++){
for(int j = i+1; j < list.length; j++){
if(list[j] < list[i]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
public static void print(double[] arr){
for(double d:arr){
System.out.println("list["+j+"]"+" = "+d);
}
}
public static int binarySearch(double[]list, double key){
int low=0,high=list.length -1;
key =input.nextInt();
while(high>=low){
int mid=(low+high)/2;
if(key<list[mid])
high=mid-1;
else if(key==list[mid]) return mid;
else low=mid+1;
}
return-1;
}
}
I need help with 2 things.
(1) is under the Print method. I want the program to print out like "list[i] = d" The d a number that the user puts in and it works fine, but the i doesn't. I want it to be the array number which is 0 through 9.
(2) I need help with invoking the binary search so I can have an output for the search.
Just for the right input, you can write a do...while loop, which loops till the input is valid:
for (int i = 0; i < 10; i++) {
double number;
Scanner input = new Scanner(System.in);
do {
System.out.print(">");
number = input.nextDouble();
} while (number < 0 || number > 10);
}
}
For the output you seem to want use
// [...] perform the sorting [...]
// enter the search key
System.out.println("Please enter a search key:");
final int position = Arrays.binarySearch(numbers, input.nextDouble());
if (position < 0) {
System.out.println("key is not in the list");
} else {
System.out.println("key is at position " + position);
}
I would write like this
public static void main(String[] args) {
// initialize
double[] numbers = new double[10];
Scanner input = new Scanner(System.in);
// insert variables into array
inputArray(numbers, input);
// start sorting
System.out.println("sorting");
selectionSort(numbers);
// print the sorted array
print(numbers);
// binary search
binarySearch(numbers, input);
// close scanner
input.close();
}
public static void inputArray(double[] numbers, Scanner input) {
System.out.println("Please enter 10 double values:");
for (int i = 0; i < 10; i++) {
System.out.print(">");
numbers[i] = input.nextDouble();
}
}
public static void print(double[] numbers) {
for (int i = 0; i < numbers.length; i++) {
System.out.println("list[" + i + "]" + " = " + numbers[i]);
}
}
public static double[] selectionSort(double[] list) {
double temp;
for (int i = 0; i < (list.length - 1); i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[j] < list[i]) {
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
public static void binarySearch(double[] numbers, Scanner input) {
System.out.println("Please enter a search key:");
double key = input.nextDouble();
int index = Arrays.binarySearch(numbers, key);
if (index < 0) {
System.out.println(key + " is not in the list");
} else {
System.out.println(key + " is in the list, index = " + index);
}
}
I am having a hard time with this code. The code is finished but the output is wrong.
My code prints Enter ten numbers: 1 2 3 5 6 6 8 7 4 1
It should print
The distinct numbers are:
1 2 3 5 6 8 7 4
but it doesn't. It prints:
10 10 10 10 10 7
How can I fix it?
Here is my code:
import java.util.*;
public class homework1 {
public static void main(String[] args){
// input from user
Scanner input = new Scanner(System.in);
int [] numbers = new int[10];
boolean[] distinct = new boolean[10];
System.out.println("Enter ten numbers");
for (int i=0; i<numbers.length; i++){
System.out.println("Number " + (i + 1) +": ");
numbers [i] = input.nextInt();
distinct[i] = true;
for(int j = 0;j<10; j++){
if(numbers[i] == numbers[j] && i != j) {
distinct[i] = false;
}
}
}
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=distinct.length;
count++;
}
}
System.out.println("The number of distinct number is: "+numbers[count]);
System.out.println("The distinct numbers are: ");
for(int i= 0; i < 10; i++) {
if(distinct[i]) {
System.out.print(numbers[i] + " ");
}
}
System.out.println();
}
}
This line:
numbers[count]=distinct.length;
Is setting your outputs to be the length of the array (Which in this case is hard coded to 10. Try:
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=numbers[j];
count++;
}
}
Which will set your output to be the distinct number.
Plug: Check out Code Review
This will solve your problem.
If you use HashMap, you will have less code.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> distinctNumbers = new HashMap<Integer, String>();
// input from user
Scanner input = new Scanner(System.in);
System.out.println("Enter ten numbers");
for (int i = 0; i < 10; i++) {
System.out.println("Number " + (i + 1) + ": ");
Integer numberEntered = input.nextInt();
distinctNumbers.put(numberEntered, null);
}
System.out.println("The number of distinct number is: " + distinctNumbers.size());
System.out.println("The distinct numbers are: ");
Set<Integer> keys = distinctNumbers.keySet();
for (Iterator<Integer> iterator = keys.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.print(" "+ integer);
}
}
}
Remove line numbers[count] = distinct.length; This make your output are all 10
Then, I change your code a little to make it run right:
...
int count = 0;
for (int j = 0; j < 10; j++) {
if (distinct[j]) {
//numbers[count] = distinct.length; //remove it, it nonsense
count++;
}
}
// distinct number should be count, not number[count]
System.out.println("The number of distinct number is: " + count);
....
public static void main(String[] args) {
int arr[] = {1,3,5,4,7,3,4,7};
Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; i++) {
if(frequency.containsKey(arr[i])){
int value = frequency.get(arr[i]);
frequency.put(arr[i], value + 1);
}
else {
frequency.put(arr[i], 1);
}
}
for(Map.Entry<Integer, Integer> entry : frequency.entrySet()) {
System.out.println(entry.getKey());
}
}
package Chapter7;
import java.util.Scanner;
public class Exercise7_5 {
public static void main(String[] args) {
// Print distinct numbers
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers: ");
for (int i = 0, j = 0; i < 10; i++) {
if (storeDistinctNumbers(j,input.nextInt(), numbers))
j++;
}
for (int i = 0; numbers[i] != 0 ; i++)
System.out.print(numbers[i] + " ");
}
public static boolean storeDistinctNumbers(int j, int num, int[] numbers) {
for (int e: numbers) {
if (e == num)
return false;
}
numbers[j] = num;
return true;
}
}
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);
}
}