The problem was to reverse user entered digits. I have it working but while testing it I realized that it won't print either leading or trailing zeros.
For example if I enter 10 it only displays 1 in the result.
If I enter 0110 I get a result of 11.
Here is my code:
public class ReversingDigits {
int value;
int reverse;
public ReversingDigits() {
value = 10;
reverse = 0;
}// end constructor
public void reverse() {
System.out.println("Enter a valid 2-4 digit number: ");
Scanner input = new Scanner(System.in);
value = input.nextInt();
if (value < 10 || value > 9999){
System.out.print("Please enter a valid 2-4 digit number: ");
value = input.nextInt();
}
while (value > 0) {
reverse *= 10;
reverse += value % 10;
value /= 10;
}
System.out.println("Reversed numbers are: " + reverse);
}
}//end class
Any ideas on how to get the zeros to print?
Thanks
Make sure you work with a String while reversing your number. It will preserve leading zeros. As you know 00001 is the same as 1 when in int representation, and so converting that to a string will remove all leading zeros.
Here's your code sample modified to read a string from the input, and only convert it to an int when you need to check the range.
public void reverse() {
System.out.println("Enter a valid 2-4 digit number: ");
Scanner input = new Scanner(System.in);
String value = input.next();
int valueInt = Integer.parseInt(value);
if (valueInt < 10 || valueInt > 9999){
System.out.print("Please enter a valid 2-4 digit number: ")
value = input.next();
}
String valueReversed = new StringBuilder(value).reverse().toString();
System.out.println("Reversed numbers are: " + valueReversed);
}
Note that in your code, if a user enters the wrong range twice in a row, your program won't prompt him again. You may want to put this part of the code into a do-while loop which only exits when the input range is correct. Example
do {
System.out.print("Please enter a valid 2-4 digit number: ")
value = input.next();
int valueInt = Integer.parseInt(value);
} while (valueInt < 10 || valueInt > 9999);
//only get here when inputted value finally within target range.
Edit: As mentioned by #Levenal, you may also want to wrap Integer.parseInt in a try/catch block for NumberFormatException in the event the user passes in a non-numerical input.
As has been pointed out, reversing numbers you are much better off reversing a string. If you are allowed to stray away from console input, JOptionPane is quite good for simple String input, like so:
while(true){
String input = JOptionPane.showInputDialog("Please anter a number between 10 & 9999: ");
if(input == null){//If input cancelled
break; //Exit loop
} else if(input.matches("\\d{2,4}")){//Regex for at least 2 but no more than 4 numbers
System.out.println(new StringBuilder(input).reverse().toString());//Reverse
break;
}
}
Good luck!
Related
I'm prompting a user for a number and am trying to determine the amount of even, odd, and zeros in that number
/* This program will determine and print the number of even, zero, and odd digits in
* an integer
*
* Author: Marco Monreal
* Date: 11/01/2016
*/
import java.util.Scanner;
public class PP5_3
{
public static void main(String[] args)
{
String exit_loop, go_again, user_num, first_char_string;
int odds, evens, zeros;
int first_char; //, second_char, third_char, fourth_char, fifth_char, sixth_char, seventh_char, eighth_char, ninth_char, tenth_char;
Scanner scan = new Scanner (System.in);
evens = 0;
odds = 0;
zeros = 0;
exit_loop = "no"; //initializing while loop
while (exit_loop.equals ("no"))
{
System.out.println ("Choose any number between 0 and 2,147,483,647. Don't include commas please.");
user_num = scan.next ();
I'm getting stuck around this area; "first_char" is not returning the digit value that I want/need.
//assigning a variable to each character of user_num
first_char = user_num.lastIndexOf(0);
/*second_char = user_num.charAt(1);
third_char = user_num.charAt(2);
fourth_char = user_num.charAt(3);
fifth_char = user_num.charAt(4);
sixth_char = user_num.charAt(5);
seventh_char = user_num.charAt(6);
eighth_char = user_num.charAt(7);
ninth_char = user_num.charAt(8);
tenth_char = user_num.charAt(9);*/
//copy every character into a string value
first_char_string = String.valueOf(first_char);
if (first_char == 2 || first_char == 4 || first_char == 6 || first_char == 8)
{
evens++;
}
else if (first_char_string.equals("1") || first_char_string.equals("3") || first_char_string.equals("5") || first_char_string.equals("7") ||
first_char_string.equals("9"))
{
odds++;
}
else
zeros++;
} //ends while loop
System.out.println ("There are " +evens+ " even numbers, " +odds+ " odd numbers, and " +zeros+ "zeros in ");
scan.close ();
} //ends main method
} //ends class
Hi take a look on this line:
user_num = scan.next (); // this will scan your user input, but does not jump to the next line
you might want to use:
user_num = scan.nextLine();
Also you made a mistake in your lastIndexOf(char) method.
This method expects a char. you supply this method an int e.g:
first_char = user_num.lastIndexOf(0);
this works because java interprets your number a an ASCI-number. the char representated by ASCI "0" is null. What you want to do is search for the character '0'. Like the following:
first_char = user_num.lastIndexOf('0');
The same for your equalisations:
first_char == 2 ---> first_char == '2';
Another notice. Please use camel case istead of underscores. instead of user_num you should write userNum. Thats the standard.
Yet another notice. The lastIndexOf() method will return the nummber of the last occurence of the parameter. e.g:
String test = "hello test";
test.lastIndexOf(e); // this will return 7 for it is the number ofthe last occurence of 'e'
I think yu want to use charAt(0) this returns the charactere at specified position
Last Notice. why are you comparing char values representing numbers ?
why not do the following:
int userNum = Integer.valueOf(yourCharHere).
Update
If I understood your comment correctly the your 'X' in the snippet below is defined by the user
first_char = userNum.charAt(X);
If I get you right you have a problem because you dont know how long the input of the user is. Instead of assigning the individual numers to variables I would do the following:
//Parsing your String into a int
int userNum = Integer.valueOf(yourUserInputHere);
Arraylist singleDigits = new ArrayList()<>;
//This goes through all digits of your number starting with the last digits
while (userNum > 0) {
singleDigits.add( userNum % 10);
userNum = userNum / 10;
}
//Reverses your list of digits
Collections.reverse(singleDigits);
Example input: 13467
your List should look like: [1],[3],[4],[6],[7]
This enables you to get the single digits by calling:
singleDigits.get(0) -> [1];
singleDigits.get(3) -> [6];
...
I hope that helps
First create sets that are containing odd/even/zero numbers:
Set<Integer> odds = "13579".chars().boxed().collect(Collectors.toSet());
Set<Integer> evens = "02468".chars().boxed().collect(Collectors.toSet());
Set<Integer> zero = "0".chars().boxed().collect(Collectors.toSet());
Then get an input from the user
Scanner scan = new Scanner(System.in);
System.out.println("Choose a number:");
String number = scan.next();
scan.close();
Parse number character by character to find out how many digits are matching each set:
long numberOfOdds = number.chars().filter(odds::contains).count();
long numberOfEvens = number.chars().filter(evens::contains).count();
long numberOfZeros = number.chars().filter(zero::contains).count();
Finally, display the result:
System.out.println("There are " + numberOfEvens + " even numbers, " + numberOfOdds + " odd numbers, and " + numberOfZeros + " zeros in ");
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
boolean isAnInteger = false;
while (isAnInteger)
{
if (digit >= 10)
{
System.out.println("Please enter an integer: ");
}
else
{
System.out.println("Correct! " + digit + " is an integer!");
}
}
}
I'm currently taking AP Computer Science and I'm curious as to how to solve this (albeit basic) issue. I'm aware that "while" loops continue whatever is in their respective curly brackets when a condition in their parenthesis continues to be a met.
When I tried setting the while condition to while (digit >= 10), it resulted in an infinite loop (correct me, but it is due to the fact that if the user inputs a digit of 10 or greater, the condition will KEEP being met and continue infinitely). So, I tried setting the while condition to some boolean value, and an if nested inside with the prior condition. Now, when the user enters 10, nothing happens after, and the program ends.
How do I write the above code so that the System will continue printing "Please enter an integer:" if the condition (of inputting 10 or greater and the opposite) continues to be met?
There is a basic "poor design" issue that the variable isAnInteger has a scope wider than needed (it lives past the last line that needs it).
The "correct" approach is loop that contains the logic that determines "integerness" of the input and doesn't leave variables in scope when the loop ends, other than the captured input in digit of course.
Next, you want to separate the concerns of capturing input with checking it, so first create a method that gets a digit:
private static int readNumber(Scanner in) {
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
in.nextLine(); // you must clear the newline char from the buffer
return digit;
}
Next, write a simple while() loop that keeps reading until it gets good input:
int digit = 10; // bad input
while (digit > 9) {
digit = readNumber(in);
}
Putting it all together with the final message:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int digit = 10; // initialize with "bad" input
while (digit > 9) {
digit = readNumber(in);
}
System.out.println("Correct! " + digit + " is an integer!");
}
private static int readNumber(Scanner in) {
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
in.nextLine(); // you must clear the newline char from the buffer
return digit;
}
This approach makes the code much easier to read and understand.
Also notice how there is no repeated code (such as the line asking for a digit, or reading input).
The main conceptual piece here is that you don't update your value anywhere inside of your loop. Because it does not update, it will always remain the value it was when it entered the loop (that is, digit >= 10 will remain true until the program stops running).
You must update your values inside of your loop.
However, there's another concept you're missing: you're guaranteed to run the loop at least once, so you should take advantage of the do...while loop instead.
Note that I make use of nextLine() to avoid any wonky nextInt() issues.
(Oh, by the way: any number you're looking for is an integer. You should communicate that you're looking for an integer less than 10 instead.)
System.out.print("Please enter a digit: ");
int digit = Integer.parseInt(in.nextLine());
boolean isAnInteger;
do {
if (digit >= 10) {
System.out.println("Please enter an integer: ");
digit = Integer.parseInt(in.nextLine());
isAnInteger = false;
} else {
System.out.println("Correct! " + digit + " is an integer!");
isAnInteger = true;
}
} while (isAnInteger);
Yes, Makoto has it right.
You never update your values inside the while loop. In your original case, when you just wanted to keep printing out Please enter an integer: , you never ask for an input right after that line. Your original digit value will continue to be greater than or equal to 10, and will keep the loop going.
Even with your current code, you will still run into an infinite loop if your digit value is less than 10. Notice how the boolean isAnInteger is independent of whether your digit is less than 10.
The best way to fix this is by using something like this:
in = new Scanner(System.in);
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
while (digit >= 10)
{
System.out.println("Please enter an integer: ");
digit = in.nextInt();
}
System.out.println("Correct! " + digit + " is an integer!");
What this does is it keeps checking to see if digit is greater than or equal to 10. If so, it will continue to ask the user for an input. If at any time during the iteration of the loop the user enters a value less than 10, it will not execute the next iteration, and leaves the loop. It will then execute the last println.
However, if the first input is less than 10, it will skip the while loop and execute the println at the bottom.
If you want to use a boolean like you did, you can do it in such a manner:
in = new Scanner(System.in);
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
bool isAnInteger = true;
if (digit >= 10)
isAnInteger = false;
while (!isAnInteger) // checks if digit is not an integer
{
System.out.println("Please enter an integer: ");
digit = in.nextInt();
if !(digit >= 10)
isAnInteger = true;
}
System.out.println("Correct! " + digit + " is an integer!");
Makoto's way of using a do while loop is probably better, although this may be a better way of visualizing it (since you used a while loop).
The instructions are: "Ask the user for the following information, in this order:
A terminating value (real number). The user will enter this value again later, to indicate that he or she is finished providing input.
A sequence of real numbers. Keep asking for numbers until the terminating value is entered.
Compute and output the smallest and second-smallest real number, in that order. It is possible for the smallest and second-smallest numbers to be the same (if the sequence contains duplicate numbers)."
I uploaded my code and the grading software gave me a zero saying the program is not consistent with the assignment, however, when testing my code it runs just as required for the assignment. Any feedback as to why this may happen would be appreciated.
This is my code:
public class TwoSmallest
{
public static void main (String[] args)
{
double terminator;
System.out.print ("Please enter a terminating value: ");
terminator = IO.readDouble();
double lowest1;
double lowest2;
System.out.println("Please enter sequence of numbers:");
lowest1 = IO.readDouble();
while (lowest1 == terminator)
{
IO.reportBadInput();
lowest1 = IO.readDouble();
}
lowest2 = IO.readDouble();
while (lowest2 == terminator)
{
IO.reportBadInput();
lowest2 = IO.readDouble();
}
double input;
do
{
input = IO.readDouble();
if (input < lowest1)
{
if(lowest2 < lowest1)
lowest2 = lowest1;
lowest1 = input;
}
else if (input < lowest2)
lowest2 = input;
}while (input != terminator);
System.out.println("RESULT: " + lowest1);
System.out.println("RESULT: " + lowest2);
}
}
Here are the two scenarios which are not handled by your solution :
For suppose you have given the sequence of numbers 3,7,1 the result of your code is 1 and 7 not 1 and 3.
It is because you are not changing lowest2 value when input < lowest1.
If your input is 3,1,7 where first number is lowest1, second number is lowest2 and then input variable value is 7 then the condition (input < lowest1) is false, so there will be no swapping of lowest1 and lowest2 values and the result will be 3 and 1 instead of 1 and 3.
I want to write a java program that can check if the UPC code is valid or not by using only 'nested while loops' and 'branching: if-else'. here is the formula to check if the UPC is valid:
From left to right, add the digits in the odd-numbered positions
(starting the count from 1) and multiply the result by 3.
From left to right, add the digits in the even-numbered positions to the total
computed in step 1
Take the result from step 2 and compute the
remainder when divided by 10 (result modulo 10). If the remainder
is not zero, subtract this remainder from 10 to get the check digit.
If the remainder is zero, then the check digit should be 0.
Note: the code is keep asking until it receive blank input.
I had input the numbers but it show nothing so what should i do, thank!
Scanner in = new Scanner(System.in);
System.out.println("Enter a UPC (enter a blank line to quit): ");
String upc = in.nextLine();
while (upc.length() <12 && upc.length()>0) {
int even= Character.getNumericValue(upc.charAt(0))+Character.getNumericValue(upc.charAt(2))+Character.getNumericValue(upc.charAt(4))+Character.getNumericValue(upc.charAt(6))+Character.getNumericValue(upc.charAt(8))+Character.getNumericValue(upc.charAt(10));
int odd= Character.getNumericValue(upc.charAt(1))+Character.getNumericValue(upc.charAt(3))+Character.getNumericValue(upc.charAt(5))+Character.getNumericValue(upc.charAt(7))+Character.getNumericValue(upc.charAt(9))+Character.getNumericValue(upc.charAt(11));
int sum= even*3+odd;
int cd= Character.getNumericValue(upc.charAt(11));
if (sum%10 !=0) {
int sub= 10-(sum%10);
if (sub==cd) {
System.out.println("Check digit should be: " +sub);
System.out.println("Check digit is: "+ cd);
System.out.println("valid");
System.out.println("Enter a UPC (enter a blank line to quit): ");
upc= in.nextLine();
}
else {
System.out.println("Check digit should be: " +sub);
System.out.println("Check digit is: "+ cd);
System.out.println("not valid");
System.out.println("Enter a UPC (enter a blank line to quit): ");
upc= in.nextLine();
}
}
}
if (upc.length()==0) {
System.out.println("Goodbye");
}
It is a very easy fix to get it to run. But you still have a lot of code to add so it loops, and also accounts for the user entering a blank string or a string that is not 12 characters.
The easy fix, so it runs, is as follows.
Your even and odd variables are switched. Saying charAt(0) is a odd number. So switch those 2 variable names around.
On the even variable you do not need to add Character.getNumericValue(upc.charAt(11)). charAt(11) is the check digit, and does not need to be accounted for when adding.
In order to start the while loop you need to make it "upc.length() <= 12", currently your while loop is only working if the string is less than 12, which is incorrect.
So as for now, this code below will allow your code to run, but remember you have a little ways to go so it functions as you want it to, if you need help just ask.
import java.util.Scanner;
public class UPC_Check {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a UPC (enter a blank line to quit): ");
String upc = in.nextLine();
while (upc.length() <= 12 && upc.length()>0) {
int odd= Character.getNumericValue(upc.charAt(0))+Character.getNumericValue(upc.charAt(2))+Character.getNumericValue(upc.charAt(4))+Character.getNumericValue(upc.charAt(6))+Character.getNumericValue(upc.charAt(8))+Character.getNumericValue(upc.charAt(10));
int even= Character.getNumericValue(upc.charAt(1))+Character.getNumericValue(upc.charAt(3))+Character.getNumericValue(upc.charAt(5))+Character.getNumericValue(upc.charAt(7))+Character.getNumericValue(upc.charAt(9));
int sum= odd*3+even;
int cd= Character.getNumericValue(upc.charAt(11));
if (sum%10 !=0) {
int sub= 10-(sum%10);
if (sub==cd) {
System.out.println("Check digit should be: " +sub);
System.out.println("Check digit is: "+ cd);
System.out.println("valid");
System.out.println("Enter a UPC (enter a blank line to quit): ");
upc= in.nextLine();
}
else {
System.out.println("Check digit should be: " +sub);
System.out.println("Check digit is: "+ cd);
System.out.println("not valid");
System.out.println("Enter a UPC (enter a blank line to quit): ");
upc= in.nextLine();
}
}
}
if (upc.length()==0) {
System.out.println("Goodbye");
}
}
}
What I'm trying to accomplish is the following...
Asks user for number and check to see if number provided by user input is a 7 digit integer.
If it's a string, throw InputMismatchException and ask again for the number. Is there an easy way to accomplish this other than using regex and provided that the number is in the form 1234567? The other problem is if I input a value such as 12345678, it gets rounded due to int, so how do avoid this.
int number = 0;
try {
number = scan.nextInt(); // Phone Number is 7 digits long - excludes area code
} catch(InputMismatchException e) {
System.out.println("Invalid Input.");
number = validateNumber(number, scan);
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
// Method checks to see if the phone number provided is 7 digits long
// Precondition: the number provided is a positive integer
// Postcondition: returns a 7 digit positive integer
public static int validateNumber(int phoneNumber, Scanner scan) {
int number = phoneNumber;
// edited while((String.valueOf(number)).length() != 7) to account for only positive values
// Continue to ask for 7 digit number until a positive 7 digit number is provided
while(number < 1000000 || number > 9999999) {
try {
System.out.print("Number must be 7 digits long. Please provide the number again: ");
number = scan.nextInt(); // reads next integer provided
} catch(InputMismatchException e) { // outputs error message if value provided is not an integer
System.out.println("Incorrect input type.");
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
}
return number;
}
A valid telephone number is not necessarily an integer (Containing a + sign for country codes for example). So use a String instead.
Simple example with basic regex (7 digits, not validating country codes etc.):
public class Test {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String telephoneNumber = stdin.nextLine();
System.out.println(Pattern.matches("[0-9]{7}", telephoneNumber));
}
}
Here is working example along the lines of your original idea.
public int GetvalidNumber(Scanner scan) {
int number = 0;
while(true) {
try {
System.out.print("Enter a 7 digit number: ");
number = scan.nextInt();
if (number > 0 && Integer.toString(number).length() == 7)
break;
} catch(InputMismatchException e) {
scan.nextLine();
System.out.println("Invalid input: Use digits 0 to 9 only");
continue;
}
System.out.println("Invalid input: Not 7 digits long");
}
return number;
}