Separate the digit in an Integer (User-Input) - java

How do I enter a digit like '23423' and output it like '2 3 4 2 3'? And how do I make it so that user cannot enter less or more than 5-digits?
(Your help would be appreciated. I just need hints from you guys since I'm learning Java. Looking forward to learn something new.)
This is what I have so far:
Scanner input = new Scanner(System.in);
int value1, value2, value3, value4, value5;
System.out.print("Enter a number: ");
value1 = input.nextInt();
System.out.print("Enter a number: ");
value2 = input.nextInt();
System.out.print("Enter a number: ");
value3 = input.nextInt();
System.out.print("Enter a number: ");
value4 = input.nextInt();
System.out.print("Enter a number: ");
value5 = input.nextInt();
System.out.printf(" %d " + " %d " + " %d " + " %d " + " %d\n ", value1, value2, value3, value4, value5);

It can be redone with a loop: make the loop read the input 5 times and, each time, put the i-th read value at the i-th position of an array.
Then, to print it, you can just use a for loop that prints each element of the array.

If you really want them to enter a single 5 digit number, you're going to have to do validation on the users input and then give an error if the input isn't valid. If the requirements are such that the first digit of your 5 digit number should never be zero, you can just get an int and then check if it is greater than 9999 and less than 100000. Otherwise take it as a string and check the length, then turn it into an integer once you have validated it.

The most appropriate solution seem to me a while loop where you build a string and add a space. In the aftermath of the while processing you should eliminate the last space. Something like the following should fit your needs. I have used the apache commons project, but you also utilize your own class.
Scanner scanner = new Scanner(System.in);
String str = "";
while (scanner.hasNext()) {
String next = scanner.next();
if (next.equals("E")) {
break;
}
if (NumberUtils.isNumber(next)) {
for (int i = 0; i < next.length(); i++) {
str += Integer.valueOf(next.substring(i, i + 1)) + " ";
}
}
}
str = str.substring(0, str.length() - 1);
System.out.println("your number: " + str);
With "E" you can exit the loop.

Related

How would I check If two user inputs only contains numbers(calculator program), I keep getting a runtime error

Hi I'm still new to java and I would like to know how to check if the user only input numbers and not letters my problem comes in when I had to parse the input from string to double to be able to add decimals together in the console. But when I googled to see how to check if my input is only numbers I had to take in a string input that gives me *2 inputs(hope I'm making sense).Is there maybe a easier version to do this or am I missing something.
public class javaCalculator {
public static void main(String[] args){
//initializing two scanners for numbers and operations and creating 3 variables
Scanner numbers = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double number1;
double number2;
String operator;
//getting user input for the type of operations and numbers they want to enter
System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = operation.next();
//My program didn't want to take decimals, so I had to parseDouble which takes the input as a string and then
//converts(parse) it to a double which then makes my program run with decimal numbers
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
number1 = Double.parseDouble(numbers.nextLine());
System.out.print("Enter your second number: ");
String num2 = numbers.nextLine();
number2 = Double.parseDouble(numbers.nextLine());
boolean check1 = num1.matches("[0-9]+");
boolean check2 = num2.matches("[0-9]+");
if (check1 == true && check2 == true){
System.out.println("...");
}else {
System.out.println("Only enter numbers not letters.");
}
//Using if else statements to check what operation was chosen above and then depending on
//that choice(+, -, *, /) printing a suitable answer to console
//Creating a calculation variable to use in the writing to a file
String calculation;
if (operator.equals("+")){
calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
System.out.println(calculation);
}else if (operator.equals("-")){
calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
System.out.println(calculation);
}else if (operator.equals("*")){
calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
System.out.println(calculation);
}else if (operator.equals("/")){
calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
System.out.println(calculation);
}else{
calculation = operator + ":" + " Is not a valid operator!";
System.out.println(calculation);
}
Your code is trying to read the same number twice:
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
number1 = Double.parseDouble(numbers.nextLine());
What you should do is read the number as a string, confirm that it is a number and then parse it only if it matches.
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
boolean check1 = num1.matches("[0-9]+");
if(check1){
number1 = Double.parseDouble(num1);
}
else{
//Error handling
}
Alternatively you can simply try to parse the string directly and catch the exception i.e.
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
try{
number1 = Double.parseDouble(num1);
} catch(NumberFormatException e){
//Error handling
}
Your approach is OK. Although Scanner lib provides the nextDouble() method I recommend using the regular expression control you are using. Even though there are some little things to fix:
You are parsing (convert from String to double) first, and then checking format. If for example, the user enters a letter your program will fail when parseDouble tries to convert the String to double. So, read the String from the input, apply the match control, and if there is no Error then parse.
Your regular expression is matching any String that has 1 or more numbers. For example, the input Hello1 will match because there is at least one number. Then the parse will fail because Hello1 is not a valid number. You have to use a regular expression that matches only numbers. This expression will look like this: "^[0-9]+$"
The ^ character means that the expression must match at the beginning of the line, and the $ character force that the expression match at the end of the line. In other words, this expression should have numbers from the beginning to the end of the string. It would be a good thing to add a .trim() (num1.trim().matches("[0-9]+");) to delete any extra white space at the beginning or at the end.
The third recommendation is that if you don't want to use decimals may be Double type is not the proper data type to use. Double can represent decimals. The proper type should be Integers.
number1 = Integer.parseInt(num1);
#christopher When you raise error you are printing a message but the program keeps running. That's why you get the Error commented on #Turamarth solution comment

Reverse a line that has multiple values

I am working on a program that allows the user to input an integer, double, character, and a string. I have used variables to store the numbers in I am using BlueJ as my IDE, and my question is how I can reverse a system.out.println line that has variables in it?
Here is my code below:
import java.util.Scanner;
import java.lang.String;
public class Lab1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Entering a integer
int money = 0;
System.out.println("Enter an integer:");
money = input.nextInt();
//entering a double
double cost = 10;
System.out.println("Enter a double:");
cost = input.nextDouble();
//Entering a character
char a;
System.out.println("Enter a character:");
a = input.next().charAt(0);
//Entering a string
System.out.println("Please enter a string:");
String string = input.next();
System.out.println();
//Single line separated by spaces
int num = money;
double price = cost;
char b = a;
String text = string;
System.out.println("Single line:");
System.out.print(num + " " + price + " " + b + " " + text);
//Values in reverse
System.out.println();
System.out.println();
System.out.println("Values in reverse:");
}
}
Note: I am using BlueJ for this, and I have tried reversing the variables but, I couldn't.
My output:
Enter an integer:
45
Enter a double:
98.32
Enter a character:
a
Please enter a string:
welcome
Single line:
45 98.32 a welcome
The reverse of '45 98.32 a welcome' should be:
Welcome a 98.32 and 45.
Thank you and have a great day.
System.out.println("Values in reverse:");
System.out.print(text + " " + b + " " + price + " " + num)
For this simple question, I thought you need to change the order of output then it would be fine?
Anyway, if this is not your expected output, do tell me so.
In case this is what you are looking for, reverse() method is for the StringBuilder class: String class does not have reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder which meant you can only reverse the string output rather than the println in Java.

