Try-Catch option does not run in Java - java

I am trying to write a Decimal & Binary converter in Java. I am trying to use try & catch option for error handling. Such as, if any one input "a" as binary number, it will print "Wrong Input". I have used parse and try-catch for this function. But it is not working. I am trying to find out the problem, but I am failed to find it. Could anyone help me in this code? When I write "1" for binary to decimal conversion, it goes to the end of the code.
The whole code is here:
package binary.with.decimal;
import java.util.Scanner;
public class RiaJava {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int binaryp = 0;
int n;
int base = 2;
int result = 0;
int multiplier = 1;
System.out.println("1.Binary to Decimal \n 2.Decimal to Binary");
System.out.println("Enter Your Option Number:");
n = scan.nextInt();
switch (n) {
case 1:
System.out.println("Input Binary Number:");
String binary = scan.nextLine();
scan.close();
try {
binaryp = Integer.parseInt(binary);
}
catch (NumberFormatException e) {
System.out.println("Wrong Input!!!");
}
while (binaryp > 0) {
int residue = binaryp % base;
binaryp = binaryp / base;
result = result + residue * multiplier;
multiplier = multiplier * 10;
}
System.out.println("Decimal....." + result);
break;
case 2:
System.out.println("Input Decimal Number:");
int decimal = scan.nextInt();
scan.close();
while (decimal > 0) {
int residue = decimal % base;
decimal = decimal / base;
result = result + residue * multiplier;
multiplier = multiplier * 10;
}
System.out.println("Binary....." + result);
break;
default:
System.out.println("you have selected wrong option number");
break;
}
}
}

scan.nextLine() should be scan.next()
nextLine() doesn't wait for user input, but reads the remaining buffer until the next end of line.

Related

Java: How to get back to the main method after using other methods

I'm fairly new to Java and the problem I am having is that this code compiles, but does not run after the hexadecimal conversion; it instead just ends after the method hexCharToDecimal. I can't reuse method main and I'm not sure how to call the method intreverse and actually have it run. Is there a way to get back into main or do I have to call intreverse somewhere?
import java.util.Scanner;
public class Homework4 {
public static void main(String[]args) {
// Sum and average of a set of intergers entered by the user
// First we will declare some variables
int userInput = 1;
int positives = 0;
int negatives = 0;
int sum = 0;
int numCount = 0;
Scanner input = new Scanner(System.in);
// Will start a while loop that will stop when user enters 20 integers
while ((numCount <= 20)) {
System.out.println("Please enter a nonzero integer or enter 0 to finish ");
userInput = input.nextInt();
if (userInput == 0) {
break;
} else if (userInput > 0) {
positives += 1;
numCount += 1;
sum = sum + userInput;
} else if (userInput < 0) {
negatives += 1;
numCount += 1;
sum = sum + userInput;
} else
System.out.println("Error, please enter an integer");
continue;
}
double average = (sum / numCount);
System.out.println("The sum of the entered integers is " + sum);
System.out.println("The average of the enetered integers is " + average);
System.out.println("There are " + positives + " positive integers and " + negatives + " negative integers");
// Convert Hexadecimal number to decimal
// Ask the user to input a string of 5 digits or less in hex
System.out.println("Please enter a hexadecimal number of up to 5 characters");
String hex = input.next();
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
}
// Now we will create the method to convert to decimal
public static int hexToDecimal(String hex) {
int decimal = 0;
for (int i = 0; i < hex.length(); i++) {
char hexcharacter = hex.charAt(i);
decimal = decimal * 16 + hexCharToDecimal(hexcharacter);
}
return decimal;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F') // check to see if there is any letters in the string
return 10 + ch - 'A';
else
return ch - '0';
}
// Print entered integer in reverse
public static void intreverse(String[]args) {
// Ask user for an integer to be reversed
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer to be reversed");
int number = input.nextInt();
reverse(number); // Method to be called
}
// Will now state our method
public static void reverse(int number) {
// use a while loop to get each digit
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
}
}
}
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
Will always run once because it is not enclosed in any sort of loop. If you want it to run again when the second case is called then enclose it in a while(true) loop and have a break statement in the first case where you want it to stop execution.

Creating a calculator but can't exit

