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;
}
Related
Hey guys I have been learning coding recently and got an assignment of finding the mean, median and mode of a number of integers in an integer array. The issue that I am facing is that my median and mode displays -1 and I'm not too sure how to fix it, my "if user inputs no, print an error statement" is also not working and I would be very grateful if someone could help me out.
This is my code:
package com.company;
import java.io.File;
import java.io.FileNotFoundException;
import static com.company.ProjectConstants.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] a = new int[MAXDATA];
int counter = 0;
boolean fileDone = false;
boolean inputOk;
String userInput;
String theDataFile;
Scanner s = new Scanner(System.in);
genProgInfo();
userInput = s.nextLine();
userInput = userInput.toLowerCase();
while (!userInput.equals("yes") && (!userInput.equals("no"))) {
System.out.println("ERROR: Please input either yes or no: ");
userInput = s.nextLine();
userInput = userInput.toLowerCase();
}
inputOk = userInput.equals("yes");
initDataStorage(a);
//do {
try {
// create file & scanner objects
System.out.println("enter one of the file names:\nData10File.txt\nData30file.txt\nData35file.txt");
theDataFile = s.next();
theDataFile = theDataFile.toLowerCase();
//fName = userInput;
File f = new File(theDataFile);
Scanner sc = new Scanner(f);
// store file data in array, a
for (int i = 0; i < MAXDATA; i++) {
if (sc.hasNext()) {
a[i] = sc.nextInt();
} else {
fileDone = true;
sc.close();
break;
}
}
// print error message if file data exceeds the range of array
if (!fileDone) {
System.out.println("\n\tCAUTION: file has additional data, consider making array larger.");
}
} catch (FileNotFoundException e) {
System.out.println(e);
e.printStackTrace();
}
//} while (inputOk);
s.close();
for (int i=0; i<MAXDATA; i++) {
if (a[i] != -1) {
counter = a[i];
}
}
System.out.println("counter: "+ counter);
displayResults(calcMean(a), calcMedian(a), calcMode(a));
}
public static void initDataStorage(int[] data) {
for (int i = 0; i < MAXDATA; i++) {
data[i] = INVALID;
}
}
public static double calcMean(int[] data) {
int counter = 0;
int mean;
int sum = 0;
for (int i = 0; i < MAXDATA; i++) {
if (data[i] != -1) {
sum += data[i];
counter++;
}
}
mean = sum / counter;
return mean;
}
public static double calcMedian(int[] data) {
int middle = data.length / 2;
if (data.length % 2 == 1) {
return data[middle];
} else {
return (data[middle -1] + data[middle]) / 2.0;
}
}
public static int calcMode(int[] data) {
int mode = 0, maxCount = 0;
for (int i = 0; i < data.length; ++i) {
int count = 0;
for (int j = 0; j < data.length; ++j) {
if (data[j] == data[i]) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
mode = data[i];
}
}
return mode;
}
public static void genProgInfo() {
System.out.println("This program will calculate the mean, median, and mode of a number of integers stored in the array");
System.out.println("Would you like to continue?");
}
public static void displayResults(double mean, double median, int mode) {
System.out.println("mean: " + mean);
System.out.println("median: " + median);
System.out.println("mode: " + mode);
}
}
I'm assuming the value of INVALID is -1 based on the other code I see and your description of what it outputs. Your array is of length MAXDATA and is initially filled with value INVALID in all elements. You then fill it with n values where n may be less than MAXDATA, and in that (probably common) case, many or even most of the values in the array are the INVALID value.
Your calcMean function is correctly skipping over the -1 (INVALID?) values and not including them in the calculation. Note however that the valid values are all at the beginning of the array and once you find an invalid value, you could break out of the loop in calcMean.
But the calcMedian and calcMode functions are not accounting for the invalid values. If n is significantly less than MAXDATA, then -1 probably really is the mode. Your calcMedian function has an additional problem as well, in that the (valid) data needs to be sorted in order for the "middle" or median value to be in the middle of the array.
Bonus question for your assignment: What if -1 occurs in the input file?
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)
I am trying to do a summation puzzle, the questions asks to use summation puzzles by enumerating and testing all possible configurations and then it says use it to solve the examples given. The examples given were
pot + pan = bib
dog+cat= pig
boy + girl = baby
I keep getting an error saying left hand side of assignment must be a variable
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
cannot convert from int to bool.
if (exists = 0)
Also in my code where I try to display the output it doesn't run.
import java.util.Scanner;
public class Recursion
{
// Example program
public static String stringOne = new String(new char[10]);
public static String stringTwo = new String(new char[10]);
public static String stringThree = new String(new char[11]);
public static String charSet = new String(new char[11]);
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int loop;
int subloop;
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < stringTwo.length(); subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the numeber
numberTwo = (numberTwo * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[subloop];
}
}
}
if (numberOne + numberTwo == numberThree)
{
//display the output
System.out.print(" Summation Puzzle solved. ");
System.out.print("\n");
System.out.print(stringOne);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("\n");
System.out.print(stringTwo);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("\n");
System.out.print(stringThree);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("\n");
//loop to show the result
for (loop = 0; loop < maxCharCount; loop++)
{
System.out.print(charSet.charAt(loop));
System.out.print("<==>");
System.out.print(numberSet[loop]);
System.out.print("\n");
}
System.exit(0);
}
}
public static void generateCombinations(int indexCounter, int[] availableSet)
{
int loop;
if (indexCounter != 0)
{
for (loop = 0; loop < 10; loop++)
{
numberSet[indexCounter] = loop;
if (availableSet[loop] == 1)
{
availableSet[loop] = 0;
generateCombinations(indexCounter + 1, availableSet);
availableSet[loop] = 1;
}
}
}
if (indexCounter == maxCharCount)
{
checkForEquality();
}
}
public static void createCharSet()
{
int loop;
int setIndex;
int exists;
int subloop;
setIndex = 0;
for (loop = 0; loop < stringOne.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
}
}
for (loop = 0; loop < stringTwo.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringTwo.charAt(loop));
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringThree.charAt(loop));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
generateCombinations(0, avaliableSet);
}
}
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter the first String :");
stringOne = scan.next();
System.out.print(" Enter the second String :");
stringTwo = scan.next();
System.out.print(" Enter the thirsd String :");
stringThree = scan.next();
createCharSet();
System.out.print(" The character set formed from the given string = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
}
}
A lot of your problems are stemming from the syntax errors in the code you've written. For example:
line 74: if (stringThree.charAt(loop) == charSet.charAt(subloop) != null)
charSet.charAt(subloop) != null is an invalid comparison since the != operator cannot be used for booleans when comparing to null. If you're trying to determine if the characters return from .charAt(var) exist, use parentheses to make independent comparisons of each object.charAt(var) to null.
line 183: charSet = tangible.StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
tangible is ironically not tangible, as the variable does not exist locally or has not been defined globally.
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
charSet.charAt(setIndex++) is a method that returns a character. This does not mean you can set the character at the specified index like it's a variable.
line 227: if (exists = 0)
You must use == when conducting comparisons in a conditional.
line 269: Scanner scan = new Scanner(System.in);
The Scanner class was not imported and thus cannot be used.
line 283: charSet.charAt(maxCharCount) = '\0';
Again, you can't use .charAt(var) to set the character at that index like it's a variable.
All of these problems can be self-determined by using a proper IDE, such as Eclipse.
Edit: Try to spend a little more time with pencil and paper working out the logic of your program before writing the code to represent your algorithm. This way you have focus and can write more comprehensive, commented, cleaner code. Here is a bit of a guide to help condense your existing project.
My getCount() method should be returning 2 in this case but it is returning 7. I think the reason why it's counting incorrectly is because it's looping through the for 7 times because that's the length of the string. However, I simply just want to scan the string for the pattern and increment patternCount by 1 each time the pattern occurs in the string I'm scanning. Here's my code:
package a2;
public class DNAStrandAdept {
private String strand;
private String pattern;
private String passedStrand;
private int ACount;
private int CCount;
private int GCount;
private int TCount;
private int patternCount = 0;
public static void main(String[] args) {
DNAStrandAdept test = new DNAStrandAdept("AGGTTGG");
System.out.println("A count: " + test.getACount());
System.out.println("C count: " + test.getCCount());
System.out.println("G count: " + test.getGCount());
System.out.println("T count: " + test.getTCount());
System.out.println("Strand: " + test.getStrandString());
System.out.println("Strand length: " + test.getLength());
System.out.println("Pattern Count: " + test.getCount("GG"));
}
public DNAStrandAdept(String strand) {
passedStrand = strand;
if (passedStrand.contains("a") || passedStrand.contains("c")
|| passedStrand.contains("g") || passedStrand.contains("t")) {
throw new RuntimeException("Illegal DNA strand");
} else if (passedStrand.contains("1") || passedStrand.contains("2")
|| passedStrand.contains("3") || passedStrand.contains("4")
|| passedStrand.contains("5") || passedStrand.contains("6")
|| passedStrand.contains("7") || passedStrand.contains("8")
|| passedStrand.contains("9") || passedStrand.contains("0")) {
throw new RuntimeException("Illegal DNA Strand");
} else if (passedStrand.contains(",") || passedStrand.contains(".")
|| passedStrand.contains("?") || passedStrand.contains("/")
|| passedStrand.contains("<") || passedStrand.contains(">")) {
throw new RuntimeException("Illegal DNA Strand");
}
}
public int getACount() {
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.charAt(i) == 'A') {
ACount++;
}
}
return ACount;
}
public int getCCount() {
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.charAt(i) == 'C') {
CCount++;
}
}
return CCount;
}
public int getGCount() {
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.charAt(i) == 'G') {
GCount++;
}
}
return GCount;
}
public int getTCount() {
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.charAt(i) == 'T') {
TCount++;
}
}
return TCount;
}
public String getStrandString() {
return passedStrand;
}
public int getLength() {
return passedStrand.length();
}
public int getCount(String pattern) {
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.contains(pattern)) {
patternCount++;
}
}
return patternCount;
}
public int findPattern(String pattern, int startIndex) {
return 0;
}
}
Here is my output:
A count: 1
C count: 0
G count: 4
T count: 2
Strand: AGGTTGG
Strand length: 7
Pattern Count: 7
Notice your for loop:
for (int i = 0; i < passedStrand.length(); i++) {
if (passedStrand.contains(pattern)) {
patternCount++;
}
}
If the pattern is there in passedStrand, it will always be true. It doesn't really depend upon any part of the loop. Since the loop is running passedStrand.length() number of times, that condition will be checked that many times. And every time, since it is true, the patternCount is incremented. And hence the final value of patternCount will be passedStrand.length();.
What you rather want to do is, starting at every index, check if next pattern.length() number of characters, make up a string equal to pattern. If yes, then increment patternCount. So, you would need to make use of substring method here:
int patternLen = pattern.length();
for (int i = 0; i < passedStrand.length() - patternLen + 1; i++) {
if (passedStrand.substring(i, i + patternLen).equals(pattern)) {
patternCount++;
}
}
Also notice that, the loop will not really run till the end of passedStrand string. You just need to run till the index, from where there is a possibility of complete occurrence of pattern string.
This method creates extra String objects inside the for loop, due to substring invocation. You can avoid this by using String#indexOf method. You just keep on finding the next index of the pattern in the passedStrand, till you get the index as -1, where it ends.
int startIndex = passedStrand.indexOf(pattern);
while (startIndex != -1) {
patternCount++;
startIndex = passedStrand.indexOf(pattern, startIndex + pattern.length());
}
If efficiency is not a big concern, then regex is really sweet. See how:
public int getCount(String pattern) {
int patternCount = 0;
Matcher matcher = Pattern.compile(pattern).matcher(passedStrand);
while (matcher.find()) {
patternCount++;
}
return patternCount;
}
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.