if (diceValues == null || diceValues.length() == 0) return 0;
int temp;
int val = 0;
Scanner scanner = new Scanner(diceValues);
while (scanner.hasNext()) {
temp = scanner.useDelimiter(" ").nextInt();
if (temp == 1) val += 100;
if (temp == 5) val += 50;
}
diceValue is a string like this: "1 2 3 4 5", and the scanner always skips the last number. So the int val(value) always smaller than it should be.
I think your code has no problem.I ran it this way and it returned me value 150.
import java.util.Scanner;
public class Prog1
{
public static void main(String[] args){
Prog1 p =new Prog1();
int value = p.mymethod();
System.out.println(value);
}
public int mymethod()
{
String diceValues = "1 2 3 4 5";
if (diceValues == null || diceValues.length() == 0) return 0;
int temp;
int val = 0;
Scanner scanner = new Scanner(diceValues);
while (scanner.hasNext()) {
temp = scanner.useDelimiter(" ").nextInt();
if (temp == 1) val += 100;
if (temp == 5) val += 50;
}
return val;
}
Related
So I had tried this online challenge but got runtime error.Please help.I am new to programming. I have attached the problem statement and my solution.
The Challenge
Using the Java language, have the function KaprekarsConstant(num) take an integer of four digits (with at least two being distinct) and perform the following routine on said number:
Arrange the digits in descending order and in ascending order.
Subtract the smaller number from the bigger number, padding the difference with zeroes if necessary to maintain a four-digit number.
Then repeat step 1 and 2 using the four-digit difference.
Stop when the difference of the two, permuted numbers equals 6174.
Return the number of times that you had to perform steps 1 and 2 before arriving at a difference with the value of 6174.
nb: performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174).
For example: if num is 3524 your program should return 3: (pass 1) 5432 - 2345 = 3087, (pass 2) 8730 - 0378 = 8352, (pass 3) 8532 - 2358 = 6174.
Here is my solution:
import java.util.*;
import java.io.*;
class Main {
public static int KaprekarsConstant(int num) {
int diff = 0, count = 0;
while (diff != 6174) {
String s1 = String.valueOf(num);
int[] ch1 = new int[s1.length()];
for (int i = 0; i < ch1.length; i++) {
ch1[i] = s1.charAt(i);
}
Arrays.sort(ch1);
String s2 = String.valueOf(ch1);
String s3 = "";
for (int j = s2.length() - 1; j >= 0; j++) {
s3 += s2.charAt(j);
}
int a = Integer.parseInt(s2);
int b = Integer.parseInt(s3);
if (a > b) {
diff = a - b;
} else if (b > a) {
diff = b - a;
} else {
System.out.println("goal cant be reached");
break;
}
count++;
num = diff;
}
return num;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(KaprekarsConstant(s.nextLine()));
}
}
Try this code:
/**
* KaprekarConstant
*/
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class KaprekarConstant {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int inputNumber;
char[] digits;
System.out.print("Enter four digit number: ");
try {
inputNumber = scan.nextInt();
if (checkLength(inputNumber))
throw new Exception();
Kaprekar(inputNumber);
} catch (InputMismatchException e) {
System.out.println("Not a number");
} catch (Exception ex) {
System.out.println("Number must have four digits");
} finally {
scan.close();
}
}
public static void Kaprekar(int target) {
int maximum = 0, minimum = 0, result = 0;
Integer[] digits = new Integer[4];
if (target == 6174)
return;
int i = 0;
while (i < 4) {
digits[i] = target % 10;
target /= 10;
i++;
}
Arrays.sort(digits);
minimum = toInt(digits);
Arrays.sort(digits, Collections.reverseOrder());
maximum = toInt(digits);
result = maximum - minimum;
System.out.println(String.format("%d - %d = %d", maximum, minimum, result));
Kaprekar(result);
}
public static boolean checkLength(int number) {
if (String.valueOf(number).length() < 5 && String.valueOf(number).length() > 3)
return false;
return true;
}
public static int toInt(Integer[] digits) {
int number = 0;
for (int digit : digits) {
number *= 10;
number += digit;
}
return number;
}
}
I think this is best method to find the karpekar constant.
There were some basic syntax & logical errors in your code. I have made appropriate changes in it. See if you understand it.
import java.util.*;
import java.io.*;
public class Main {
public static int KaprekarsConstant(int num) {
int diff = 0, count = 0;
while (diff != 6174) {
String s1 = String.valueOf(num);
char[] ch1 = new char[s1.length()];
for (int i = 0; i < ch1.length; i++) {
ch1[i] = s1.charAt(i);
}
Arrays.sort(ch1);
String s2 = new String(ch1);
String s3 = "";
for (int j = s2.length() - 1; j >= 0; j--) {
s3 += s2.charAt(j);
}
int a = Integer.parseInt(s2);
int b = Integer.parseInt(s3);
if (a > b) {
diff = a - b;
} else if (b > a) {
diff = b - a;
} else {
System.out.println("goal cant be reached");
break;
}
count++;
num = diff;
}
return count;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(KaprekarsConstant(s.nextInt()));
}
}
This solution has less lines of code:
import static java.lang.System.out;
import java.util.Arrays;
/**
* #see https://en.wikipedia.org/wiki/6174_%28number%29
*/
public class KaprekarConstant {
public static void main(String[] args) {
assert(count(3524) == 3);
assert(count(3087) == 2);
assert(count(8352) == 1);
assert(count(6174) == 1);
out.println("All passed.");
}
public static int count(int start) {
int ct = 0;
do {
start = calc(start);
ct++;
} while (start != 6174);
return ct;
}
static int calc(int n) {
String n1s = String.format("%04d", n);
char[] chs = n1s.toCharArray();
Arrays.sort(chs);
n1s = new String(chs);
String n2s = new StringBuilder(new String(n1s)).reverse().toString();
int n1 = Integer.parseInt(n1s);
int n2 = Integer.parseInt(n2s);
return Math.max(n1, n2) - Math.min(n1, n2);
}
}
Here is a Python implementation:
def kc_count(start_int):
def kc_calc(n):
ns1 = ''.join(sorted("%04d" % n))
ns2 = ns1[::-1]
return max(int(ns1), int(ns2)) - min(int(ns1), int(ns2))
ct = 0;
while True:
start_int = kc_calc(start_int)
ct += 1
if start_int == 6174:
break
return ct
assert(kc_count(3524) == 3)
assert(kc_count(3087) == 2)
assert(kc_count(8352) == 1)
assert(kc_count(6174) == 1)
import java.util.*;
public class Main_5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
for(int i = 0; i < m; i++){
String password = sc.nextLine();
System.out.println(got(password));
}
}
public static String got(String password) {
HashMap<Character, Integer> checkpass = new HashMap<>();
Character ch = null;
Integer val = 0;
int odd = 0, even = 0;
for (int i = 0; i < password.length(); i++) {
ch = password.charAt(i);
if (checkpass.containsKey(ch) == false) {
checkpass.put(ch, 1);
} else {
val = (Integer) checkpass.get(ch);
checkpass.put(ch, val + 1);
}
}
Set<Character> hashval = checkpass.keySet();
for (Character key : hashval) {
val = (Integer) checkpass.get(key);
if (val == password.length())
return "YES";
else if (val % 2 == 1)
odd++;
else
even++;
}
if (odd == 1 || odd == 0)
return "YES";
else
return "NO";
}
}
PLEASE TEST THIS OUT FOR YOURSELF
As you can see, there is integer m in the main method. When I hit run, it makes integer m as if it were part of the got method. This is a code to find if x Strings can be a permutation palindrome.
This should what the console should look like:
*Input*:
3
ccaabcbb
azzza
bbbbccccdddddddd
*Output*:
NO
YES
YES
Use sc.next() instead sc.nextLine() as its giving the empty line created by your first enter.
import java.util.*;
public class Main_5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
for(int i = 0; i < m; i++){
String password = sc.next();
System.out.println(got(password));
}
}
public static String got(String password) {
HashMap<Character, Integer> checkpass = new HashMap<>();
Character ch = null;
Integer val = 0;
int odd = 0, even = 0;
for (int i = 0; i < password.length(); i++) {
ch = password.charAt(i);
if (checkpass.containsKey(ch) == false) {
checkpass.put(ch, 1);
} else {
val = (Integer) checkpass.get(ch);
checkpass.put(ch, val + 1);
}
}
Set<Character> hashval = checkpass.keySet();
for (Character key : hashval) {
val = (Integer) checkpass.get(key);
if (val == password.length())
return "YES";
else if (val % 2 == 1)
odd++;
else
even++;
}
if (odd == 1 || odd == 0)
return "YES";
else
return "NO";
}
}
I my be wrong, but rewritting getting m to this:
int m = Integer.parseInt(sc.nextLine());
should do the trick. There is problem using scanner's nextInt() and reading new line from standard input.
Just like older mobile phones' keypads work. I should input a string of numbers and the program should print out a text based on those numbers.
e.g: Input: 4448 9666777557777 should output to: ITWORKS.
Here's my code so far but it's not printing out anything. Could you please tell me what's wrong with it and what could've I done better?
Scanner sc = new Scanner(System.in);
String[] letters = {
"0",
"1",
"ABC",
"DEF",
"GHI",
"JKL",
"MNO",
"PQRS",
"TUV",
"WXYZ"
};
System.out.println("Write something.");
String numbers = sc.nextLine();
char[] toChar = numbers.toCharArray();
int count = 0;
for (int index = 0; index < toChar.length; index++) {
if (toChar[index] >= '2' && toChar[index] <= '9') {
if (index > 0 && toChar[index] == toChar[index - 1]) {
count++;
}
else if (count > 0) {
System.out.print(letters[toChar[index - 1] - '0'].charAt(count - 1));
count = 0;
}
}
}
How about this?
import java.util.Scanner;
public class Test {
private static final String[] letters = {
"0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
};
private static char getChar(int digit, int count) {
while (count > letters[digit].length()) {
count -= letters[digit].length();
}
return letters[digit].charAt(count - 1);
}
private static String getString(String input) {
int lastDigit = 0, count = 1;
String result = "";
for (int i = 0; i < input.length(); i++) {
int currentDigit = input.charAt(i) - '0';
if (currentDigit >= 2 && currentDigit <= 9) {
if (lastDigit == 0) {
lastDigit = currentDigit;
} else if (currentDigit == lastDigit) {
count++;
} else {
result += getChar(lastDigit, count);
lastDigit = currentDigit;
count = 1;
}
}
}
return result + getChar(lastDigit, count);
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Write something");
System.out.println(getString(scanner.nextLine()));
}
}
}
I enhanced the problem decomposition. It works for all examples OP has shown so far.
If I understand your intention correctly, count should increment only if current digit is the same as previous:
for (int pos = 1, char c = toChar[0], int count = 1; pos <= toChar.length; pos++, count = 1) {
int n = letters[c - '0'].length;
while (pos < toChar.length && c == toChar[pos] && count < n) {
pos++;
count++;
}
System.out.println(letters[c - '0'].charAt(count - 1));
if (pos < toChar.length - 1) {
c = toChar[++pos];
}
}
This code will help you!
Check this one
public class Denene {
public static String getChar(String cha)
{
String [] chars= {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
String[] strSplit = cha.split(" "); //7777 88 7777 2 66 8
int len=strSplit.length;
char r;
char []ar =new char[len];
for(int i=0;i<len;i++){
String str=strSplit[i];
ar[i]= chars[Integer.parseInt(String.valueOf(str.charAt(0)))].charAt(str.length()-1);
}
return new String(ar);
}
public static void main(String[] args) {
System.out.println("Enter any number .....");
System.out.println(getChar(new Scanner(System.in).nextLine())); //Output : susant
}
}
I'm developing an application that takes 4 lines of input. The first line contains N, which is the number of iterations, and the following N lines contain the data.
Here is my program:
import java.util.Scanner;
public class Principal {
static String binary;
static int count = 0;
public static void main (String args [])
{
Scanner s = new Scanner(System.in);
int N = Integer.parseInt(s.next());
//System.out.println(N);
int X = 0;
int cpt=1, test = 1;
boolean negatif = false;
boolean test1 = false;
for (int i =0;i <N; i++)
{
X = Integer.parseInt(s.next());
//System.out.println(s.next());
while (cpt < 1337)
{
if ((cpt % 7 == 0)||(Integer.toString(cpt)).contains("7"))
{
negatif = !negatif;
}
if (negatif == false)
{
if (test == 1337)
test = 1;
else
test++;
}
else
{
if (test == 1)
test = 1337;
else
test--;
}
cpt++;
if (cpt == X)
{
test1 = true;
break;
}
}
if (test1)
System.out.println(test);
test = 1;
cpt=1;
negatif = false;
test1 = false;
}
}
}
And the input is:
3
10
100
1000
And the output is supposed to be:
4
2
1311
The problem is that I cannot reach the last line which contains 1000.
Please help.
import java.util.Scanner;
public class PD {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter your number: " );
int number = input.nextInt();
for (int count = 2; count < number; count++) {
String blank = "";
String Snumber = count + blank;
if (isPalindromic(count) && isPrime(count) &&
isPalindromic((int)(Snumber.length())) &&
isPrime((int)(Snumber.length()))){
System.out.println( count + "is double palidromic prime");
}
else
continue;
}
}
// method to find palindromic
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
for (int i = 0, q = 1; i <= (convert.length()/2 - 1); i++, q++) {
if (convert.substring(i,q) == convert.substring(convert.length() - q, convert.length() - i)){
return true;
}
}
return false;
}
// method to find prime
public static boolean isPrime(int count ) {
for (int divisor = 2; divisor <= count/2; divisor++) {
if (count % divisor == 0) {
return false;
}
}
return true;
}
}
Currently the thing compiles and ask for input, but it always results in nothing.
Does someone see something wrong with my program that is obvious wrong.
Overall, the program receives input and has to look through values 2 until it hits the value the user wants and print the ones that follow the if statement.
Your isPalindromic method is not functioning properly. It is not returning true for palindromic numbers. Change it to this:
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
int n = convert.length();
for (int i = 0; i < (n / 2 + 1); i++) {
if (convert.charAt(i) != convert.charAt(n - i - 1)) {
return false;
}
}
return true;
}