This question already has answers here:
Print out elements from an Array with a Comma between the elements
(14 answers)
Closed 5 years ago.
this is my code
System.out.println("Enter any integer number ");
int number = scan.nextInt();
while (number > 0) { System.out.print( number % 10 + ",");number = number / 10;}
To clarify if the user enter 1234
the output should be 4,3,2,1,
how can i edit the code to remove the comma after the last num?
something like 4,3,2,1
Since everyone is having a field day, here's mine:
while (number > 0) {
System.out.print( number % 10 + ((number/=10)>0 ? "," : ""));
}
This is the most elegant approach I have picked along the way:
String delimiter = "";
while (number > 0) {
System.out.print(delimiter + number % 10);
number /= 10;
delimiter = ",";
}
I would do the following
if (number > 0) {
System.out.print( number % 10 );
number = number / 10;
while (number > 0) {
System.out.print("," + (number % 10) );
number = number / 10;
}
}
Print the first element and then for all the other ones prepend a ,. In this way, you always end with a
, X
The other options are doing unnecessary if checks.
I would do it this way
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
if (number > 0)
System.out.print(",");
}
This could do the trick:
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
if(number!=0) System.out.print(",");
}
Sotirios's solution works but here's an alternative:
// replacing "scan" with an example number.
int start = 123456789;
for (int number = start; number > 0; number = number / 10) {
if(number < start)
System.out.print(',');
System.out.print(number % 10);
}
This will DRY up the calculation of the count down (number/10) but does the test to see if it's not the first one in each loop. I think that that test, however, would turn out to be faster than doing string arithmetic ("," + (number % 10)).
Hope this helps.
int x;
Scanner scan = new Scanner(System.in);
System.out.print("Enter integer : ");
x = scan.nextInt();
for(x = 4; x>1; x = x-1)
{
System.out.print(x + ",");
}
if (x != 0) // this is so the last number doesn't end with a comma
{
System.out.print(x);
}
All the code that was showed here is invalid because the user can enter 0 and 0 should be printed out.
The valid code will look the following way
do
{
System.out.print( number % 10 );
number = number / 10;
if ( number != 0 )
System.out.print( "," );
} while ( number != 0 );
Related
Problem while entering a 3 digit no and getting no result. after entering 123 and when 2 is detected as even, and if user enters 7, it should display 173. but the program is immediately ending. It might be a problem in the last 0 check if-block. but removing it also doesn't help. Thanks in advance!
// in 3 dig, check even dig., replace them with odd and disp.
import java.util.*;
public class p24123 {
public static void main(String[] args) {
int n,h,t,o,m,z=0,z1=0,z2=0,fn;
Scanner ob = new Scanner(System.in);
n=ob.nextInt();
if(n>99&&n<1000){
h= n/100;
o=n%10;
m=n/10;
t=m%10;
if(h%2==0){
z=h;
System.out.println("Enter the odd number you would like to replace the EVEN hundred's digit"+h+" with \n");
z=ob.nextInt();
if(z%2==0){
System.out.println("That's not odd. So we will keep the original digit in it's place");
z=h;
}
else if(t%2==0) {
System.out.println("Condition enter bokachpda");
z1 = t;
System.out.println("Enter the odd number you would like to replace the EVEN ten's digit" + t + " with \n");
z1 = ob.nextInt();
if (z % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
z1 = t;
}
}
else if(o%2==0){
z2=o;
System.out.println("Enter the odd number you would like to replace the EVEN one's digit"+h+" with \n");
z2=ob.nextInt();
if(z2%2==0){
System.out.println("That's not odd. So we will keep the original digit in it's place");
z2=o;
}
}
else if(2==2){
if(h<1||t<1||o<1||z<1||z1<1||z2<1){
System.out.println("Error");
System.exit(0);
}
}
fn=z*100+z1*10+z;
}
}
}
}
Here's your code cleaned up and fixed. I modified as little as possible to keep it at a level a beginner would be comfortable with. Some improvements to be made:
Repeated code like this screams, "Put me in my own function!"
A loop can be used to handle any number of digits, not just three.
Error checking/handling. You should handle bad input. What if the user enters "hello" instead of a number?
Improvements I made:
Your original code never printed a result.
Better formatting. It makes the code easier to read.
Descriptive variable names!
Scanner ob = new Scanner(System.in);
int n = ob.nextInt();
if (n > 99 && n < 1000) {
int hundredsDigit = n / 100;
int tensDigit = n / 10 % 10;
int onesDigit = n % 10;
if (hundredsDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN hundred's digit " + hundredsDigit +" with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
hundredsDigit = replacementDigit;
}
}
if (tensDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN ten's digit " + tensDigit + " with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
tensDigit = replacementDigit;
}
}
if (onesDigit % 2 == 0) {
System.out.println("Enter the odd number you would like to replace the EVEN one's digit " + onesDigit + " with \n");
int replacementDigit = ob.nextInt();
if (replacementDigit % 2 == 0) {
System.out.println("That's not odd. So we will keep the original digit in it's place");
}
else {
onesDigit = replacementDigit;
}
}
System.out.println(hundredsDigit * 100 + tensDigit * 10 + onesDigit);
}
I am new to Java and currently working on a small class assignment. The question is as follows:
Write a program that determines whether a bank account number with 10 digits or fewer passes a validation test; it requires that we extract the digits, right to left by:
Using the modulo operator to extract the right most digit
Using integer division to remove the right-most digit from the account number to obtain a new number without it.
Beginning with the 2nd right-most digit, moving right to left, double every other digit. If it produces a value greater than 9, subtract 9 from that value.
Form the sum of all products(new digits) and the unchanged digits.
if the sum doesn't end in 0, its invalid.
Check the validity of 5113 4765 12 and 65 1234 1234
Here is my code:
long account = Long.parseLong(JOptionPane.showInputDialog( null, "Enter account number: " ));
int sum = 0;
long digit;
//5113476512
//6512341234
String str_number = String.valueOf(account);
digit = account % 10;
account /= 10;
for(int i = str_number.length() -2; i >= 0; i --){
digit = account % 10;
account /= 10;
// account%=10;
// sum += digit;
digit *= 2;
if (digit > 9){
digit -= 9;
}
sum += digit;
}
// for(int x = 0; x < digit.length; x ++){
// sum += digit[x];
// }
if (sum % 10 != 0){
JOptionPane.showMessageDialog(null, "Account number invalid");
}
else{
JOptionPane.showMessageDialog(null, "Account number valid");
}
JOptionPane.showMessageDialog(null, sum);
But I feel it doesn't follow the requirements and might not be correct. Only one of the account numbers returns valid although I'm not sure if that is supposed to be so or not. Any ideas on how to go about this?
The following implementation using a boolean flag to detect the other number shows that both account numbers are invalid:
public static boolean isValid(long acc) {
System.out.print(acc + " -> "); // debug print
int sum = 0;
boolean other = false;
while (acc > 0) {
int digit = (int) (acc % 10);
acc /= 10;
if (other) {
digit *= 2;
if (digit > 9) digit -= 9;
}
System.out.print(digit + " "); // debug print
sum += digit;
other = !other;
}
System.out.println("sum = " + sum); // debug print
return sum % 10 == 0;
}
Tests:
System.out.println(isValid(5113476512L));
System.out.println(isValid(6512341234L));
Output:
5113476512 -> 2 2 5 3 7 8 3 2 1 1 sum = 34
false
6512341234 -> 4 6 2 2 4 6 2 2 5 3 sum = 36
false
I've started to learn basics of Java and currently I have to find and print largest divisible number.
For example number 30 can be divided by 2, 3, 6 and 10 so on the console I should show only 10. Another example is number 12 which can be divided by 2, 3 and 6 - should show 6.
I'm stuck at the point where I show the largest number. What I have so far is this one
double isItDivisible = Double.parseDouble(scanner.nextLine());
int num = 2;
if ( isItDivisible % 2 == 0 ) {
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 3 == 0 ) {
num = 3;
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 6 == 0 ) {
num = 6;
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 10 == 0 ) {
num = 10;
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 7 == 0 ) {
System.out.println("The number is divisible by " + 7);
}
The snipped display the first occurrence instead of the largest.
You can tell how new I'm based on the snipped so please bear with me.
When you want to find the highest divisible number that is not the input you could do the following:
int highest = 1; //1 should always apply - at least for integers
//iterate from highest to lowest number
for( int d = input-1; d > 1; d-- ) {
//stop at the first number that divides the input without a rest
if( input % d == 0 ) {
highest = d;
break;
}
}
If you want to check specific numbers only, you could modify that to use a sorted collection of numbers.
//TreeSet is sorted and the reserved comparator makes it sort from high to low
SortedSet<Integer> divisors = new TreeSet<>(Comparator.reversed());
//if the collection itself is sorted the order of additions doesn't matter
//if you're using a list and don't sort it after adding elements then order of insertion is relevant though
divisors.add(2);
divisors.add(10);
divisors.add(3);
divisors.add(7);
divisors.add(6);
Integer highest = null;
//iterates in sorted order
for( Integer d : divisors ) {
if( input % d == 0 ) {
highest = d;
break;
}
}
Try this :
public static void main(String[] args)
{
// Scanner Class
Scanner scanner = new Scanner(System.in);
double isItDivisible = Double.parseDouble(scanner.nextLine());
int high = 0;
for (int i = 0; i < isItDivisible; i++) {
if (isItDivisible % i == 0) {
high = i;
}
}
System.out.println(high);
}
Edit : With divide by pecific numbers 2,3,6,7,10:
public static void main(String[] args)
{
// Scanner Class
Scanner scanner = new Scanner(System.in);
double isItDivisible = Double.parseDouble(scanner.nextLine());
int high = 0;
int[] divide = {2,3,6,7,10};
Arrays.sort(divide);
for (int i : divide) {
if (isItDivisible % i == 0) {
high = i;
}
}
System.out.println(high);
}
The program needs to take an odd number and output it in a descending order
For example: if the input is 11 the output needs to be 11 , 9 , 7 , 5 , 3, 1.
I tried using a for loop but I can only seem to get it to work with even numbers not odd numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
for (int i = number - 1; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
}
The output is the number in descending order but as even only. If I add a 1 into the descend variable the numbers would seem to descend in an odd manner but its not ideal.
This line returns true if the number is even:
if (i % 2 == 0) {
If you want to know when the number is odd:
if (i % 2 != 0) {
Also, why are you starting your count at 1 less than the input value:
int i = number - 1;
I think you want to do this:
for (int i = number; i > 0; i--) { // tests for numbers starting at the input and stopping when i == 0
Just replace (i%2==0) to (i%2==1)
Asking if the number % 2 is equal to zero is basically asking if the number is even, so what you really have to do is ask if the number % 2 is not equal to zero, or equal to 1
if (i % 2 != 0) {
int descend = i;
System.out.println(descend + " ");
}
Also, there's no need to subtract 1 from the user input so your for loop can be written like this
for (int i = number; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an an odd number: ");
int number = input.nextInt();
while(number%2==0){
System.out.print("Number must be odd number:" +
"(Ex:1, 3,5)\nTry again: ");
number=input.nextInt();
}
for (int i = number; i >= 0; i--) {
if(number%2!=0){
System.out.println(number);}
number-=1;
}
}
So I had to write a simple code that would compute the 3N+1 equation; where N is an integer user types in and if it is a positive integer than N = N / 2 and if negative integer than N = N * 3 + 1.
However from what I can understand, my code doesn't work after the first while loop and hence prints nothing. What am I doing wrong? New to programming and still learning so I appreciate your help :)
Code:
import java.util.Scanner;
public class ThreeNplusOneProgram {
public static void main(String[] args) {
int N; Scanner input = new Scanner(System.in); int counter;
System.out.println("Please Enter an integer: ");
N = input.nextInt();
while ( N <= 0 ) {
System.out.println("ERROR: Please Enter an integer greater than zero: ");
N = input.nextInt();
}
//So far we know that N is great than Zero
System.out.println(N);
counter = 1;
while ( N != 1 ) {
if (N == N % 2 )
N = N / 2;
else N = N * 3 + 1;
counter = counter + 1;
}
System.out.println("There were" + counter + "terms in the sequence");
}
}
That is wrong: if (N == N % 2 )
N % 2 returns 1 or 0. You should use if (0 == N % 2 ) to check for being odd / even.
The problem is your if (N == N % 2), you might just want to check if (N >= 0) since you do state that you are looking to check if it is a positive integer.