I've been doing java for 4 months, so I'm still an amateur. Just trying to get some hwk done. Can't seem to find the right tips for getting my denominator to function well by rejecting text data and zero while keeping in a loop with error messages. Another issue is the fact my quotient is 0.0 no matter what my numerator / denominator is. Lots of problems, any advice is appreciated. Directions are as follows:
--This program takes user input for a (int) numerator and
(int) denominator then computes and displays the (double) quotient.
--If the user enters text instead of number for the numerator, display an error message explaining the issue and keep user in a loop until the correct data is entered.
--If the user enters text or a zero instead of a number for the denominator, display an error message explaining the issue and keep user in a loop until the correct data is entered.
--Messages should be descriptive with respect to the issue.
public static void main(String[] args) throws Exception {
Scanner console = new Scanner(System.in);
int n1 = 0; //number 1
int n2 = 1; //number 2..
double r = (double) n1 / n2; //quotient
String n1Str = "Please enter a real number for the numerator";
String n2Str = "Please enter a real number greater than zero for the denominator";
String errMsg = "Please enter a real number.";
String notZero = "Denominator cannot equal zero."; // not all string msgs are used, just there in case i need them.
try {
n1 = getInteger(n1Str); // validates against alphabet
if (hasNextInt()) { // working
n1 = console.nextInt();
}
} catch (InputMismatchException ime) {
}
try {
n2 = getInteger2(n2Str); // trying to validate against alphabet & zero
if (hasNextInt()) { // not working though...
n2 = console.nextInt();
}
} catch (InputMismatchException ime) {
}
System.out.println("Fraction result is " + r);
}
public static int getInteger(String message) {
Scanner console = new Scanner(System.in);
int count = 0;
boolean isValidInteger = false;
do {
System.out.println(message);
if (console.hasNextInt()) {
isValidInteger = true;
count = console.nextInt();
} else {
console.nextLine();
}
} while (!isValidInteger);
return count;
}
public static int getInteger2(String message) {
Scanner console = new Scanner(System.in);
int count = 0;
boolean isValidInteger = false;
do {
System.out.println(message);
if (console.nextInt() != 0 || console.hasNextInt()) { // validates against zero but
isValidInteger = true; // can't get it to validate against text.
count = console.nextInt(); //tried switching statements and using && but get thrown into endless loop
}
} while (!isValidInteger);
return count;
}
private static boolean hasNextInt() {
return false;
}
}
You have lots of issues with your code.
For starters, you should have only one Scanner, that would exist throughout the lifespan of your application. There's no need to instantiate multiple scanners.
public class SomeClass {
private static Scanner console;
public static void main(String[] args) throws Exception {
console = new Scanner(System.in);
(...)
console.close();
}
}
Now lets look into your problematic getInteger2 method.
You should simple validate, as you do on your getIntegermethod, if the input is an integer. If it is, you process it; otherwise, you skip it using next() (not nextLine()) since you want to jump over the next complete token from this scanner.
public static int getInteger2(String message) {
int count = -1;
boolean isValidInteger = false;
do {
System.out.println(message);
if (console.hasNextInt()) {
count = console.nextInt();
if (count != 0) {
isValidInteger = true;
} else {
System.out.println("Denominator cannot equal zero.");
}
} else {
console.next();
}
} while (!isValidInteger);
return count;
}
Finally, your quotient is always being printed 0.0 since you're not updating its value before outputting it:
r = (double) n1 / n2;
System.out.println("Fraction result is " + r);
The fact that your quotient "r" is always 0.0 is because you initialize n1 to be 0 and n2=1; You should just declare the variables and initialize them down in your code; i.e when you want to get the values from the user.
It seems that you have two "main" problems in your code/logic...
Problem 1) You are not calculating r (your quotient) after you get the inputs.
So the lines:
} catch (InputMismatchException ime) {
}
System.out.println("Fraction result is " + r);
could be changed to something like:
} catch (InputMismatchException ime) {
}
r = (double) n1 / n2; //calculate the quotient
System.out.println("Fraction result is " + r);
Problem 2)
Your code:
do {
System.out.println(message);
if (console.nextInt() != 0 || console.hasNextInt()) { // validates against zero but
isValidInteger = true; // can't get it to validate against text.
count = console.nextInt(); //tried switching statements and using && but get thrown into endless loop
}
} while (!isValidInteger);
return count;
could be changed to something like this, if you don't want to change too much in your code:
do {
System.out.println(message);
try {
if ((count = console.nextInt()) != 0) {
isValidInteger = true;
}
} catch (InputMismatchException ime) {
return getInteger2(message);
}
} while (!isValidInteger);
return count;
so that only if the input in console is an int you read it with nextInt() and store it in count. In your code you would read the int with nextInt() and if it is an int you read it again with nextInt(), which causes the user to write in 2 ints as well as your issue that you read the int before checking that it is an int which causes the InputMismatchException to be thrown. In the code I sent you, if the read number is an int AND not 0 then it is returned, if it is 0 your loop runs again and if it isn't an int at all the the method is simply called again (see Recursion).
I hope this helps you understand the issues.
The best way, however, would probbaly be do redesign your code a bit.
Related
So my biggest problem is that I cannot seem to remember how to parse a string into an int so that I can idiot proof my code. My goal here is to find out if the user enters in a word instead of an int and then I can explain to them what an integer is. Can someone please help? I just need a simple list of parsing commands so that I can study them for use in the future, once there is a simple list I think I'll be able to figure all the others out from there.
import java.util.Scanner;
import java.util.*;
public class SelfTestNumberNine
{
public static void main(String[] args)
{
boolean test = false;
int num = 0;
int sum = 0;
int count = 0;
int pos = 0;
int neg = 0;
Scanner in = new Scanner(System.in);
while(!test)
{
num = 0;
System.out.print("Enter in an Integer Value: ");
String letta = in.next();
if(??parsing stuff goes here!!)
{
num = in.nextInt();
count++;
if(num > 0)
{
pos++;
sum = sum + num;
}
else if(num < 0)
{
neg++;
sum = num + sum;
}
else
{
test = true;
}
}
else
{
System.out.println("An Integer is a number that is positive or
negative,\nand does not include a decimal point.");
}
}//end while
System.out.println("Total: " + sum);
double avg = sum / count;
System.out.println("Average: " + avg);
}//end main
}//end class
Basically, the program asks the user to input integers, counts the number of positive and negatives, and prints out the total and average (Ignoring 0). The program ends when the user inputs a 0.
P.S. Thanks for your time!! ]:-)
If you want to ensure that the user has entered an int without throwing an exception if they don't you can use the hasNextInt() method:
System.out.println("Enter an int (0) to quit");
//While the user has not entered a valid int
while (!input.hasNextInt()) {
System.out.println("Please enter an integer: ");
//Consume the bad input
input.nextLine();
}
Which will loop until they enter a valid int. A sample run (- denotes user input):
Enter an int (0 to quit)
-No
Please enter an integer:
-Never!!
Please enter an integer:
-Ok ok fine
Please enter an integer:
-3
You can do this in two ways.
- Integer.parseInt()
- Integer.valueOf()
String myStr = "1";
int parsedInt = Integer.parseInt(myStr);
int valueOf = Integer.valueOf(myStr);
System.out.println("Parse Int: " + parsedInt);
System.out.println("Value Of: " + valueOf);
Note: You might get exception if the input is not parseable. NumberFormatException.
You can use a Boolean method and a try-catch to check if you can parse the string to an Integer.
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
import java.util.Scanner;
class Main {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int testNumber = userInput.nextInt();
do{
System.out.println(newNumber * 2);
newNumber++;
}while( testNumber < 1000000);
}
}
You need to update the number after you multiply it by 2:
newNumber = newNumber * 2;
System.out.println(newNumber);
Also you are using newNumber and testNumber and newNumber doesn't appear to be defined anywhere...
}while( ***testNumber***newNumber*** < 1000000);
You need to pick one because if you are updating newNumber but comparing testNumber in your loop you will have created an infinite loop.
The code you have shown shouldn't compile unless you are leaving something out of your post.
You have the right idea with your loop, but you have multiple problems with your variables.
Your first problem is that you read in a variable from the user - testNumber, but then you are (incorrectly) manipulating a completely different variable - newNumber.
Your second problem is that you are testing the unchanged variable as your stop condition.
You probably want your loop to be something like:
do {
testNumber = testNumber * 2;
System.out.println(testNumber);
} while(testNumber < 1000000);
You can also make a recursive method for it.
public int reachMillion(int num) {
if(num<=0)
return -1; // indicating it is not possible.
if(num>=1000000) // Base Condition denoting we have reached 1 million
return num;
return reachMillion(num*2); // recursive part to multiply by 2 until we reach 1 million
}
class Main {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int newNumber = 0;
do{
System.out.println("Enter a positive number: ");
try{
newNumber = userInput.nextInt();
}catch(Exception ignored){ }
System.out.println("");
}while(newNumber <= 0);
System.out.println("----- " + newNumber + " multiply by 2 ------");
while(newNumber <= 1_000_000){
System.out.print("2 * " + newNumber +" = ");
newNumber <<= 1;//in some compilers left shift is faster than multiply
System.out.println(newNumber);
}
}
#brso05 has done well describing what went wrong here. I'd like to offer a complete example:
import java.util.Scanner;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Please input a number: ");
int userInputNumber = userInputScanner.nextInt();
System.out.println();
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
Beware! That code does not handle any bad user input. For instance, if you give it 0, it will loop forever, and if you give it foo, it will crash. In case you want to handle all the edge cases of user input, this will do that:
import java.util.*;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
int userInputNumber;
//
while(true) {
System.out.print("Please input a number: ");
if (userInputScanner.hasNext()) {
// The user gave us something, but we don't know if it's a number
String rawUserInput = userInputScanner.next();
try {
userInputNumber = Integer.parseInt(rawUserInput);
// If that previous line runs, the user has given us an integer!
System.out.println();
if (userInputNumber > 0) {
// The user has given a valid number. Break out of the loop and multiply it!
break;
}
else {
// The user has given a bad number. Tell them why and ask again.
System.out.println("The number has to be greater than 0.");
}
}
catch (NumberFormatException exception) {
// The user has given us something, but it wasn't an integer
System.out.println();
System.out.println("That is not a number: " + exception.getMessage());
}
}
else {
// There is no input, so we can't do anything.
return;
}
}
// Done looping through user input
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
There is a tricky part of do-while loops. In that type of loops, do part is executed firstly. For the example below, although the input is already bigger than 1000000, it prints 1000001.
public void doWhileLoop() {
int num = 1000001;
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}
Therefore, it will be a good idea to use some guard-clauses (aka, if-statements) before doing something in do-while loops. Like,
public void doWhileLoop() {
int num = 1000001;
if(num >= 1000000) {
return;
}
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}
I'm trying to make a program that evaluates a mathematic equation that's written one character or value per line at a time. The user will enter alternating numbers and operators, line by line, terminating with a ‘.’. That means I'm not trying to evaluate from a single string (and assume input will always alternate between number and operator).
I don't know how to make it so that it keeps taking input until the user types ".'
I also am not sure how to keep the value continuously changing as the user types the formula and how to store that.
Sample input:
1
+
6
-
3
.
The solution to your equation is: 4
import java.util.Scanner;
class Evaluator {
static int add (int a, int b)
{
return a + b;
}
static int multiply (int a, int b)
{
return a * b;
}
static int divide (int a, int b)
{
return a / b;
}
static int subtract (int a, int b)
{
return a - b;
}
static int modulus (int a, int b)
{
return a % b;
}
public static void main(String [] args)
{
Scanner input = new Scanner (System.in);
int a,b,c;
System.out.println("Enter the equation:");
a = input.nextInt();
String c = input.next();
b = input.nextInt();
if (c.contains("+")) {
int result = add (a,b);
}
else if (c.contains("*")) {
int result = multiply (a,b);
}
else if (c.contains("/")) {
int result = divide (a,b);
}
else if (c.contains("-")) {
int result = subtract (a,b);
}
else if (c.contains("%")) {
int result = modulus (a,b);
}
else if (c.contains(".")) {
break;
}
System.out.print("The solution to your equation is: " + result);
}
}
Your code is very close, in that you use Scanner next() and nextInt() in the correct order (to match the input rules). Here a while(true) loop is added around the pair of inputs; either a user enter a '.' and the loop breaks, or the user enters an operator followed by the next number. The result is kept up to date by using it repeatedly in the various math operators.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int b, result;
System.out.println("Enter the equation:");
result = input.nextInt();
while (true) {
String c = input.next();
if (c.contains(".")) {
break;
}
b = input.nextInt();
if (c.contains("+")) {
result = add(result, b);
} else if (c.contains("*")) {
result = multiply(result, b);
} else if (c.contains("/")) {
result = divide(result, b);
} else if (c.contains("-")) {
result = subtract(result, b);
} else if (c.contains("%")) {
result = modulus(result, b);
}
}
input.close();
System.out.print("The solution to your equation is: " + result);
}
Here is a simple while loop you can use to get input from the user. I have a check if it's a digit or something else. You can use this skeleton to grab input from the user and exit when someone presses "."
Scanner input = new Scanner (System.in);
int a,b,currentTotal = 0;
String inputFromUser = "nothing";
while(!inputFromUser.equals("."))
{
inputFromUser = input.nextLine(); //grab line by line
if(inputFromUser.matches("\\d+")){
//parse the number and set it to a value like a...
System.out.println("You entered a number: " + inputFromUser);
}
else if(!inputFromUser.equals(".")){
//check if you have value and try to apply your number to your current total
System.out.println("You entered something other than a number: " + inputFromUser);
}
}
If the user enters a number, set a variable to that number, perhaps a
If the user enters something other than a number and not a period then check if the input is a valid operation with your provided logic and apply it like operatorMethod(a, currentTotal)
I am a beginner and i wrote a java program that allows you to enter n numbers and it displays the max, min and average only if the number -5 is entered, my program its not displaying correctly and i need some help. I want to use try/catch to catch errors when a string is entered instead integer.
import java.util.Scanner;
public class Average{
public static void main(String[]args){
System.out.print("Enter any integer numbers or -5 to quit:");
Scanner scan =new Scanner(System.in);
double avg = 0.0;
int number = -1;
double avg = 0.0;
double sum = 0;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
try {
while((scan.nextInt())!= -5)
{
if (count != 0) {
avg = ((double) sum) / count;
count++;
}
if (number > max){
max = number;
}
if(number < min){
min = number;
}
catch (InputMismatchException e) {
System.out.println("please enter only integer numbers");
System.out.println("Average : " + avg);
System.out.println("maximum : " + max);
System.out.println("minimum : " + min);
}
}
}
}
}
To get integer inputs in a loop, respond to an "exit" value, and guard against invalid inputs, I would use something like the template below.
Note that something critical that none of the answers so far has mentioned is that it is not good enough to simply catch InputMismatchException. You must also call your scanner object's nextLine() method to clear the bad input out of its buffer. Otherwise, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter integers or -5 to quit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == -5) {
done = true;
}
else {
// The input was definitely an integer and was definitely
// not the "quit" value. Do what you need to do with it.
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Enter integers or -5 to quit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: -5
Exiting...
You would probably want
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
inside the while loop because right now you are only checking the last read value(also, there's no need to up the counter outisde the loop(after you have read -5, btw, why -5?o.O).
Also, you would probably want the min/max values initialised this way, because if your min value is bigger than 0, your code outputs 0. Same goes if your max value is below 0:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
For the non-integer part: read up on exceptions and use a try-catch block to catch the InputMismatchException.
try {
//while(scan.nextInt) here
} catch (InputMismatchException e) {
//Do something here, like print something in the console
}
As someone else pointed out, if you want the average to not be truncated, cast sum to double: ((double) sum) / count.
Finally, but most important: try debugging it yourself before asking someone else.
Try this:
import java.util.Scanner;
public class Average {
static Scanner scan;
public static void main(String[] args) {
System.out.println("Enter any integer numbers or -5 to quit:");
scan = new Scanner(System.in);
int number = -1, sum = 0, count = 0;
int max = 0;
int min = 0;
while((number = scanNextInt()) != -5) {
count++;
sum = sum + number;
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
}
if(number == -5) {
try {
System.out.println("Average : " + (sum / count));
System.out.println("Maximum : " + max);
System.out.println("Minimum : " + min);
}catch(Exception e) {
//Error printing, so quit the program. Look below.
}
//Quit
System.exit(0);
}
scan.close();
}
static int scanNextInt() {
try {
return scan.nextInt();
}catch(Exception e) {
//Stop the program if the user inputs letters / symbols
System.out.println("Invalid Number.");
return -5;
}
}
}
Changes I've made:
1. I've created a method called scanNextInt() that returns scan.nextInt() if possible. If it will cause an error, it returns -5 to stop the program.
2. I've included the two if statements in the while loop so they actually work.
3. I've caught all of the possible errors, so you should not see any error messages
Note: This HAS been tested
Firstly - you need to move the closing bracket of the while loop after the min number check to allow the checks to be performed for every number you read. And remove one count++ to avoid double counting.
To ignore illegal input you could use one of the other Scanner methods and read a String instead of int, then try to Integer.parseInt the String and wrap the parsing into a try catch.
//count++;
double avg = 0.0;
if (count != 0) {
avg = ((double) sum) / count;
}
System.out.println("Average : " + avg);
When both sides of the division are int then it is an integer division (result int, remainder of division thrown away).
Hence we cast one side, here sum to floating point:
(double) sum
And then it works.
If nothing is put in after java Rev, I need this statement to be printed "Enter only a three digit number, with the first digit larger than the third."
This is not being printed but an error is coming up that says:
x-10-104-10-64:Assgn Katie$ javac Rev.java
x-10-104-10-64:Assgn Katie$ java Rev
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Rev.main(Rev.java:9)
What do I need to fix?
Here is my code:
public class Rev {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
if (checkDigits(num)) {
num = subtractNum(num);
addNum(num);
} else {
System.out.println("Enter only a three digit number, with the first digit larger than the third");
}
}
// checks if numbers are correct
static boolean checkDigits(int number) {
int reverse = reverseNum(number);
if(number < reverse) {
throw new Error("Reverse number needs to be less than the original number!");
} else {
return true;
}
}
//reverses number
static int reverseNum(int number) {
int reverse = 0;
while(number != 0) {
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
// subtracts
static int subtractNum(int number) {
int reverse = reverseNum(number);
int total = number - reverse;
System.out.println("Reverse and subtract: ");
System.out.println(number);
System.out.println(reverse + " - ");
System.out.println("---");
System.out.println(total);
System.out.println();
return total;
}
// adds
static int addNum(int number) {
int reverse = reverseNum(number);
int total = number + reverse;
System.out.println("Reverse and add: ");
System.out.println(number);
System.out.println(reverse + " + ");
System.out.println("---");
System.out.println(total);
return total;
}
}
Check the length of args. Add something like
if (args.length != 1) {
System.err.println("Please provide a single argument.");
System.exit(1);
}
to the start of main.
You are trying to access the 0th element of the args array, which may not exist (if the program is ran without arguments). You should either verify that args has sufficient length before attempting to access the element, or handle the ArrayIndexOutOfBoundsException with a try/catch block.
Use a try/catch block with a print statement inside the catch portion to display that particular message.
public static void main(String[] args)
{
try {
int num = Integer.parseInt(args[0]);
if (checkDigits(num))
{
num = subtractNum(num);
addNum(num);
}
} catch (Exception e) {
System.out.println("Enter only a three digit number, with the first digit larger than the third");
}
}