Java. Turning integer values into String using the scanner

I have created a program that uses the Scanner to ask the user for int values until they insert -1 which makes the program to stop receiving numbers. After doing so, it will add all the values entered by the user. This is my code so far:
public static void main(String[] args)
{
int sum = 0, value, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (-1 to quit): ");
value = scan.nextInt();
String string = Integer.toString(value);
while (value != -1)
{
count = count + 1;
sum = sum + value;
System.out.print("Enter an integer (-1 to quit): ");
value = scan.nextInt();
string = Integer.toString(value);
}
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
{
System.out.println("Number entered: " + string + ",");
System.out.println ("The sum is " + sum);
}
}
I want the output to look like this:
Entered numbers: 1,2,3,4,5 //example of number the user might enter
The sum is 15
I wanted to use a String for it to give me the sets of entered numbers, but it only gives me the last entered value. Which is -1 because that is the number that has to be entered to stop the program.
How can I out this problem?
In your
while(value != -1){
...
string = Integer.toString(value);
}
you are replacing string value with new one, so old value is lost. You should add new value to previously stored one. So your code may look like
string = string + "," + value;
You should also place this code before handling value which will be -1.
BTW, when you will learn more about Java you will know that each time you call
string + "," + value
new String is being created. Such string will need to copy content of other chunks. which may be very inefficient in case of long strings. To optimize this we can use StringBuilder and append new parts to it in loop.
In Java 8 we can also use StringJoiner which can automatically add prefixes, delimiters and suffixes for us.
Simply use string += "," + Integer.toString(value); This will give you a comma separated list of all the values you have entered. Your current statement string = Integer.toString(value); causes the variable string to be reset to the string representation of "value" for every iteration.
Check this code.
public static void main(String[] args)
{
int sum = 0, value, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (-1 to quit): ");
value = scan.nextInt();
StringBuilder sb = new StringBuilder();
while (value != -1)
{
if(sb.length() == 0){
sb.append(value);
}else{
sb.append(","+value);
}
count = count + 1;
sum = sum + value;
System.out.print("Enter an integer (-1 to quit): ");
value = scan.nextInt();
}
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
{
System.out.println("Number entered: " + sb.toString());
System.out.println ("The sum is " + sum);
}
}

