Scanner in Java doesn't read all my input - java

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.

Related

Why my code is incorrect (processing string)?

I'm currently doing an online course on hyperskill. There's a task:
The password is hard to crack if it contains at least A uppercase
letters, at least B lowercase letters, at least C digits and includes
exactly N symbols. Also, a password cannot contain two or more same
characters coming one after another. For a given numbers A, B, C, N
you should output password that matches these requirements.
And here's my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int upper = scan.nextInt();
int lower = scan.nextInt();
int digits = scan.nextInt();
int quantity = scan.nextInt();
String symbolsUpper = "QWERTYUIOPASDFGHJKLZXCVBNM";
String symbolsLower = "qwertyuiopasdfghjklzxcvbnm";
String symbolsDigits = "1234567890";
boolean exit = false;
Random random = new Random();
ArrayList<Character> password = new ArrayList<>();
if (upper > 0) {
for (int i = 0; i < upper; i++) {
password.add(symbolsUpper.charAt(random.nextInt(symbolsUpper.length())));
}
}
if (lower > 0) {
for (int k = 0; k < lower; k++) {
password.add(symbolsLower.charAt(random.nextInt(symbolsLower.length())));
}
}
if (digits > 0) {
for (int z = 0; z < digits; z++) {
password.add(symbolsDigits.charAt(random.nextInt(symbolsDigits.length())));
}
}
if (quantity - digits - upper - lower > 0) {
for (int m = 0; m < (quantity - digits - upper - lower); m++) {
password.add(symbolsDigits.charAt(random.nextInt(symbolsDigits.length())));
}
}
Collections.shuffle(password);
while (!exit) {
if (password.size() > 1) {
for (int i = 1; i < password.size(); i++) {
if (password.get(i).equals(password.get(i - 1))) {
char buffer = password.get(i);
password.remove(i);
password.add(buffer);
i--;
} else {
exit = true;
}
}
} else {
exit = true;
}
}
StringBuilder buildPassword = new StringBuilder();
for (Character character : password) {
buildPassword.append(character);
}
System.out.println(buildPassword);
}
}
When I run the code in IntelliJ IDEA, the program works just fine, however, the hyperskill platform doesn't accept this code as the right one.
The topic is "Processing string".
Can anyone here tell me please, what am I doing wrong? Is there a better way to write this code?
Can anyone here tell me please, what am I doing wrong?
The problem is that, due to the nature of random numbers, you might be very unlucky in the characters which are picked. This can result in two problems:
You can pick the same characters from the pool of characters. When you create a password using the input 0 0 0 2 it might be possible that two same digits are picked. As an example the password "55" can never satisfy the condition of having not two characters next to each other be the same, no matter how many time you shuffle it.
When the password is very long and you find two characters same next to each other you put one of the character to the end. This can happen twice for the same character. This means that the password "........44........44........." can result in the password ".........4.........4...........44", and now you have two same characters again (at the end).
Is there a better way to write this code?
Yes.
I don't know if you are trying for best performance, but here is a fun solution:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int uppers = scan.nextInt();
int lowers = scan.nextInt();
int digits = scan.nextInt();
int quantity = scan.nextInt();
int freeChoices = quantity - uppers - lowers - digits;
if (freeChoices < 0) {
System.exit(1);
}
ThreadLocalRandom r = ThreadLocalRandom.current();
StringBuilder password = new StringBuilder();
boolean isPasswordReady = false;
int lastUpper = -1, lastLower = -1, lastDigit = -1;
PasswordPart[] options = PasswordPart.values();
while (!isPasswordReady) {
int partChoice = r.nextInt(0, options.length);
switch (options[partChoice]) {
case DIGIT:
if (digits > 0 || freeChoices > 0) {
CharIndexHolder result = options[partChoice].get(lastDigit, -1, r);
password.append(result.c);
lastDigit = result.i;
if (digits == 0) {
freeChoices--;
} else {
digits--;
}
}
break;
case LOWER:
if (lowers > 0 || freeChoices > 0) {
CharIndexHolder result = options[partChoice].get(lastLower, lastUpper, r);
password.append(result.c);
lastLower = result.i;
if (lowers == 0) {
freeChoices--;
} else {
lowers--;
}
}
break;
case UPPER:
if (uppers > 0 || freeChoices > 0) {
CharIndexHolder result = options[partChoice].get(lastUpper, lastLower, r);
password.append(result.c);
lastUpper = result.i;
if (uppers == 0) {
freeChoices--;
} else {
uppers--;
}
}
break;
}
isPasswordReady = uppers == 0 && lowers == 0 && digits == 0 && freeChoices == 0;
}
System.out.println(password.toString());
}
enum PasswordPart {
UPPER("QWERTYUIOPASDFGHJKLZXCVBNM"), LOWER("qwertyuiopasdfghjklzxcvbnm"), DIGIT("1234567890");
private String pool;
PasswordPart(String pool) {
this.pool = pool;
}
public CharIndexHolder get(int lastIndex, int additionalIndex, ThreadLocalRandom random) {
int i = random.nextInt(0, pool.length());
while (i == lastIndex || i == additionalIndex) {
i = random.nextInt(0, pool.length());
}
return new CharIndexHolder(pool.charAt(i), i);
}
}
private static class CharIndexHolder {
char c;
int i;
CharIndexHolder(char c, int i) {
this.c = c;
this.i = i;
}
}

Finding Kaprekars Constant of a number using Java

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)

Java: Why is the integer in the main method combined with method

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.

can someone help me clear these errors

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.

Currently compiling, but receiving nothing but end to program?

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;
}

Categories