Printing with delimiter only between values - java

I have a slight problem with the output of my code and been searching for such topics same as with this but I don't find any.
while (true) {
System.out.print("Enter a positive integer: ");
n = sc.nextInt();
System.out.print(n + "! = ");
for (int i = 1; i <= n; i++) {
factorial = factorial * i;
System.out.printf("%d x " , i);
}
System.out.println("");
}
The output must be. Whenever I type integer. e.g 5.
Enter a positive integer: 5
5! = 1 x 2 x 3 x 4 x 5
But the slight problem is that the output goes like this 5! = 1 x 2 x 3 x 4 x 5 x
There's extra x on the last number which should not be there

StringJoiner
Others already answered how to fix your code but I would like to provide you with a more professional solution, namely by using a StringJoiner.
With this, you can give a delimiter, prefix and suffix, then just add all your elements and the StringJoiner will make sure that the delimiter is only added in between. It takes all the work from you. Here is the code:
StringJoiner sj = new StringJoiner("x ", n + "! = ", "");
for (int i = 1; i <= n; i++) {
sj.add(Integer.toString(i));
}
System.out.println(sj);
Streams
If you prefer streams:
String result = IntStream.rangeClosed(1, n)
.mapToObj(Integer::toString)
.collect(Collectors.joining("x ", n + "! = ", ""));
System.out.println(result);

Replace this line:
System.out.printf("%d x " ,i);
by this:
if (i == n)
System.out.printf("%d" ,i);
else
System.out.printf("%d x " ,i);
This way you avoid printing "x" when you print the last number in the factorization.

Perhaps you can do this:
while (true) {
System.out.print("Enter a positive integer: ");
n = sc.nextInt();
String result = "";
System.out.print(n + "! = ");
for (int i = 1; i <= n; i++) {
factorial = factorial * i;
result += i + " x ";
}
System.out.println(result.substring(0, result.length() - 3);
}

Related

Java - Searching an element in a random array

I executed the following code:
import java.util.Scanner;
public class Linear_Search {
public static void main(String[] args) {
int arr[] = new int[20];
for(int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random() * 10) + 1;
}
System.out.print("Array is: ");
for(int i : arr)
System.out.print(arr[i] + " ");
//int arr[]= {1,2,4,5,6,7,8,43,6,4,2,6,8,3};
System.out.println();
System.out.println("Enter the number you want to search");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
boolean found = false;
String indices = "";
for(int i = 0; i < arr.length; i++) {
if(num == arr[i]) {
found = true;
indices = indices + i + ", ";
}
}
if(found == false) {
System.out.println(num + " does not exist");
}
else {
System.out.println(num + " found at index: " + indices.substring(0, indices.length() - 2));
}
sc.close();
}
}
Output:
Array is: 3 3 1 2 8 1 2 2 3 1 3 3 7 1 7 3 1 3 8 3
Enter the number you want to search
2
2 found at index: 0, 1, 8 ,15
Why is this displaying random indices as answers. The code works fine when i use a custom array like the one that is commented in the code. Is it related to explicit cast on Math.random() or something else?
You are mislead by the loop printing the array, which doesn't really print the array elements.
Change:
for(int i : arr)
System.out.print(arr[i] + " ");
to:
for(int i : arr)
System.out.print(i + " ");
and you'll see the actual array values.
When you iterate over an array with the enhanced for loop, you are iterating over the array values not over the array indices.

Output line repeats using while loop?

I am just beginning to learn Java and still getting used to while loops. I would like the output statement to only show once instead of multiple times. For example, the statement should say:
"Even integers between 1 and 5 are: 2 4"
instead of:
"Even integers between 1 and 5 are:
2
Even integers between 1 and 5 are:
Even integers between 1 and 5 are:
4"
If I could get some feedback on what I'm doing wrong here, it'd be appreciated. Thanks
//Declare variables
int n1, n2, sumOdd = 0;
int sum = 0;
int sumSquares = 0;
//Part B
int count = n1;
while (count < n2)
{
if (count % 2 ==0)
{
System.out.println(count);
}
count++;
System.out.println("Even integers between " + n1 + " and " + n2 + " are: ");
} //end loop
create an int array or Collection before your loop, when you find out the even number in while loop, append the number in the array/collection.
After the while loop, print output only once, of course with those found numbers.
I think it is straightforward, and I leave the implementation part to you.
You should take last part of the while loop out of it:
//Part B
System.out.println("Even integers between " + n1 + " and " + n2 + " are: ");
int count = n1;
while (count < n2) {
if (count % 2 ==0) {
System.out.print(" " + count);
}
count++;
}
As you didn't mention that you want a comma between even numbers, then replacing println with print should be enough
They are different ways to achieve your goal. A quick solution would be to put
System.out.println("Even integers between " + n1 + " and " + n2 + " are: ");
in front of your while-loop and and replace System.println() with System.print().
int n1, n2, sumOdd = 0;
int sum = 0;
int sumSquares = 0;
System.out.print("Even integers between " + n1 + " and " + n2 + " are: ");
//Part B
int count = n1;
while (count < n2)
{
if (count % 2 == 0)
{
System.out.print(count);
}
count++;
} //end loop