Parse int, double, and String from a String in Java

I have to do an assignment in my Java class using the Scanner method to input an integer (number of items), a string (name of the item), and a double (cost of the item). We have to use Scanner.nextLine() and then parse from there.
Example:
System.out.println("Please enter grocery item (# Item COST)");
String input = kb.nextLine();
The user would input something like: 3 Captain Crunch 3.5
Output would be: Captain Crunch #3 for $10.5
The trouble I am having is parsing the int and double from the string, but also keeping the string value.
First of all, split the string and get an array.
Loop through the array.
Then you can try to parse those strings in array to their respective type.
For example:
In each iteration, see if it is integer. Following example checks the first element to be an integer.
string[0].matches("\\d+")
Or you can use try-catch as follow (not recommended though)
try{
int anInteger = Integer.parseInt(string[0]);
}catch(NumberFormatException e){
}
If I understand your question you could use String.indexOf(int) and String.lastIndexOf(int) like
String input = "3 Captain Crunch 3.5";
int fi = input.indexOf(' ');
int li = input.lastIndexOf(' ');
int itemNumber = Integer.parseInt(input.substring(0, fi));
double price = Double.parseDouble(input.substring(li + 1));
System.out.printf("%s #%d for $%.2f%n", input.substring(fi + 1, li),
itemNumber, itemNumber * price);
Output is
Captain Crunch #3 for $10.50
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();//take the message from the command line
String temp [] = message.split(" ");// assign to a temp array value
int number = Integer.parseInt(temp[0]);// take the first value from the message
String name = temp[1]; // second one is name.
Double price = Double.parseDouble(temp[2]); // third one is price
System.out.println(name + " #" + number + " for $ " + number*price ) ;

Inputting a number then reversing it

Ok so I wrote a program which asks user to input a number and then reverse it. I was successful in it however the program does not reverses numbers that end with a 0. for example if i enter 1234 it will print out 4321 however if i input 1200 it will only output 21. I tried converting the number that is to become output into string. Please help me understand where I am doing it wrong. Just remember I am a beginner at this :). Below is my code.
import java.util.*;
public class ReverseNumber
{
public static void main (String [] args)
{
Scanner n = new Scanner(System.in);
int num;
System.out.println("Please enter the number");
num = n.nextInt();
int temp = 0;
int reverse = 0;
String str = "";
System.out.println("The number before getting reversed " + num);
while (num != 0)
{
temp = num % 10;
reverse = reverse*10 + temp;
num = num/10;
str = Integer.toString(reverse);
}
//String str = Integer.toString(reverse);
System.out.println("The reversed number is " + str);
}
}
You're storing your reversed number as an int. The reverse of 1200 is 0021, but that's just 21 as an int. You can fix it by converting each digit to a string separately.
The problem is that you're calculating the reversed value as a number and, when it comes to numbers, there is no difference between 0021 and 21. What you want is to either print out the reversed value directly as you're reversing it or build it as a string and then print it out.
The former approach would go like this:
System.out.print("The reversed number is ");
while (num != 0)
{
System.out.print(num % 10);
num = num / 10;
}
System.out.println();
The latter approach would go like this:
String reverse = "";
while (num != 0)
{
reverse = reverse + Integer.toString(reverse);
num = num / 10;
}
System.out.println("The reversed number is " + reverse);
The latter approach is useful if you need to do further work with the reversed value. However, it's suboptimal for reasons that go beyond the scope of this question. You can get more information if you do research about when it's better to use StringBuilder instead of string concatenation.
I actually found this way really interesting, as this is not how I usually would reverse it. Just thought to contribute another way you could reverse it, or in this case, reverse any String.
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
int num = n.nextInt();
System.out.println("The number before getting reversed is " + num);
String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = sNum.length()-1; i >= 0; i--)
{
sNumFinal += sNum.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
If you wanted to take this further, so that you can enter "00234" and have it output "43200" (because otherwise it would take off the leading zeros), you could do:
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
String num = n.next(); // Make it recieve a String instead of int--the only problem being that the user can enter characters and it will accept them.
System.out.println("The number before getting reversed is " + num);
//String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = num.length()-1; i >= 0; i--)
{
sNumFinal += num.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
And of course if you want it as an int, just do Integer.parseInt(sNumFinal);
The reason the two zero is being stripped out is because of the declaration of temp and reverse variable as integer.
If you assigned a value to an integer with zero at left side, example, 000001 or 002, it will be stripped out and will became as in my example as 1 or 2.
So, in your example 1200 becomes something like this 0021 but because of your declaration of variable which is integer, it only becomes 21.
import java.util.Scanner;
public class Reverse {
public static void main(String args[]){
int input,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
in.close();
}
}

Categories