I need help with my coding. I am practicing again with my java programming and today I am creating a calculator that has the same function as the real calculator but again I run into errors and unable to figure out again.
Okay, the way I wanted my calculator to works is instead of getting line by line input from the user like this:-
In code output
Enter Number: 1
Enter Operator (+,-, /, *, ^ (Power) or s (Square): +
Enter Number: 2
Ans: 3
I wanted it to calculate when the user press enter like this:-
The Output that I want
enter number: 1+2*4
Ans: 12
So they can add as many long numbers as they want before they hit enter calculate. The users are supposed to be able to reset the number to when using the calculator while in the loop of the calculation.
at the beginning of the code, it will ask the user for an input to continue or exit the calculator. Then if continue it will run the calculation. The calculator will be looping until the users press E to exit the calculator and if exit it will exit the code.
This is where I have errors. First, I can't figure out how to break from the loop inside the looping calculator and second at the beginning of the code when the user press E it was supposed to exit the calculator but it didn't. The third error is when the user using the square to calculate I want it to get straight to show the answer instead of asking another number.
and I want to simplify the code in public static void main(String[] args)for the calculation part. Is it possible to put the switch case in method and call it inside the main? or do you have a suggestion on how to simplify the calculation part?
Please help me:(
public class TestingCalculator {
public static void main(String[] args){
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
String a = ans.next();
activateCalc = a.charAt(0);
while (activateCalc != 'E' || activateCalc != 'e') {
Scanner input = new Scanner(System.in);
System.out.print("Enter number: ");
String n =input.next();
numA = Double.parseDouble(n);
while (calculator = true) {
//User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); //User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA,numB);
break;
case '-':
answer =subtract(numA,numB);
break;
case '*':
answer = multiply(numA,numB);
break;
case '/':
answer = divide(numA,numB);
break;
case '^':
answer = power(numA, numB);
break;
case 's':
case 'S':
answer = Math.pow(numA, 2);
break;
}
//The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator: ");
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
}
}
ans.close();
}
//Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}
}
Instead of trying to identify the problems with your application, I decided to focus on producing a program that works the way you want (with the input you specified). The code was a little big, but I tried to leave it well commented for you to understand what I did. I know that some things may still be a little confusing, so I will simulate running the program to try to make it clearer how it works.
Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestingCalculator
{
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Evaluates a mathematical expression.
*
* #param line Mathematical expression. This line cannot have blank
* spaces
* #return Result of this mathematical expression
*/
public static String calc(String line)
{
while (!hasOnlyNumbers(line)) {
// Checks if line has parentheses
if (line.contains("(")) {
// Get index of the most nested parentheses
int parentheses_begin = line.lastIndexOf("(");
int parentheses_end = line.substring(parentheses_begin).indexOf(")");
String ans = calc(line.substring(parentheses_begin+1, parentheses_end));
// Replaces content of parentheses with the result obtained
if (line.length()-1 >= parentheses_end+1)
line = line.substring(0,parentheses_begin)+ans+line.substring(parentheses_end+1);
else
line = line.substring(0,parentheses_begin)+ans;
}
// Checks if line has potentiation operator
else if (line.contains("^")) {
int opIndex = line.indexOf("^");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = power(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has square operator
else if (line.contains("s")) {
int opIndex = line.indexOf("s");
String n1 = extractFirstNumber(line, opIndex);
double ans = square(Double.valueOf(n1));
line = calc(parseLine(line, n1, opIndex, ans));
}
// Checks if line has multiplication operator
else if (line.contains("*")) {
int opIndex = line.indexOf("*");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = multiply(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has division operator
else if (line.contains("/")) {
int opIndex = line.indexOf("/");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = divide(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has sum operator
else if (line.contains("+")) {
int opIndex = line.indexOf("+");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = add(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
// Checks if line has subtraction operator
else if (line.contains("-")) {
int opIndex = line.indexOf("-");
String n1 = extractFirstNumber(line, opIndex);
String n2 = extractSecondNumber(line, opIndex);
double ans = subtract(Double.valueOf(n1), Double.valueOf(n2));
line = calc(parseLine(line, n1, n2, opIndex, ans));
}
}
// Returns line only when it has only numbers
return line;
}
/**
* Checks if a line contains only numbers.
*
* #param line Line to be analyzed
* #return If a line contains only numbers
*/
private static boolean hasOnlyNumbers(String line)
{
return line.matches("^[0-9.]+$");
}
/**
* Given a mathematical expression, replaces a subexpression for a value.
*
* #param line Mathematical expression
* #param n1 Number to the left of the subexpression operator
* #param n2 Number to the right of the subexpression operator
* #param opIndex Operator index of the subexpression
* #param ans Value that will replace the subexpression
* #return New mathematical expression with the subexpression replaced
* by the value
*/
private static String parseLine(String line, String n1, String n2, int opIndex, double ans)
{
int lenFirstNumber = n1.length();
int lenSecondNumber = n2.length();
if (line.length()-1 >= opIndex+lenSecondNumber+1)
return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+lenSecondNumber+1);
return line.substring(0, opIndex-lenFirstNumber)+ans;
}
/**
* Given a mathematical expression, replaces a subexpression for a value.
*
* #param line Mathematical expression
* #param n1 Number to the left of the subexpression operator
* #param opIndex Operator index of the subexpression
* #param ans Value that will replace the subexpression
* #return New mathematical expression with the subexpression replaced
* by the value
*/
private static String parseLine(String line, String n1, int opIndex, double ans)
{
int lenFirstNumber = n1.length();
if (line.length()-1 >= opIndex+2)
return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+2);
return line.substring(0, opIndex-lenFirstNumber)+ans;
}
/**
* Extracts the first number from an operation. <br />
* <h1>Example:<h1> <br />
* <b>Line:</b> 1+2*3 <br />
* <b>opIndex:</b> 3 <br />
* <b>Return:</b> 2 <br />
*
* #param line Mathematical expression
* #param opIndex Index of the operator to which the number to be
* extracted belongs to
* #return Number to the left of the operator
*/
private static String extractFirstNumber(String line, int opIndex)
{
StringBuilder num = new StringBuilder();
int i = opIndex-1;
while (i>=0 && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
num.append(line.charAt(i));
i--;
}
// Reverses the result, since the number is taken from the end to the
// beginning
num = num.reverse();
return num.toString();
}
/**
* Extracts the second number from a math operation. <br />
* <h1>Example:<h1> <br />
* <b>Line:</b> 1+2*3 <br />
* <b>opIndex:</b> 3 <br />
* <b>Return:</b> 3 <br />
*
* #param line Mathematical expression
* #param opIndex Index of the operator to which the number to be
* extracted belongs to
* #return Number to the right of the operator
*/
private static String extractSecondNumber(String line, int opIndex)
{
StringBuilder num = new StringBuilder();
int i = opIndex+1;
while (i<line.length() && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
num.append(line.charAt(i));
i++;
}
return num.toString();
}
// Method for the operators.
private static double add(double numA, double numB)
{
double answer = numA + numB;
return answer;
}
private static double subtract(double numA, double numB)
{
double answer = numA - numB;
return answer;
}
private static double multiply(double numA, double numB)
{
double answer = numA * numB;
return answer;
}
private static double divide(double numA, double numB)
{
double answer = numA / numB;
return answer;
}
private static double power(double numA, double numB)
{
int answer = (int) Math.pow(numA, numB);
return answer;
}
private static double square(double num)
{
int answer = (int) Math.pow(num, 2);
return answer;
}
//-------------------------------------------------------------------------
// Main
//-------------------------------------------------------------------------
public static void main(String[] args) throws IOException
{
char option;
String inputLine = "";
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
option = input.readLine().charAt(0);
while (option != 'E' && option != 'e') {
// Gets user input
System.out.print("Enter mathematical expression: ");
inputLine += input.readLine();
// Processes input
inputLine = inputLine.replaceAll(" ", "");
inputLine = inputLine.replaceAll("S", "s");
// Evaluates input
System.out.println("Evaluating...");
String ans = TestingCalculator.calc(inputLine);
// Displays answer
System.out.println("Ans: "+ans);
// Checks if the user wants to continue running the program
System.out.print("Press E to Exit the calculator: ");
inputLine = input.readLine();
if (inputLine.length() > 0)
option = inputLine.charAt(0);
}
input.close();
}
}
Output
Enter mathematical expression: (1+2*4)/3
Evaluating...
Ans: 3.0
Output 2
Enter mathematical expression: 1+2*9/3
Evaluating...
Ans: 7.0
Desk checking
Input: (1+2*4)/3
calc( (1+2*4)/3 )
not hasOnlyNumbers( (1+2*4)/3) ) ? true
( (1+2*4)/3) ) contains '(' ? true
int parentheses_begin = 0
int parentheses_end = 6
String ans = calc( 1+2*4 )
calc( 1+2*4 )
not hasOnlyNumbers( 1+2*4 ) ? true
( 1+2*4 ) contains '(' ? false
( 1+2*4 ) contains '^' ? false
( 1+2*4 ) contains 's' ? false
( 1+2*4 ) contains '*' ? true
int opIndex = 3
int n1 = 2
int n2 = 4
String ans = n1 * n2 = 2 * 4 = 8
line = calc( 1+8 )
calc( 1+8 )
not hasOnlyNumbers( 1+8 ) ? true
( 1+8 ) contains '(' ? false
( 1+8 ) contains '^' ? false
( 1+8 ) contains 's' ? false
( 1+8 ) contains '*' ? false
( 1+8 ) contains '/' ? false
( 1+8 ) contains '+' ? true
int opIndex = 1
int n1 = 1
int n2 = 8
String ans = n1 + n2 = 1 + 8 = 9
line = calc( 9 )
calc( 9 )
not hasOnlyNumbers( 9 ) ? false
return 9
line = 9
not hasOnlyNumbers( 9 ) ? false
return 9
line = 9
not hasOnlyNumbers( 9 ) ? false
return 9
ans = 9
(9-1 >= 6+1) ? true
line = 9/3
not hasOnlyNumbers( 9/3 ) ? true
( 9/3 ) contains '(' ? false
( 9/3 ) contains '^' ? false
( 9/3 ) contains 's' ? false
( 9/3 ) contains '*' ? false
( 9/3 ) contains '/' ? true
int opIndex = 1
String n1 = 9
String n2 = 3
double ans = 9 / 3 = 3
line = calc( 3 )
calc( 3 )
not hasOnlyNumbers( 3 ) ? false
return 3
line = 3
not hasOnlyNumbers( 3 ) ? false
return 3
Some observations
No checks are made to see if the user-provided input is valid
It is important to maintain the order of operations that are verified in the calc method, in order to maintain precedence between operators (exponentiation / radication must be done first, followed by multiplication / division and finally addition / subtraction operations)
I had problems with the Scanner class, so I used BufferedReader to read the input
Square operation must be done as follows: <num>s or <num>S
Hope this helps. If you don't understand something, tell me I can explain it to you.
try below code and one suggestion try to handle the negative scenarios as well.
public static void main(String[] args) {
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
Scanner input = new Scanner(System.in);
activateCalc = input.next().charAt(0);
while (true) {
if (activateCalc != 'E' && activateCalc != 'e') {
System.out.print("Enter number: ");
String n = input.next();
numA = Double.parseDouble(n);
// User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); // User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA, numB);
break;
case '-':
answer = subtract(numA, numB);
break;
case '*':
answer = multiply(numA, numB);
break;
case '/':
answer = divide(numA, numB);
break;
case '^':
answer = power(numA, numB);
break;
case 'S':
case 's':
answer = Math.pow(numA, 2);
break;
default:
answer = 0;
}
// The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator or Y to continue : ");
activateCalc = input.next().charAt(0);
if(activateCalc != 'E' && activateCalc != 'e')continue;
}
System.out.println("Thank you for using the calculator. By :) ");
ans.close();
break;
}
}
// Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}
This question requires debugging details so here we go:
Your code does not seem to compile because of the error:
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
where you had to use comparison == operator instead of assignment =.
Similar issue is in your inner loop while (calculator = true) - and there's a warning that this value is never used - but this does not affect much.
You cannot exit the loop because you never check the input for exit, it should be:
System.out.println("Press E to Exit the calculator: ");
activateCalc = input.next().charAt(0);
But even if you updated activateCalc, you'd get into endless loop anyway because of the error in this condition while (activateCalc != 'E' || activateCalc != 'e') -- even if user presses 'e', or 'E' this condition is always true.

Positive and Negative numbers in String

I have to make a program that allows the user to enter integer numbers until he press '0'. The program has to print:
1)The total number of the entered numbers
2) The number of the positive ones
3) The average of the positive ones
4) The number of the negative ones
5) The sum of the negatives
So far, all I could do is make the "enter untill '0' is pressed" and find the number of the entered numbers, which is a lot for me and my programing skills. I am having troubles trying to find out if the number is positive or negative. Probably I am not comparing them right, so I would love if I get a little help from someone advanced.
Here's my code so far:
import java.io.*;
class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
EnteredNumbers++;
str = br.readLine();
} while(!str.equals("0"));
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Firstly as pointed out Integer.parseInt is used in java to convert from String to int.
Secondly you need to have a extra variable to store and accumulate the total of positive numbers too. I have added a try-catch exception block to handle errors.
Here is a code for reference.
import java.io.*;
public class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
int PositiveSum = 0; // Added extra variable
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
try{
do {
EnteredNumbers++;
str = br.readLine();
int num = Integer.parseInt(str);
if (num>0)
{
Positive++;
PositiveSum+=num;
}
else if (num<0)
{
Negative++;
NegativeSum+=num;
}
} while(!str.equals("0"));
AveragePositive = (double)PositiveSum/(double)Positive;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
catch (java.lang.NumberFormatException e)
{
System.out.println("Wrong format");
}
}
}
Output if there are no errors
Enter '0' to quit.
Enter Numbers:
1
5
5
-5
-5
0
You have have entered 5 numbers!
You have have entered 3 Positive numbers!
The Average of the Positive Numebers is 3.6666666666666665!
You have have entered 2 Negative numbers!
The Sum of the Negative numbers is -10!
check by parsing String to int
Integer.parseInt(str)>0 //positive number
Integer.parseInt(str)<0 //negative
do {
EnteredNumbers++;
str = br.readLine();
int number= Integer.parseInt(str);
if(number>0){ //do positive stuffs}
else if(number<0){//do negative stuffs}
} while(!str.equals("0"));
Hope the below code achieves what you want to do
import java.io.*;
class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
double AveragePositive = 0;
double PositiveSum = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
EnteredNumbers++;
str = br.readLine();
if(Integer.parseInt(str) > 0){
Positive++;
PositiveSum = PositiveSum + Integer.parseInt(str);
AveragePositive = PositiveSum/Positive;
}
if(Integer.parseInt(str) < 0){
Negative++;
NegativeSum = NegativeSum + Integer.parseInt(str);
}
} while(!str.equals("0"));
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Create a list and keep adding the numbers into List. You should do something like:
List<Integer> numberList = new ArrayList<Integer>();
do {
str = br.readLine();
int number = Integer.parseInt(str);
} while(number != 0);
And then use for loop to do count like:
int negativeNumberSum = 0;
int positiveNumberSum = 0;
int positiveNumberCounts = 0;
for (int i =0; i<numberList.size(); i++) {
if (numberList.get(i) >= 0) {
positiveNumberSum += numberList.get(i);
positiveNumberCounts ++;
} else {
negativeNumberSum += numberList.get(i);
}
}
//print average of positive as positiveNumberSum /(double) positiveNumberCounts if positiveNumberCounts != 0
//print average of positive as negativeNumberSum / (double)(numberList.size() - positiveNumberCounts) same if (numberList.size() - positiveNumberCounts) != 0
//print positive count as positiveNumberSum and same for negative.
//
Try using Integer.parseInt() to get an int from your string str, and checking to see if the integer is < 0 (negative) or > 0 (positive)
I have added an extra variable called PositiveSum to assist with the AveragePositive calculation.
In order to perform this calculation, you need to ensure the value is an Integer so I have added the parse statement.
class Nums {
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
int EnteredNumbers = -1;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
int PositiveSum = 0;
double AveragePositive = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
EnteredNumbers++;
str = br.readLine();
int number = Integer.parseInt(str);
if(number<0) {
Negative++;
NegativeSum += number;
} else if(number>0) {
Positive++;
PositiveSum += number;
}
} while(!str.equals("0"));
AveragePositive = PositiveSum / EnteredNumbers;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numebers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Change your do-while loop: it is using Strings, not integers:
do {
EnteredNumbers++;
num = sc.nextInt();
} while(num != 0);
Also, you need to import the scanner utility:
import java.util.Scanner;
Don't use a BufferedReader, but use:
static Scanner sc = new Scanner(System.in);
Also, you would want to use a checker for your positive and negative numbers inside your do-while loop:
if(Integer.parseInt(num)<0) { Negative++; }
else { Positive++; }
I've also added a try-catch statement to handle an error if someone doesn't enter an int:
try {
num = sc.nextInt();
}
catch(Exception e) {System.out.println("Invalid integer"); System.exit(0); }
I added a little bit of code that takes the 0 off when it prints the numbers, as I realise it will include 0 when you type it in to exit.
Change your class statement to public, it's just programming:
public class Nums {
Also, I add a negative-number counter in the main code, and an averager.
Here is the complete code, to avoid confusion:
import java.io.*;
import java.util.Scanner;
public class prime {
static Scanner sc = new Scanner(System.in);
public static void main(String args[])
{
int EnteredNumbers = 0;
int Positive = 0;
int Negative = 0;
int NegativeSum = 0;
double AveragePositive = 0;
int num = 0;
int PosTotal = 0;
System.out.println("Enter '0' to quit.");
System.out.println("Enter Numbers: ");
do {
try {
num = sc.nextInt();
}
catch(Exception e) {System.out.println("Invalid integer!"); System.exit(0); }
if(num<0) { Negative++; NegativeSum += num; }
if(num>0){ Positive++; PosTotal += num; }
EnteredNumbers++;
} while(num != 0);
AveragePositive = PosTotal / Positive;
EnteredNumbers -= 1;
System.out.println("You have have entered "+EnteredNumbers+ " numbers!");
System.out.println("You have have entered "+Positive+ " Positive numbers!");
System.out.println("The Average of the Positive Numbers is "+AveragePositive+ "!");
System.out.println("You have have entered "+Negative+ " Negative numbers!");
System.out.println("The Sum of the Negative numbers is "+NegativeSum+ "!");
}
}
Hope it helps!
Note I have trial-tested it, and it works brilliantly. If you have any errors with this please tell me :)

Java: Exception Help Char and Int

Ok all, I'm stuck again with this code.
I need to put in an Exception that won't allow the user to input 0 (because you can't divide later by 0) and the user cannot enter alpha characters. I am trying to display the message, disregard the wrong input, and loop to allow the user to try again until they put in the acceptable number.
Here is what I have:
package exceptionhandler;
/**
*
* #author Sarah
*/
import java.util.Scanner;
public class ExceptionHandler {
/**
* #param args
* the command line arguments10 10
*/
public static void main(String[] args) throws NumberFormatException {
Scanner in = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("Please enter ten values:");
System.out.println();
// Input the data into array from the user.
double[ ] digit = new double[11];
int sum = 0;
//Declare an array
try
{
for (int i = 1; i < digit.length; i++) {
System.out.print("Value " + i + ": ");
digit[i] = (double)in.nextInt();
sum += (int)digit[i];
}
catch (NumberFormatException e)
{
System.out.println("You Can Only Enter Numbers!");
}
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println();
System.out.println("Would you like to divide the values?");
System.out.println("Yes or No to Exit the Program");
String a = input.next();
if(a.equalsIgnoreCase("yes")){
double [] divisionResult = new double[digit.length / 2];
//Division array declared
for (int i = 1; i < digit.length; i += 2)
{
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult [i / 2] = result;
System.out.println(result);
}
}
else if(a.equalsIgnoreCase("no")){
System.exit(0);
}
}
}
I have tried declaring the throw exception and then tried a try..catch. But it is not recognizing catch and try talking to one another... so I know I am doing something wrong, but I can't see where it should go.
Is the Exception in the right place? Should I have done something else? Is my exception written wrong? How can I then move on to prevent the input of zero as well- rethrow?
Help?
It supposed to be InputMismatchException not NumberFormatException to catch an exception upon entering characters and you need to check for 0 if the user input 0 and deduct 1 the current index of the for-loop to let the user try again.
sample:
for (int i = 1; i < digit.length; i++) {
try {
System.out.print("Value " + i + ": ");
digit[i] = (double) in.nextInt();
sum += (int) digit[i];
if(digit[i] == 0.0)
{
System.out.println("You cant enter 0: try again");
--i;
}
} catch (InputMismatchException e) {
System.out.println("You Can Only Enter Numbers!");
--i;
in.nextLine(); //to consume the character
}
}
result:
Please enter ten values:
Value 1: 0
You cant enter 0: try again
Value 1: asd
You Can Only Enter Numbers!
Value 1:

Need help making a random math generator

What I am supposed to do is this:Write a program that gives the user 10 random math problems, asks for the answer each time, and then tells the user if they were right or wrong. Each problem should use 2 random numbers between 1 and 20, and a random operation (+, -, *, or /). You will need to re-randomize the numbers for each math problem. You should also keep track of how many problems they get right. At the end, tell the user how many problems they got right and give them a message based on their result. For example, you may say “good job” or “you need more practice.”
So far I am at a loss
import java.util.Scanner;
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
if (operator == 1)
System.out.println("+");
if (operator == 2)
System.out.println("-");
if (operator == 3)
System.out.println("*");
if (operator == 4)
System.out.println("/");
}
}
I mostly need to know how to turn these random numbers and operators into a problem, and how to grade each question to see if they are wrong.
Well, what you need to add is:
to count answers:
a variable that counts correct answers (increment it every time the user answers correctly);
a variable to store current correct answer;
a variable to store current user answer (refresh it every next problem, no need to store it forever, cause in your case only statistics is needed);
a function (let it be called e.g. gradeTheStudent() ) which uses several conditions to decide what to print out according to number of correct answers;
to create a problem:
put problem generation and answer evaluation into a cycle, which repeats 10 times;
in your switch (i.e. when you choose operators) also calculate the correct answer:
switch(operator){
case 1: {
operation = "+";
correctResult = number1 + number2;
break;
}
case 2: ....
case 3: ....
case 4: ....
default: break;
}
don't forget to check if the user entered a number or something else (you could use either an Exception or a simple condition).
So, a "pseudocode"solution for your problem would look something like this:
String[] reactions = ["Awesome!","Not bad!","Try again and you will get better!"]
num1 = 0
num2 = 0
operator = NIL
userScore = 0
userAnswer = 0
correctAnswer = 0
def function main:
counter = 0
for counter in range 0 to 10:
generateRandomNumbers()
correctAnswer = generateOperatorAndCorrectAnswer()
printQuestion()
compareResult()
gradeStudent()
def function generateRandomNumbers:
# note that you have already done it!
def function generateOperatorAndCorrectAnswer:
# here goes our switch!
return(correctAnswer);
def function printQuestion:
print "Next problem:" + "\n"
print num1 + " " + operator + " " + num2 + " = " + "\n"
def function compareResult(correctAnswer):
# get user result - in your case with scanner
if(result == correctAnswer)
print "Great job! Correct answer! \n"
userScore++
else print "Sorry, answer is wrong =( \n"
def function gradeStudent (numOfCorrectAnswers):
if(numOfCorrectAnswers >= 7) print reactions[0]
else if(numOfCorrectAnswers < 7 and numOfCorrectAnswers >= 4) print reactions[1]
else print reactions[2]
General advice: don't try to solve the problem all at once. A good approach is to create small functions, each doing its unique task. The same with problem decomposition : you just should write down what you think you need in order to model the situation and then do it step by step.
Note: as far as I can see from your current function, you are not familiar with object oriented programming in Java. This is why I am not providing any tips about how great it would be to use classes. However, if you are, then please let me know, I will add info to my post.
Good luck!
For example you can use something like that:
public class Problem {
private static final int DEFAULT_MIN_VALUE = 2;
private static final int DEFAULT_MAX_VALUE = 20;
private int number1;
private int number2;
private Operation operation;
private Problem(){
}
public static Problem generateRandomProblem(){
return generateRandomProblem(DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE);
}
public static Problem generateRandomProblem(int minValue, int maxValue){
Problem prob = new Problem();
Random randomGen = new Random();
int number1 = randomGen.nextInt(maxValue + minValue) + minValue;
int number2 = randomGen.nextInt(maxValue + minValue) + minValue;
prob.setNumber1(number1);
prob.setNumber2(number2);
int operationCode = randomGen.nextInt(4);
Operation operation = Operation.getOperationByCode(operationCode);
prob.setOperation(operation);
return prob;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public Operation getOperation() {
return operation;
}
public void setNumber1(int number1) {
this.number1 = number1;
}
public void setNumber2(int number2) {
this.number2 = number2;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
}
And another class for holding operations:
public enum Operation {
PLUS,
MINUS,
MULTIPLY,
DIVIDE;
public double operationResult(int n1, int n2) {
switch (this) {
case PLUS: {
return (n1 + n2);
}
case MINUS: {
return n1 - n2;
}
case MULTIPLY: {
return n1 * n2;
}
case DIVIDE: {
return n1 / n2;
}
}
throw new IllegalArgumentException("Behavior for operation is not specified.");
}
public static Operation getOperationByCode(int code) {
switch (code) {
case 1:
return PLUS;
case 2:
return MINUS;
case 3:
return MULTIPLY;
case 4:
return DIVIDE;
}
throw new IllegalArgumentException("Operation with this code not found.");
}
}
But you not must throw IllegalArgumentException, there are another options for handling unexpected arguments.
Printout the numbers and the operation , read the user input using file IO , and perform your logic of keeping a track of answered questions
Code :
public class SS_Un5As4 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
if (operator == 1)
operation="+";
if (operator == 2)
operation="-";
if (operator == 3)
operation="*";
if (operator == 4)
operation="/";
System.out.println("Question "+number1+operation+number2);
}
}
Keep a track of result and compare with the user input and verify its right or wrong
public static void main(String[] args) throws IOException{
int number1 = (int)(Math.random()* 20) + 1;
int number2 = (int)(Math.random()* 20) + 1;
int operator = (int)(Math.random()*4) + 1;
String operation = null;
int result=0;
if (operator == 1){
operation="+";
result=number1+number2;
}
if (operator == 2) {
operation="-";
result=number1-number2;
}
if (operator == 3){
operation="*";
result=number1*number2;
}
if (operator == 4){
operation="/";
result=number1/number2;
}
System.out.println("Question "+number1+operation+number2);
String result1 = new BufferedReader(new InputStreamReader(System.in)).readLine();
if(result==Integer.parseInt(result1))
System.out.println("Right");
else
System.out.println("Wrong");
}
Since I do not want to hand you a full solution to this problem, and you seem to have some knowledge in the Java language I will just write down how I would continue/change what you have as a start.
First I would store the result in your operator if statements. Result is an int.
if (operator == 1) {
operation="+";
result=number1+number2;
}
After this I would print the math question and wait for the user to answer.
System.out.println("What is the answer to question: " +number1+operation+number2);
userResult = in.nextLine(); // Read one line from the console.
in.close(); // Not really necessary, but a good habit.
At this stage all you have to do is compare the result with the user input and print a message.
if(Integer.parseInt(userResult) == result) {
System.out.println("You are correct!");
} else {
System.out.println("This was unfortunately not correct.");
}
This solution is more or less psudo code and some error handling (if user enters test in the answer for example) is missing, also I would split it up into methods rather than have it all in main(). Next step would be to make it object oriented (Have a look at the answer from demi). Good luck in finalizing your program.
In regard to generating random math operations with +, -, * & / with random numbers your can try the following;
import java.util.*;
public class RandomOperations{
public static void main(String[] args){
Random `mathPro` = new Random();
//for the numbers in the game
int a = mathPro.nextInt(50)+1;
int b = mathPro.nextInt(50)+1;
//for the all the math operation result
int add = a+b;
int sub = a-b;
int mult = a*b;
int div = a/b;
//for the operators in the game
int x = mathPro.nextInt(4);
/*
-so every random number between 1 and 4 will represent a math operator
1 = +
2 = -
3 = x
4 = /
*/
if(x == 1){
System.out.println("addition");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(add);
}else if(x == 2){
System.out.println("subtraction");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(sub);
}else if(x == 3){
System.out.println("multiplication");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(mult);
}else{
System.out.println("division");
System.out.println("");
System.out.println(a);
System.out.println(b);
System.out.println(div);
}
//This os for the user to get his input then convert it to a numbers that the program can
//understand
Scanner userAnswer = new Scanner(System.in);
System.out.println("Give it a try");
int n = `userAnswer.nextInt();

Categories

Resources