Printf Issue or Program Issue? - java

Trying to take an arraylist of numbers and print out the following...
MOST POPULAR NUMBERS
The following numbers were picked 263 times: 41
LEAST POPULAR NUMBERS
The following numbers were picked 198 times: 20
AVERAGE
The Average was 228.545455 times.
The following numbers were picked 228 times: 5 22
The following numbers were picked 229 times: 2 7 12 40
My code...
import java.util.*;
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
public class Hmwk {
public static void main(String[] args) throws FileNotFoundException {
Scanner input=new Scanner (new File ("input.txt"));
int counter = 0;
ArrayList<Integer> numberList = new ArrayList<Integer>(45);
while(input.hasNextInt()){
int in = input.nextInt();
numberList.add(in);
counter++;
}
mostPopular(numberList,counter);
leastPopular(numberList,counter);
average(numberList,counter);
}
public static void mostPopular(ArrayList<Integer> list, int total){
Collections.sort(list);
int popular = 0;
int counter = 0;
int counterTwo = 0;
for (int i=0; i<total-1; i++){
while(list.get(i) == list.get(i+1)){
counter++;
i++;
if(i == total-1) break;
}
if(counter > counterTwo){
counterTwo = counter;
popular = i;
}
}
System.out.printf("MOST POPULAR NUMBERS");
System.out.printf("The following number was picked",counterTwo,"times:", popular);
}
public static void leastPopular(ArrayList<Integer> list, int total){
Collections.sort(list);
int unpopular=0;
int counter = 0;
int counterTwo = 0;
for (int i=0; i<total-1; i++){
while(list.get(i) == list.get(i+1)){
counter++;
i++;
if(i == total-1) break;
if(counter < counterTwo){
counterTwo = counter;
unpopular = i;
}
}
}
System.out.printf("LEAST POPULAR NUMBERS");
System.out.printf("The following number was picked",counterTwo,"times:", unpopular);
}
public static void average(ArrayList<Integer> list, int total){
int sum = 0;
int counter = 0;
ArrayList<Integer> average = new ArrayList<Integer>(45);
for (int i=0; i<total-1; i++){
while(list.get(i) == list.get(i+1)){
counter++;
i++;
if(i == total-1) break;
}
average.add(counter);
}
for (int i = 0; i <average.size(); i++){
sum+= average.get(i);
}
double average2 = sum/total;
System.out.printf("AVERAGE");
System.out.printf("The Average was",average,"times.");
double ceiling = Math.ceil(average2) ;
double floor = Math.floor(average2);
int counter2 = 0;
Collections.sort(list);
for (int i=0; i<total-1; i++){
while(list.get(i) == list.get(i+1)){
counter2++;
i++;
if(i == total-1) break;
}
if(counter2 == ceiling){
System.out.printf("The following number was picked", ceiling,"times:",i);
}
if (counter2 == floor){
System.out.printf("The following number was picked", floor,"times:",i);
}
}
}
My output is currently...
MOST POPULAR NUMBERSThe following number was pickedLEAST POPULAR NUMBERSThe following number was pickedAVERAGEThe Average was
What I can't seem to figure out is where I went wrong in my program, or if I'm making some stupid mistakes while trying to print out the data. Any and all help is much appreciated, thanks for your time.

printf
The manner in which printf is invoked shows you may have some misconceptions about how it works. printF does NOT concatenate each argument passed to the method. It takes a String containing placeholders as the first parameter and then successive arguments to be assigned to each placeholder.
To invoke printf you need to add placeholders in your initial string and supply the arguments for each placeholder as follows:
System.out.printf("The following number was picked %s times %s",counterTwo, popular);
The code is currently only printing the first String argument which does not have any place holders. The extra arguments supplied to the method are then ignored because no placeholders exist for these arguments to be assigned.
Here is a simple example to help
String stringForFormatting = "Argument %s Argument %s";
String argument1 = "1";
String argument2 = "2";
System.out.printf(stringForFormatting, argument1, argument2); //any other args would be ignored
//outputs Argument 1 Argument 2
New Lines
It also appears that you would like the output to appear on different lines. This can be done in two ways.
First you could add \n to the String:
System.out.printf("MOST POPULAR NUMBERS\n");
But since you really don't need to use printF if the String does not contain any dynamic content (meaning it does not need placeholders), you could use plain System.out.println(), which will add the newline for you:
System.out.println("MOST POPULAR NUMBERS");

Related

Lucky number with User Input

I'm facing troubles solving the following question: I suppose to get the user to input a number and check if it is a lucky number. A lucky number is the sum of squares of even-positioned digit (starting from the second position) is a multiple of 7.
Following is the example of my codes, when i run the program it will stuck at user input, please advise how do i get it to run:
public class Tester {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number: ");
int number = scanner.nextInt();
int count = 0;
while(number!=0) {
number/=10;
++count;
}
int[] array = new int[count];
int sum = 0;
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
for (int i=0; i<count; i++) {
if(array[i]%2==0) {
sum+=(array[i]*array[i]);
}
else {
continue;
}
}
if (sum%7==0) {
System.out.println("The number: " +number+ "is a Lucky number");
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
}
I believe the culprit is the below loop:
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
I think your intention was to get each of the digits into an array. However, you are getting an input from the scanner (which in this case is the user input) for count number of times.
While there are several ways of getting the number of digits and each digit into an array. I'm going to give you two ways. Also, I see no validations on the input integer (such as negative numbers, etc.) and I am going to ignore them right now.
Approach 1: Your for loop corrected
You just get the ith digit of the number using a formula.
for (int i=1; i<=count; i++) {
array[i] = (int) (number / Math.pow(10, count-i)) % 10;
}
Approach 2: Converting the numbers to String and back using streams
List<Integer> digits = Arrays.toStream(number.toString().split("")).map(
digitChar -> Integer.parseInt(digitChar)
).collect(Collectors.toList());
Note:
You need to import the classes java.util.Arrays and java.util.stream.Collectors
If you want even positioned digits,then you can directly get it in while loop.
while(number!=0) {
if(count%2 !=0){
int value = number %10; // even positioned values
// Do whatever you need to do with this value
}
number/=10;
++count;
}
If you want to convert the number into an digit array,then first find number of digits using log function and then store it array in reverse order.
int noOfDigits =(int) Math.floor(Math.log10(number)+1); // Finding No of digits
int[] array = new int[noOfDigits];
while(--noOfDigits>=0){
array[noOfDigits] = number/10; // storing every digits in reverse order
number%=10;
}
I don't know below code will be helpful for your core logic,yet I record this too.
If you want Sum of Squares of even positioned digits in number which is represented as array, then you can use below code.
int sum = 0;
for (int i=1; i<array.length; i+=2) {
sum += array[i] * array[i];
}
if (sum%7==0) {
// print number is lucky
}
else {
// print number is not lucky
}
If I understand your description correctly, here's a program that does what you want:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a number: ");
System.out.flush();
int number = scanner.nextInt();
int count = 0;
int n = number;
int sum = 0;
while(n!=0) {
int d = n % 10;
n/=10;
++count;
if (count % 2 == 0) {
System.out.printf("sum = %d + %d^2 = %d\n", sum, d, sum + d * d);
sum += d * d;
}
}
if (sum%7==0) {
System.out.printf("The number: %d is a Lucky number (%d = 7 * %d)", number, sum, sum / 7);
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
A lucky result:
Input a number: 123456
sum = 0 + 5^2 = 25
sum = 25 + 3^2 = 34
sum = 34 + 1^2 = 35
The number: 123456 is a Lucky number (35 = 7 * 5)

Why runtime error for 2 out of 8 cases?

I've completed Hackerrank's "Birthday Cake Candles" challenge and have passed 6 out of 8 test cases using the following code that sorts an array, then increments the frequency that the max int occurs and prints that value:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numCandles = in.nextInt();
int height[] = new int[numCandles];
for(int height_i=0; height_i < numCandles; height_i++){
height[height_i] = in.nextInt();
}
//Option 2: Sort the array, then count the number that are highest.
Arrays.sort(height);
int max = height[height.length - 1];
int index = height.length - 1;
int freq = 0;
while(height[index] == max) {
freq++;
index--;
}
System.out.println(freq);
}
}
It's not passing Test Case #6 (input) or Test Case #7. In short, Test Case #6 is 100,000 occurrences of the int 999999 and Test Case #7 is 100,000 occurrences of the int 1. Expected output for both is supposed to be 100000.
I'm thinking it might be encountering a runtime error because of the sorting method I call on the array and the array trying to sort ints of equal value over and over? Can anyone explain why my code won't work for those two Test Cases?
When all values in the input are the same, as in the sample input you included, the condition in this loop will be true until index is reduced to -1, at which point you'll get an ArrayIndexOutOfBoundsException:
while(height[index] == max) {
freq++;
index--;
}
Add a range check to the loop condition, for example:
while (index >= 0 && height[index] == max) {
With this change, the solution will pass all tests. But it's an inefficient solution. You sorted the input to reduce the number of iterations in the while loop. But sorting is an O(n log(n)) operation, which is slower than a simple filtering with O(n). For example:
int numCandles = in.nextInt();
int heights[] = new int[numCandles];
int m = Integer.MIN_VALUE;
for (int i = 0; i < numCandles; i++) {
heights[i] = in.nextInt();
m = Math.max(m, heights[i]);
}
final int max = m;
long freq = IntStream.of(heights).filter(x -> x == max).count();
System.out.println(freq);
You are getting an outbound of exception because you are reaching a part when you go less than 0
while(height[index] == max) {
freq++;
if(index == 0)
break;
index--;
}
This is my solution for this problem
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int height[] = new int[n];
for(int height_i=0; height_i < n; height_i++){
height[height_i] = in.nextInt();
}
Arrays.sort(height);
int counter = 0;
int different = height[n-1];
for(int height_i=n-1; height_i >=0 ; height_i--){
if(different ==height[height_i] )
{
counter = counter + 1;
}
else
{
break;
}
}
System.out.println(counter);
}
This is my solution for this. I think is better to use a for than a while for this.
Simple Solution
static int birthdayCakeCandles(int[] arr) {
int max = arr[0];
int count = 0;
for(int i =0; i<arr.length;i++) {
if(max < arr[i]) {
max = arr[i];
}
}
for(int i =0; i<arr.length;i++) {
if(max == arr[i]) {
count++;
}
}
return count;
}

Ascending order and Descending Java

Hi here's my problem i cant seem to print my outputs correctly i guess i'm having a logical error in my code, it doesn't print when i put an ascending number then a descending. i'm kind of new to programming too.
Code:
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
int n, i, k, j;
int asc = 0,
Scanner x = new Scanner(System.in);
do {
System.out.print("How many numbers to process : ");
k = x.nextInt();
if(k<=1) {
System.out.println("Enter a number greater than 1");
}
} while(k<=1);
System.out.printf("Please enter %d numbers: ",k);
n = x.nextInt();
for(i=0; i<n-1; i++) {
j = x.nextInt();
if( j < n) {
asc++; // is this right?
} else {
asc--;
}
}
if (asc==k) {
System.out.print("Not Growing Up.");
}
if (asc!=k) {
System.out.print("Growing Up.");
}
}
}
Here are the outputs
Example outputs (what i'm trying to get)
How many numbers to process : 4
Please enter 4 numbers : 1 2 3 4
Growing up.
How many numbers to process : 4
Please enter 4 numbers : 4 3 2 1
Not Growing up.
This is my problem :
How many numbers to process : 4
Please enter 4 numbers : 1 2 1 3
Growing up. // it should be not growing up.
There is no need to iterate through all numbers. You can just check if the previous number is lower (if growing). If not, print and return. Check my example code.
Replace
n = x.nextInt();
for (i=0; i<n-1; i++) {
j = x.nextInt();
if( j < n) {
asc++; // is this right?
} else {
asc--;
}
}
if (asc==k) {
System.out.print("Not Growing Up.");
}
if (asc!=k) {
System.out.print("Growing Up.");
}
With
int prev = x.nextInt();
for (i=0; i<k-1; i++) {
j = x.nextInt();
if (j < prev) { System.out.print("Not Growing Up."); return; }
prev = j;
}
System.out.print("Growing Up.");
String numbers = "1 2 3 4"; // Let's take this input for example
int temp = 0; // This use to compare previous integer
boolean isAsc = false; // This store whether the digits is growing up or not
StringTokenizer st = new StringTokenizer(numbers); // Declare StringTokenizer
while (st.hasMoreTokens()) {
int next = Integer.parseInt(st.nextToken()); // Put the first integer in next (1)
if(next > temp){ // if (1) > 0
temp = next; // Assign 1 to temp, next time digit 2 will compare with digit 1
isAsc = true; // Assign the ascending to true
} else
isAsc = false;
}
if(isAsc)
System.out.print("Growing up.");
else
System.out.print("Not growing up.");
}
Your can store the user input as a string like the variable numbers I've declared and break them into each token for compare purpose.
import java.lang.reflect.Array;
import java.util.*;
public class A1 {
public static void main(String[] args) {
int a[]={2,5,0,1};
Arrays.sort(a);
int b= a.length;
for(int i=0;i<a.length;i++)
{
System.out.println(+a[i]+"\t"+a[b-1]);
b--;
}
}
}