java get even or odd number

I have a assignment for school: I need to get even or odd numbers and I made something to work for numbers that are above zero, but I need to find out how a negative number is even or odd.
String[] evenodd = {" number is even", " number is odd"};
for(int i = 0; i < 100; i++)
{
int x = i;
while (x > 1) x = x - 2;
System.out.println(i + evenodd[x]);
}
simply use module % operator
String[] evenodd = {" number is even", " number is odd"};
for(int i = 0; i < 100; i++)
{
int x;
if(i%2==0){
x=0;/*pass 0 to print even number */
}else{
x=1;/*pass 1 to print odd number*/
}
System.out.println(i + evenodd[x]);
}
Even and Odd numbers:
String[] evenodd = {" number is even", " number is odd"};
for(int i = 0; i < 100; i++)
{
System.out.println(i + evenodd[i % 2]);
}
OR
String[] evenodd = {" number is even", " number is odd"};
for(int i = 0; i < 100; i++)
{
if(i % 2 == 0)
System.out.println(i + evenodd[i % 2]);
else
System.out.println(i + evenodd[i % 2]);
}
For negative numbers is even or odd?:
String[] evenodd = {" number is even", " number is odd"};
for(int i = 0; i > -100; i--)
{
if(i % 2 == 0)
System.out.println(i + evenodd[0]);
else
System.out.println(i + evenodd[1]);
}
Try and use the % operator.
Usage : x % y -> This will give you the remainder when y is divided by x.
In your case use y = 2. Hence if the remainder = 0, the number is even else the number will be odd.
I am not giving you the exact code, since this is your assignment. Try it yourself based on the suggestion.
To find out odd and even number. Follow the logic
divide your number by 2 if the reminder is 0 then it is even
else it is odd
this similar for both positive and negative numbers
to find out reminder use modulo division operator (%). if your_number%2=0 your_number is even else your_number is odd.
Sample code:
for(int i=1;i<100;i++){
if(i%2==0){//for positive number
System.out.println(i+ " is Even Number");
}else{
System.out.println(i+ " is Odd Number");
}
if((-1)*i%2==0){//for negative number
System.out.println((-1)*i+" is Even Number");
}else{
System.out.println((-1)*i+" is Odd Number");
}
}

How to compare the given integer with possible roots

I could not name the question in the best way... My aim is to write a program that takes integer n from user. Then compare with the third power of two integers a and b.
If a^3 + b^3 is smaller than or equal to the given input, I want to print out every single possible calculation to the user.
My code is as follows:
System.out.println("Hi. Please insert an integer: ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double root = Math.cbrt(n);
int rootInt = (int) root;
for (int i = 0; i < rootInt; i++){
for (int j = 0; j < rootInt; j++){
if ((Math.pow(i, 3)) + (Math.pow(j, 3)) <= n){
double t = (Math.pow(i, 3) + (Math.pow(j, 3)));
int totalInt = (int) t;
System.out.println(i + "^3" + " + " + j + "^3" + " = " + totalInt );
} else {
}
j++;
}
i++;
}
When I run this and give an input as 30, it prints
0^3 + 0^3 = 0
0^3 + 2^3 = 8
2^3 + 0^3 = 8
2^3 + 2^3 = 16
What am I doing wrong?
You increase j and i twice. That's why you test only the even values for i, j.
If you want to correct the code, remove the i++, j++ from the end and use only the increments from the 2 fors.

How to sum array contents with their powers of 3

I need to do something like this - user types in a number (e.g. 5) and the program shows the result of the following action: 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 + 5*5*5.
My code is following:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt();
int a[] = new int[n];
int power = 0;
int sum = 0;
for (int i = 1; i <= a.length; i++)
{
power = (int) pow(i, 3);
// Maybe here'a the problem, a[n] has not enough space for the power (???)
sum += a[power];
}
System.out.println(Result: " + sum);
}
I think that I understand why this code doesn't work but I will appreciate any ideas about how to do it properly and runnable.
sum += power;, no need for a.
Or simply use math :
int n = input.nextInt();
int result = (int)(0.25 * Math.pow(n, 2)*Math.pow(1+n,2));
Or even more simple, as #ajb said :
int result = n*n*(n+1)*(n+1)/4;
Change:
sum += a[power];
to
a[i-1] = power;
sum += a[i-1];
or forget the array altogether
sum += power;
sum += a[power]; doesn't exist.
You need to :
store the power value in the ith array item.
add the ith array value to the sum
Change your loop body to:
power = (int) pow(i, 3);
a[i - 1] = power;
sum += a[i - 1];
You're doing way too much work.
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt(),
sum = 1;
for (int i=2; i<=n; i++) {
sum += (int) Math.pow(i,3);
}
done. sum now contains the sum 1³ + 2³ + 3³ + ...
Or, more efficiently with exactly the same functionality:
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt(),
sum = 1;
while(n > 1) {
sum += (int) Math.pow(n--,3);
}
Why? Because 1 + 5³ + 4³ + 3³ + 2³ is the same as 1³ + 2³ + 3³ + 4³ + 5³
Of course you could also just directly compute that value, using actual maths, cutting all the entire algorithm with a simple arithmetic oneliner.

Categories