This program is for computing the digits of an integer. So there is chances to enter the input by user may string("raju" whatever it may be), number(12334), combination(string & number i.e, 234dsd) and nothing(he doesn't enter anything), isn't it? There might be another chances too I don't know(If there is mention it here).Try out with various inputs and the problems here are when I entered number and nothing. If input is number "result not coming" cmd prompt not continuing further and input is nothing(not entered) if statement is not executing. when the cmd prompt goes like that?
//computing digits of integer.
import java.util.Scanner;
class Main
{
public static void main (String w[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a number");
String g=s.nextLine();
System.out.println("Entered value is"+g);
if(g==null)
{
System.out.println("Enter atleast one number");
}
else
{
try
{
int st=Integer.parseInt(g);
int sum=0;
while(st>=0)
{
int value=st%10;
st=st/10;
sum=value+sum;
}
System.out.println("the sum of digits: "+sum);
}catch (NumberFormatException nfe)
{
System.err.println("Invalid input. Enter only number...");
}
}
}
}
It is hard to understand you are asking here, but if you are asking you code is not trying again when the user inputs invalid input, the answer is that it is because your code has no loop to do that.
Repetition of something (in this case, the task of asking for input) generally requires a loop of some kind.
If you indented your code properly, this would probably be more obvious to you.
Try this one
//computing digits of integer.
import java.util.Scanner;
public class Main {
public static void main(String w[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
String g = s.nextLine();
System.out.println("Entered value is " + g);
try {
int st = Integer.parseInt(g);
int sum = 0;
while (st > 0) {
int value = st % 10;
st = st / 10;
sum = value + sum;
}
System.out.println("the sum of digits: " + sum);
} catch (NumberFormatException nfe) {
System.err.println("Invalid input. Enter only number...");
}
}
}
None of the answers so far explicitly mentioned the problem: There is an endless loop here:
int st=Integer.parseInt(g);
int sum=0;
while(st>=0)
{
int value=st%10;
st=st/10;
sum=value+sum;
}
because st never becomes negative when you start with a positive value.
Related
I am trying to get my code to prompt an Error Message whenever the user enters a decimal number/negative number and will continue to loop until a positive number greater than 0 is implemented.
This is what I have so far;
public static void numberFunctions()
{
System.out.println("Calculating a Factorial");
Scanner myScan= new Scanner (System.in);
System.out.println("Please enter the number you'd like to use: ");
int number = myScan.nextInt();
System.out.println(number);
if(number>0)
{
int factorial = 1;
int count;
for (count = number; count >=1; count --)
{
factorial = factorial * count;
System.out.print(count +" * ");
}
System.out.println(" = " + factorial);
}
else
{
System.out.println("ERROR! Please enter a positive number");
}
}
First you can create a method for example
public static int getInteger() {
}
In that method you can ask the user to enter an integer using a try catch block inside a while loop so that way if they enter a double or a String it will catch the Exception and ask the user to try to enter an integer again.
Once you figure that out you can call that method and check if the number returned is greater than 0.
Once you create this method you can always use it to ask for integers from the user.
Add a try/catch block while taking input.
try {
int number = myScan.nextInt();
}
catch(InputMismatchException e) {
System.out.println("Enter integer numbers only");
System.out.println(scanner.next() + " was not valid input.");
}
You are doing ok with the negative number checking part. However if the user enter an invalid string or a real number, this line of code will throw exception so we need to catch that error: int number = myScan.nextInt();
It is also a good practice to always close your Scanner after using it so we will put it in the finally part.
Here is my suggested code for you:
public static void numberFunctions()
{
System.out.println("Calculating a Factorial");
Scanner myScan= new Scanner (System.in);
System.out.println("Please enter the number you'd like to use: ");
try {
int number = myScan.nextInt();
if(number>0)
{
int factorial = 1;
int count;
for (count = number; count >=1; count --)
{
factorial = factorial * count;
System.out.print(count);
if (count != 1) {
System.out.print(" * ");
}
}
System.out.println(" = " + factorial);
}else {
System.out.println("ERROR! Please enter a positive number");
}
}catch(InputMismatchException ex) {
System.out.println("ERROR! Please enter a positive number");
}finally {
myScan.close();
}
}
First off, yes this a HW assignment. Having issues with recursive factorials in Java. Everything I'm finding on here and elsewhere already shows me what I've done is correct. However I'm having issues with an additional step. Basically what I need is the 1) User to enter a number 2) Factorial to be calculated 3) If user enters anything but a character or string (rather than an int) for an error message to come out 4) The question to repeat until user enters "0" to exit.
Steps 1 and 2 I have completed. I'm having issues with step 3. It seems like I am missing a return statement if the user enters anything but an int but I can't seem to figure out exactly what.
Here is code thus far:
import java.util.Scanner;
public class Recursive
{
public static void main(String[] args)
{
int number; // To hold a number
char letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
number = keyboard.nextInt();
//Display the factorial
System.out.println(number + "! is " + factorial(number));
}
private static int factorial(int n)
{
if (n == 0)
return 1; // Base Case
else if (n > 0)
return n * factorial(n-1);
else (!(n>0))
return
System.out.println(number + "is invalid");
}
}
After getting the user input, before doing factorial, we have to check if input is a number or not. We can use pattern. Check regular expression patterns to do that. After checking if it is a number or not, check if it is zero, if yes use exit (0) to come out of the program. If not do the factorial
while (true) {
// Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
int number = keyboard.nextInt();
if (Pattern.matches("\\d+", String.valueOf(number))) {
if (Integer.valueOf(number) == 0)
System.exit(0);
// Display the factorial
System.out.println(number + "! is " + factorial(number));
}
else
System.out.println("Error");
}
My answer is based on an assumption that your factorial function is working properly.In order to complete your step 3 and 4 you need to take input in a loop. In that loop, take input as string and parse it into integer, use try catch so that you can catch exception when a non-integer is given as input and you can prompt an error message.
public static void main(String[] args)
{
Integer number; // To hold a number
String letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
while(keyboard.hasNext()){
letter = keyboard.next();
try{
number = Integer.parseInt(letter);
if(number==0){
//Exiting
break;
}
int fact = factorial(number);
//Display the factorial
System.out.println(number + "! is " + fact);
System.out.print("Enter an integer to find the factorial: ");
}
catch(NumberFormatException e){
System.out.println("Invalid input please enter integers only");
}
}
}
Also your factorial function is having compilation issues currently. You need to fix it for proper functioning of your code.
My solution for recursive factorial using Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.*;
class Main {
public static String factorial(int n,String s){
if(n>0){
BigInteger fact = new BigInteger(s);
fact = fact.multiply(new BigInteger(n + ""));
return factorial(n-1,fact.toString());
}
else{
return s.toString();
}
}
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int n = Integer.parseInt(line);
if(n==0)
System.out.println("Factorial is 0");
else{
String s = factorial(n,"1");
System.out.println("Factorial is " + s);
}
}
}
the example of factorial using recursive in Java
public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter,
factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}
I looked through a bunch of other questions and online, but I can't find anything that answers this specifically. I'm trying to handle dealing with and determining valid input based on a Windows command line argument. As a sample, I was just seeing if an entered number was positive to be as easy as possible. The biggest issue, and what made me unable to find a specific answer, was I'm really trying to use recursion to make it keep asking until a valid input is entered, rather than just killing the program.
Algorithm:
If there is an argument provided and it's a positive integer
Display value
Otherwise
Until the argument is a positive number
Prompt for a positive integer
Display value
I wrestled with the code and eventually got this to work, but it seems really inefficient, repetitive and hacked together. At first, I had the while-loop inside the caught exceptions, but this allowed other things to slip through from the command line. How can I make this as efficient as possible and also prevent any logic errors or exceptions? What approach should I take with my algorithm when tackling this? Here's my code:
import java.util.Scanner;
public class Test
{
public static void main( String[] args )
{
String arg;
Scanner user_input = new Scanner(System.in);
int i = 0;
try {
arg = args[0];
i = Integer.parseInt(arg);
} catch( ArrayIndexOutOfBoundsException e ) {
arg = "";
} catch( NumberFormatException e2 ) {
arg = "";
}
while( i <= 0 )
{
System.out.print("Please type in a positive whole number. ");
arg = user_input.next();
try {
i = Integer.parseInt(arg);
} catch( NumberFormatException e2 ) {
System.out.print("That's a letter! ");
continue;
}
if( i <= 0 )
{
System.out.print("That's a negative. ");
}
}
System.out.println("Input is " + i);
}
}
Try this:
The code is quite lengthy this is because two separate try blocks are required; one for the command-line argument & the other for the argument provided via the scanner...
I had to create my own custom exception, "NegativeNumberException"...
import java.util.Scanner;
public class NegativeNumberException extends Exception{
NegativeNumberException(){
System.out.println(exceptionMessage);
}
String exceptionMessage = "Number must be positive";
static int num;
public static void main(String[] args) throws NegativeNumberException{
try
{
if(Integer.parseInt(args[0])<0){
throw new NegativeNumberException();
}
else{
int num = Integer.parseInt(args[0]);
System.out.println("Your number is: " + num);
}
}
catch(NumberFormatException ex){
System.out.println("That's not even a number.");
}
catch(NegativeNumberException ex){
ex.getMessage();
}
while(num==0){
try{
System.out.println("Enter a positive number:");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
if(num1<0){
throw new NegativeNumberException();
}
num = num1;
break;
}catch(Exception ex){
System.out.println("Positive number only, try again...");
}
}//End While
System.out.println("Your number is:" + num);
}
}
Input: (Command-line): lol
Output
(Console):That's not even a number
Enter a positive int
(Console input via Scanner): -4
(Console):Number must be positive
Positive number only, try again...
Enter a positive number:
(Console input via Scanner): 3
(Console):Your number is: 3
I modified your code so that it runs the way you want. Try using this:
public static void main( String[] args ) {
String arg;
Scanner user_input = new Scanner(System.in);
int numTries = 0, value = 0;
try {
numTries = Integer.parseInt(args[0]); // get max number of tries
} catch (ArrayIndexOutOfBoundsException e) {
arg = "";
} catch (NumberFormatException e2) {
arg = "";
}
// try 'numTries' times to read a valid number input
for (int i=numTries; i > 0; --i) {
System.out.print("Please type in a positive whole number: ");
arg = user_input.next();
try {
value = Integer.parseInt(arg);
} catch(NumberFormatException e2) {
System.out.println("That's a letter! ");
continue;
}
if (value <= 0) {
System.out.println("That's a negative. ");
}
break; // exit loop if number input found
}
System.out.println("Input is " + value);
}
This code has been tested on IntelliJ and it runs with no problems.
I am allowing the user to enter numbers via command line. I would like to make it so when the user enters more then one number on the command line at a time it displays a message asking for one number then press enter. then carries on.
here is my code. If someone could show me how to implement this I would appreciate it.
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
class programTwo
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size(); // added return statement
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
String inputs = scan.nextLine();
while (!inputs.matches("[qQ]") )
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
try{
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
catch (InputMismatchException e) {
System.out.println("Stop it swine! Numbers only! Now you have to start over...");
main(args);
return;
}
inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
}
As suggested in the comments to the question: Just do not scan the line you read for numbers, but parse it as a single number instead using Double.valueOf (I also beautified the rest of your code a little, see comments in there)
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
// we can use a for loop here to break on q and read the next line instead of that while you had here.
for (String inputs = scan.nextLine() ; !inputs.matches("[qQ]") ; inputs = scan.nextLine())
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
try{
myArr.add(Double.valueOf(inputs));
count++; //that'S even shorter than count += 1, and does the exact same thing.
System.out.println("Please enter another number or press Q for your average");
}
catch (NumberFormatException e) {
System.out.println("You entered more than one number, or not a valid number at all.");
continue; // Skipping the input and carrying on, instead of just starting over.
// If that's not what you want, just stay with what you had here
}
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
(Code untested, so there may be errors in there. Please notify me if you got one ;))
String[] numbers = inputs.split(" ");
if(numbers.length != 1){
System.out.println("Please enter only one number");
}
Hey guys so i've been trying to answer this question for hours:
Write a program that asks the user to input a set of floating-point values. When the
user enters a value that is not a number, give the user a second chance to enter the
value. After two chances, quit reading input. Add all correctly specified values and
print the sum when the user is done entering data. Use exception handling to detect
improper inputs.
I've tried a few different things but i always have the same problem. Once something that isn't a number is given as input, the program outputs the message prompting for another input however the chance is not given, that is to say after 1 incorrect input it prints that message and jumps straight to printing the sum. The best i could do is below i'm just not sure how to approach this problem. Any help is greatly appreciated.
import java.util.Scanner;
import java.util.InputMismatchException;
public class q6{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean firstChance = true;
boolean secondChance = true;
double sum = 0;
while (secondChance){
try{
while (firstChance){
try{
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
}
catch (InputMismatchException ex){
firstChance = false;
}
System.out.print("Please enter a number to continue or something else to terminate: ");
double input = in.nextDouble();
sum = sum + input;
firstChance = true;
}
}
catch (InputMismatchException e){
secondChance = false;
}
}
System.out.print("The sum of the entered values is " + sum);
}
}
i'm just not sure how to approach this problem
Pseudocode could be as follows:
BEGIN
MAX_INPUT = 2;
i = 0;
WHILE i < MAX_INPUT
TRY
num = GET_NUM();
CATCH
continue;
FINALLY
i++
END WHILE
END
Since the parsing of input to double is not successful, the scanner does not go past the given input. From javadoc Scanner
Scans the next token of the input as a double. This method will throw
InputMismatchException if the next token cannot be translated into a
valid double value. If the translation is successful, the scanner
advances past the input that matched.
Since the translation is not successful, it does not advance. So, in the catch block you could call in.next() to skip the token.
You could use an integer counter instead of the boolean variables firstChance and secondChance and do something like:
int attempts = 0;
while(attempts < 2) {
try {
//Get user input - possible exception point
//Print sum
} catch(InputMismatchException e) {
attempts++;
//Continue?
}
}
import java.util.*;
public class q6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double inputNumber, sum = 0.0;
int correctCount = 0, wrongCount = 0;
while(wrongCount <=1) {
System.out.println("Please enter a numeric floating value:");
try {
inputNumber = in.nextDouble();
correctCount++;
sum += inputNumber;
if(correctCount >= 2)
break;
} catch(InputMismatchException e) {
wrongCount++;
in = new Scanner(System.in);
continue;
}
}
System.out.println(sum);
}
}
You need to break your while loop when you encounter a "bad" input. Then, you'll need to set firstChance to true again, so you can access the second while, you also will need a counter that counts the number of the attempts (I named it chances):
int chances = 0;
while (secondChance){
firstChance = true;
try{
while (firstChance){
try{
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
}
catch (InputMismatchException ex){
chances ++;
in = new Scanner(System.in);
firstChance = false;
}
if(!firstChance && chances < 2)
break;
if(chances >= 2) {
System.out.print("Please enter a number to continue or something else to terminate: ");
double input = in.nextDouble();
sum = sum + input;
firstChance = true;
}
}
}
catch (InputMismatchException e){
secondChance = false;
}
}
As stated in my comment, in order to not deal with Scanner wrong read, it would be better to use Scanner#nextLine() and read the data as String, then try to parse it as double using Double#parseDouble(String) since this method already throws NumberFormatException and you can handle this error. Also, it would be better that your code could handle more than 1 request (if your teacher or somebody else asks to do this):
final int REQUEST_TIMES = 2;
double sum = 0;
for(int i = 1; i <= REQUEST_TIMES; i++) {
while (true) {
try {
if (i < REQUEST_TIMES) {
System.out.print("Please enter a number: ");
} else {
System.out.print("Please enter a number to continue or something else to terminate: ");
}
String stringInput = in.nextLine();
double input = Double.parseDouble(stringInput);
sum += input;
} catch (NumberFormatException nfe) {
System.out.println("You haven't entered a valid number.");
break;
}
}
}
The logic is to read the input once, if it is correct then display the sum, else read the input again and display the sum if the input is correct.
public class q6 {
static int trial = 0;
public static void main(String[] args) {
double sum = 0;
while (trial <= 2) {
Scanner in = new Scanner(System.in);
try {
trial++;
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
trial=3;
} catch (InputMismatchException ex) {
trial++;
if (trial == 4){
System.out.println("You have entered wrong values twice");
}
}
}
if (trial <= 3){
System.out.print("The sum of the entered values is " + sum);
}
}
The above program is just a rough idea, you can improve this to adapt to your need.