Print Fibonacci sequence up to nth place?

I am trying to print the entire fibonacci sequence up to a given place. So the user would decide how many numbers of the fibonacci sequence they want to see (up to 16 repetitions) and it would print the entire sequence.
My current code only prints the number in the sequences for the place that you choose.
ex: 4 prints 2 instead of 0 1 1 2.
public int Fibonacci(int number){
if(number == 1 || number == 2){
return 1;
}
int fib1=1, fib2=1, fibonacci=1;
for(int count= 3; count<= number; count++){
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
return fibonacci;
}
Here is my main method:
import java.util.Scanner;
public class FibonacciPrinter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
int input = in.nextInt();
FibonacciGenerator newNumber = new FibonacciGenerator();
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(input));
}
}
}
I think here,
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(input));
}
You almost certainly wanted,
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(fibCount)); // <-- fibCount not input
}
You need to update your method to handle the zero case, for example
public int Fibonacci(int number) {
if (number == 0) return 0;
// ...
}
and in Java, the convention would name Fibonacci to fibonacci because method names are camel case starting with a lower case letter (classes start with a capital letter by convention).

Java backtraking problem

Hey guys. I've been strugling with a backtraking problem for hours. Can anyone lend me a hand? Here is the problem:
n camels numbered from 1 to n are the arranged order. I want to rearrange so that each camel has a diferent camel in front.
This is what I have so far:
import java.util.*;
public class NCamile{
static int size;
static int count;
static char[] arrN= new char[100];
public static void main(String[] args){
System.out.print("Enter word: ");
String numar = getInt();
size = numar.length();
count=0;
for(int i=0; i < size ; i++){
arrN[i] = numar.charAt(i);
}
backtraking(size);
}
public static void backtraking(int newsize){
if (newsize == 1){
return;
}
for(int i=0 ; i < newsize; i++){
backtraking(newsize - 1);
if(newsize == 2 ){
display();
}
rotate(newsize);
}
}
public static void rotate(int newsize){
int position = size - newsize;
for(int i = position + 1; i < newsize; i++){
char gigi;
gigi = arrN[i - 1];
arrN[i - 1] = arrN [i];
arrN[i] = gigi;
}
}
public static void display(){
if (count < 9){
System.out.print(" ");
}
System.out.print(++count+ ")" + " ");
for(int i = 0 ; i < size ; i++)
System.out.print(arrN[i]);
System.out.print(" ");
if(count % 10 == 0){
System.out.println(" ");
}
}
public static String getInt(){
Scanner scan = new Scanner(System.in);
String s = scan.next();
return s;
}
}
With this, the algorithems show me every posible solution to rearrange a string, but it dosen't respect the last condition of the problem. I've tried ading this:
for(int j = 0 ; j < size ; j++){
if (array[j] !=[array[j + 1] )
display()
}
But after I added it I got about 10 times more displayed words then it should have shown me
Can anyone give me an idea on what should I do?
If you're only asked to insure that
i) a single new arrangement is produced, and
ii)that new arrangement must satisfy the condition that each camel follows a camel different from the one it followed in the original arrangement,
then you can easily satisfy this just by reversing the list of camels.
Surely this is not optimized solution, but for simply gettin result I would consider checking all of the permutations. Method producing every permutation wouldn't be hard to write (see e.g. String permutation) and checking if some camel has the same backtraced won't be any effort at all.
--- edit
So... Few things mended, few not:
I worked on String, not char array. Char array is completely misunderstand in this problem. It's better to use String object (cause in fact, String is char array) or int array (this have been hard to me, cause I haven't found any permutation method to be applied with such parameter). So the main method looks now:
private static String word;
public static void main(String[] args)
{
System.out.print("Enter word: ");
Scanner scan = new Scanner(System.in);
word = scan.next();
permutation(word);
}
I deleted your class variables (length, count, etc...) cause they are unnecessary right now. Writing out String is quite simple and if you would like to change output format - use String.length property instead.
Permutation method is copied from mentioned source, and little modified. It looks following:
public static void permutation(String s)
{
permutation("", s);
}
private static void permutation(String prefix, String s)
{
int n = s.length();
if (n == 0)
{
if (camelFit(prefix))
System.out.println(prefix);
}
else
{
for (int i = 0; i < n; i++)
permutation(prefix + s.charAt(i),
s.substring(0, i) + s.substring(i + 1, n));
}
}
if you would uncomment line checking if (camelFit (prefix)) it would display every permutation of input String. But! We would like to print only these camel chains, which fits problem conditions. How do we check if given chain is so? Simple method:
private static boolean camelFit(String prefix)
{
for (int i = 0; i < word.length() - 1; i++)
{
char camel = word.charAt(i);
char camelFollow = word.charAt(i+1);
for (int j = 0; j < prefix.length() - 1; j++)
{
if (prefix.charAt(j)==camel && prefix.charAt(j+1)==camelFollow)
{
return false;
}
}
}
return true;
}
Maybe not so simple, because we have to check every pair of input chain (every follower and followed) with every pair of output chain. If there isn't any match between any two pairs - given chain is fine.
Please notice, that this solution is absolutely non-optimized. Finding permutations is O(n!) complexity and checking pairs is O(n^2) complexity. Final complexity is O(n^2)*O(n!) so very, very high.

Categories

Resources