the code below convert a decimal number to octal number. what i need is to have it to be able to display these message when the input is invalid and repeat the input process until a valid input in entered
"Enter a decimal number: -1
Input should not have any negative sign!
Enter a decimal number: -a
Input should not have any negative sign!
Input should not contain letters!
Enter a decimal number: -1.1
Input should not have any decimal point!
Input should not have any negative sign!
Enter a decimal number: -1.a
Input should not have any decimal point!
Input should not have any negative sign!
Input should not contain letters!
Enter a decimal number: 15 decimal 15 = octal 17"
import java.util.Scanner;
public class apple
{
public static void main(String args[])
{
Scanner sc = new Scanner( System.in );
System.out.print("Enter a decimal number: ");
int num =sc.nextInt();
int rem;
String str="";
int num1 = num;
while(num>0)
{
rem=num%8;
num=num/8;
str =rem+str;
}
System.out.println("decimal " + num1 + " = octal " + str);
}
}
thanks in advance.
boolean continueEntering = true;
while(continueEntering)
{
int num =sc.nextInt();
if(your condition failed){
//print whatever you want
continueEntering = true; //didnt got the out put so asking again
}else{
//input is valid no need to ask data again
continueEntering = false;
}
}
you need to pass a boolean value at the while loop. If the user has entered a invalid input you can make the boolean value true so that you can ask the input one more time. However i have stopped the program when user has entered a valid input. You can change that by reversing the value of the boolean.
Related
I need to write a program that requests and accepts three inputs from a user- a string, an int and a double.
The program should pass the inputs to a method that converts the string to its equivalent numeric value and adds this value to the sum of the remaining inputs. The program should display the result to the user.
The letter a is worth 1, b worth 2, all the way up to the letter z being worth 26.
If it contains a digit, the value of that character is the value of the digit itself, 0 is worth 0, 1 worth 1, all the way up to 9 worth 9.
Any other character in the string (for example: !$?*&^%) is worth 0.
What I have so far is in my code below
import java.util.Scanner;
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Please enter a string");
String input1 = myObj.nextLine();
if (!input1.matches("[a-zA-Z_]+!$?*&^%")) {
System.out.println("Invalid String");
}
else {
System.out.println("Please enter a integer");
}
int input2 = myObj.nextInt();
System.out.println("Please enter a double");
double input3 = myObj.nextDouble();
}
}
Sample output
Please enter a string: dad6!
Please enter an integer: 10
Please enter a decimal number: 2.5
Result is: 27.5
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
float charSum=0;
Scanner myObj = new Scanner(System.in);
System.out.println("Please enter a string");
String input1 = myObj.nextLine();
char[] arr=input1.toCharArray();
for(int i=0;i<arr.length;i++){
int ascii=(int)arr[i];
if(ascii>=97&&ascii<=122){
charSum=charSum+ascii-96; //for a-z
}
else if(ascii>=65&&ascii<=90){
charSum=charSum+ascii-64; //for A-Z
}
else if(ascii>=48&&ascii<=57){
charSum=charSum+ascii-48; //ascii for number
}else{
charSum=charSum+0; //ascii for special Character
}
}
System.out.println("Please enter a Integer");
int integerValue = myObj.nextInt();
charSum+=integerValue;
System.out.println("Please enter a Double");
Double doubleValue = myObj.nextDouble();
charSum+=doubleValue;
System.out.println(charSum);
}
}
here,I have taken string and find out the ascii value of each and subtracted 96 because the ascii value of a-> 97 .A->65 (so if a needs to be 1 it must be 97-96=1) and for special characters as you asked it to be 0 so added that to the sum variable.Since the double is also and input so the output can be either float or double .I have taken float.Hope this solution solves your query
https://www.onlinegdb.com/online_java_compiler can check the code on this compiler online.
I am writing a calculator program, where the user in the last input prompt writes the number of decimal points (1, 2 ,3...), that the output of for example sum of 2 numbers should have.
import java.util.Scanner;
import java.util.Formatter;
public class Lab01 {
public void start(String[] args) {
double cislo1;
double cislo2;
int operacia;
String decimal;
String dec;
Scanner op = new Scanner(System.in);
System.out.println("Select operation (1-sum, 2-dev, 3- *, 4- / )");
operacia = op.nextInt();
if (operacia >= 1 && operacia <= 4) {
if(operacia == 1) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number one:");
cislo1=input.nextDouble();
System.out.println("Enter number two:");
cislo2=input.nextDouble();
System.out.println("Enter number of decimal points");
decimal=input.nextLine();
dec="%."+decimal+"f";
Formatter fmt = new Formatter();
fmt.format(dec, cislo2);
System.out.println( fmt);
}
} else {
System.out.println("wrong!");
}
}
}
I have tried Formatter method for the decimal input but the error says" Conversion = '.' "
System.out.println("Enter number of decimal points");
decimal = input.nextLine();
dec = "%." + decimal + "f";
Formatter fmt = new Formatter();
fmt.format(dec, cislo2);
System.out.println(fmt);
Your variable decimal should be an int. So you should change the follow lines:
String decimal;
You should change to:
int decimal;
And:
decimal = input.nextLine();
You should change to:
decimal = input.nextInt();
Or, if you want to keep it as a String, you can add an extra input.nextLine(); before reading the number of decimals. It occurs because nextLine() consumes the line separator where you are reading your cislo2 variable and nextInt() will only read an int.
So here is my program:
// Creates a Scanner object that monitors keyboard input
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("How old are you? ");
int age = checkValidAge();
if (age != 0)
{
System.out.println("You are " + age + " years old");
}
}
public static int checkValidAge()
{
try
{
return userInput.nextInt(); // nextInt() receives the user input
}
catch (InputMismatchException e)
{
userInput.next(); // Skips the last user input and waits for the next
System.out.print("That isn't a whole number");
return 0;
}
}
When I enter a number with 3 decimal places, Java outputs it as an Integer:
If I input the number with 2 or more than 3 decimal points, then the program will know that input is not correct. So why does it ignore 3 decimal places and outputs it as an int?
Stream::nextInt reads an integer from a stream.
2,444 is an integer in your default locale (2,444 = 2444).
If you want to read a decimal number you need to use the Stream::nextDouble or another appropriate method.
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!
I'm trying to set up a do-while loop that will re-prompt the user for input until they enter an integer greater than zero. I cannot use try-catch for this; it's just not allowed. Here's what I've got:
Scanner scnr = new Scanner(System.in);
int num;
do{
System.out.println("Enter a number (int): ");
num = scnr.nextInt();
} while(num<0 || !scnr.hasNextLine());
It'll loop if a negative number is inputted, but if a letter is, the program terminates.
You can take it in as a string, and then use regex to test if the string contains only numbers. So, only assign num the integer value of the string if it is in fact an integer number. That means you need to initialize num to -1 so that if it is not an integer, the while condition will be true and it will start over.
Scanner scnr = new Scanner(System.in);
int num = -1;
String s;
do {
System.out.println("Enter a number (int): ");
s = scnr.next().trim(); // trim so that numbers with whitespace are valid
if (s.matches("\\d+")) { // if the string contains only numbers 0-9
num = Integer.parseInt(s);
}
} while(num < 0 || !scnr.hasNextLine());
Sample run:
Enter a number (int):
-5
Enter a number (int):
fdshgdf
Enter a number (int):
5.5
Enter a number (int):
5
As using try-catch is not allowed, call nextLine() instead
of nextInt(), and then test yourself if the String you got
back is an integer or not.
import java.util.Scanner;
public class Test038 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num = -1;
do {
System.out.println("Enter a number (int): ");
String str = scnr.nextLine().trim();
if (str.matches("\\d+")) {
num = Integer.parseInt(str);
break;
}
} while (num < 0 || !scnr.hasNextLine());
System.out.println("You entered: " + num);
}
}