How to loop the following code? - java

I'm really new to java and I cannot find a way around this. I want to make a program that tells you that a number is either positive or negative, regardless if it is int or double. But after the program is executed, I want it to loop and ask again for input from the user, to execute the code again and again and again, as long as there is user input. Can I do that in java?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String userInput = "Input your number: ";
System.out.println(userInput);
if (in.hasNextInt()) {
int z = in.nextInt();
if (z > 0) {
System.out.println(z + " is positive.");
} else if (z < 0) {
System.out.println(z + " is negative.");
} else {
System.out.println(z + " is equal to 0.");
}
} else if (in.hasNextDouble()) {
double x = in.nextDouble();
if (x > 0) {
System.out.println(x + " is positive.");
} else if (x < 0) {
System.out.println(x + " is negative.");
} else {
System.out.println(x + " is equal to 0.");
}
} else {
System.out.println("Hey! Only numbers!");
}
}
}

Here is a one of the approach which is good start for you to understand what wonders pattern matching can do in Java and it can be improved by testing it against exhaustive data points.
This also shows how to use while-loop, overloading methods and ternary operator instead of nested if-then-else.
As you are learning, you should also use debugging feature of editors and also use system.out.println to understand what code is doing.
I am ending the program when user presses just enter (empty string).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String userInput = "Input your number: ";
System.out.print(userInput);
String input = scanner.nextLine();
// look for integer (+ve, -ve or 0)
if (input.matches("^-?[0-9]+$")) {
int z = Integer.parseInt(input);
System.out.println(display(z));
// look for double (+ve, -ve or 0)
} else if (input.matches("^-?([0-9]+\\.[0-9]+|[0-9]+)$")) {
double z = Double.parseDouble(input);
System.out.println(display(z));
// look for end of program by user
} else if (input.equals("")) {
System.out.println("Good Bye!!");
break;
// look for bad input
} else {
System.out.println("Hey! Only numbers!");
}
}
scanner.close();
}
// handle integer and display message appropriately
private static String display(int d) {
return (d>0) ? (d + " is positive") : (d<0) ? (d + " is negative") : (d + " is equal to 0");
}
// handle double and display message appropriately
private static String display(double d) {
return (d>0) ? (d + " is positive") : (d<0) ? (d + " is negative") : (d + " is equal to 0");
}
}
Sample Run:
Input your number: 0
0 is equal to 0
Input your number: 0.0
0.0 is equal to 0
Input your number: -0
0 is equal to 0
Input your number: -0.0
-0.0 is equal to 0
Input your number: 12
12 is positive
Input your number: -12
-12 is negative
Input your number: 12.0
12.0 is positive
Input your number: -12.0
-12.0 is negative
Input your number: 12-12
Hey! Only numbers!
Input your number: ---12
Hey! Only numbers!
Input your number:

Use this code!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Console console = new Console();
while(true) {
// Take your input
Scanner in = new Scanner(System.in);
String userInput = "Input your number: ";
System.out.println(userInput);
if (in.hasNextInt()) {
int z = in.nextInt();
if (z > 0) {
System.out.println(z + " is positive.");
} else if (z < 0) {
System.out.println(z + " is negative.");
} else {
System.out.println(z + " is equal to 0.");
}
} else if (in.hasNextDouble()) {
double x = in.nextDouble();
if (x > 0) {
System.out.println(x + " is positive.");
} else if (x < 0) {
System.out.println(x + " is negative.");
} else {
System.out.println(x + " is equal to 0.");
}
} else {
System.out.println("Hey! Only numbers!");
}
// Ask for exit
System.out.print("Want to quit? Y/N")
String input = console.readLine();
if("Y".equals(input))
{
break;
}
}
}
}

Related

Java guess game. How do I use data validation to check if a number is within a certain range?

I need help coding a set of statements of data validation that checks if a user entry is within a range of 0 and 100, and anything the user types that ISNT a non-decimal integer between 1 and 100 should display an error message. Also I need a way to code how I can get a "goodbye" output to only display if the user enters "n" not "n" and "y." N meaning no and y meaning yes.
Heres my code.
import java.util.Scanner;
public class GuessingGameCalc {
private static void displayWelcomeMessage(int max) {
System.out.println("Welome to the Java Guessing Game!");
System.out.println(" ");
System.out.println("I'm thinking of a number between 1 and" + " " + max + " " + "let's see if you guess what it is!");
System.out.println(" ");
}
public static int calculateRandomValue(int max) {
double value = (int) (Math.random() * max + 1);
int number = (int) value;
number++;
return number;
}
public static void validateTheData(int count) {
if( count < 3) {
System.out.println("Good job!");
} else if (count < 7) {
System.out.println("Need more practice.");
} else{
System.out.println("Need way more practice.");
}
}
public static void main(String[] args) {
final int max = 100;
String prompt = "y";
displayWelcomeMessage(max);
int unit = calculateRandomValue(max);
Scanner sc = new Scanner(System.in);
int counter = 1;
while (prompt.equalsIgnoreCase("y")) {
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
if ( (unit - userEntry) > 10 ) {
System.out.println("Way Too low! Guess higher!");
} else {
System.out.println("Too low! Guess higher!");
}
} else if (userEntry > unit) {
if( (userEntry - unit) > 10 ){
System.out.println("Way Too high! Guess lower!");
} else {
System.out.println("Too high! Guess lower!");
}
} else {
System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
validateTheData(counter);
break;
}
counter++;
}
System.out.println("Would you like to try again? Yes or No?");
prompt = sc.next();
System.out.println("Goodbye!");
}
}
}
Instead of using .nextInt() rather use .nextLine(), which returns a String and then parse it to an int and catch the NumberFormatException
So basically you'll have this structure:
try {
int userEntry = Integer.parseInt(sc.nextLine());
...
} catch (NumberFormatException nfe) {
System.out.println("Please enter a valid number.");
}
Oh, just a comment on the rest of your code. You don't really need two while loops, one will be more than sufficient.

Command program, mostly working, bugs here and there

I'm writing a program to take in commands from the user, and output accordingly. The program keeps asking for input, until the user inputs "Quit" as a command.
Commands are:
Factorial # (takes one number as an argument)
Outputs the factorial of the number, Ex.
Factorial 5
5! == 120
GCD # # (Takes 2 numbers as arguments)
outputs the greatest common divisor between 2 numbers (Recursively.) Ex.
gcd 5 10
gcd(5, 10) == 5
Sorted # #... (Takes as many numbers as the user wants)
checks to see if the numbers after the command are in order. Ex.
sorted 1 2 3 4 5
That list is sorted.
sorted 1 2 3 5 4
Out of order: 4 after 5.
Now all this works pretty good. nothing wrong as of now, what im struggling with, when the user enters a letter instead of a number, it should try and catch an InputMismatchException, this kind of works. for example.
if the user enters a letter it would say this.
Factorial j
Not a number: For input string: j
BUT
Factorial 5 j
5! == 120
it would go on how it normally would, but it takes the "j" as the next command, for so if i type Factorial 5 quit, it would print the factorial then quit, i don't know why this is happening.
another thing is i want to throw and catch an exception if the arguments are too much for the command, so the user cant type Factorial 5 10, and it would just calculate the factorial of 5, it would print an error message, i dont know how to achieve this.
Heres my code as of now.
A09.java
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
*
*
* #author Amr Ghoneim (A00425709)
*
*/
public class A09 {
static int counter = 0;
#SuppressWarnings("resource")
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.next().toLowerCase();
// FACTORIAL
if (commands[1].startsWith(command)
&& commands[1].contains(command)) {
try {
int num = scnr.nextInt();
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// GCD
} else if (commands[2].startsWith(command)
&& commands[2].contains(command)) {
try {
int numA, numB;
numA = scnr.nextInt();
numB = scnr.nextInt();
System.out.println("gcd(" + numA + ", " + numB + ") == "
+ GCD(numA, numB));
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// SORTED
} else if (commands[0].startsWith(command)
&& commands[0].contains(command)) {
try {
List<Integer> nums = new ArrayList<Integer>();
StringTokenizer st = new StringTokenizer(scnr.nextLine(),
" ");
while (st.hasMoreTokens()) {
nums.add(Integer.parseInt(st.nextToken()));
}
sorted(nums);
} catch (NumberFormatException nfe) {
System.out.println("Not a number: For input string: ");
}
// QUIT
} else if (commands[4].startsWith(command)
&& commands[4].contains(command)) {
isValid = false;
quit();
// HELP
} else if (commands[3].startsWith(command)
&& commands[3].contains(command)) {
help();
}
}
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "\nGCD, and check to see if a list of numbers are in order"
+ "\n-----------------------------------"
+ "\nMade by Amr Ghoneim (A00425709)"
+ "\n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "\n - factorial #"
+ "\n The product of all numbers from 1 to #."
+ "\n (The argument must not be negative.)" + "\n - gcd # #"
+ "\n The greatest common divisor of the two numbers."
+ "\n The biggest number that divides evenly into both of
them."
+ "\n - sorted #..."
+ "\n Whether the numbers are in order from smallest to
largest."
+ "\n If not, then where the first out-of-order number is."
+ "\n - help" + "\n This help message." + "\n - quit"
+ "\n End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after "
+ nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}
What im missing is finding out how many arguments the user is putting, if too much print a message, and for the sorted command, i cant get it to print the letter the user puts. and for some reason when i input "Factorial 5 5" is would print the ">>>" twice instead of once. theres just some bugs here and there, can someone guide me on how i would approach this stuff, or show some examples?
Thanks!
I have modified your code so that it will work as what you have described. Just look at the code comments for details. Feel free to comment for clarifications.
Modified code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static int counter = 0;
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.nextLine().toLowerCase(); // instead of getting the input per space, get all the input per
// line
String[] userCommand = command.split(" "); // split the line by spaces
// check if the command has at least 2 parameters except for "help" and "quit"
if (!commands[3].equals(userCommand[0]) && !commands[4].equals(userCommand[0]) && userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
// since you know that the first word will be the command, you just have to get
// the value of index 0
// FACTORIAL
// use equals do not use startsWith or contains since it will hold true for
// inputs "FACTORIALINVALID 4"
if (commands[1].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 2 parameters
if (userCommand.length != 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the factorial and convert it into an int
int num = Integer.parseInt(userCommand[1]);
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// GCD
// use equals do not use startsWith or contains since it will hold true for
// inputs "GCDINVALID 4 5"
} else if (commands[2].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 3 parameters
if (userCommand.length != 3) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the GCD and convert it into an int
int numA, numB;
numA = Integer.parseInt(userCommand[1]);
numB = Integer.parseInt(userCommand[2]);
System.out.println("gcd(" + numA + ", " + numB + ") == " + GCD(numA, numB));
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// SORTED
// use equals do not use startsWith or contains since it will hold true for
// inputs "SORTEDINVALID 4 5 6"
} else if (commands[0].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must at least 2 parameters
if (userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
List<Integer> nums = new ArrayList<Integer>();
// get the list
for (int i = 1; i < userCommand.length; i++) {
nums.add(Integer.parseInt(userCommand[i]));
}
sorted(nums);
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// QUIT
// use equals do not use startsWith or contains since it will hold true for
// inputs "QUITINVALID"
} else if (commands[4].equals(userCommand[0])) {
isValid = false;
quit();
// HELP
// use equals do not use startsWith or contains since it will hold true for
// inputs "HELPINVALID"
} else if (commands[3].equals(userCommand[0])) {
help();
}
}
scnr.close();
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "\nGCD, and check to see if a list of numbers are in order" + "\n-----------------------------------"
+ "\nMade by Amr Ghoneim (A00425709)" + "\n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "\n - factorial #" + "\n The product of all numbers from 1 to #."
+ "\n (The argument must not be negative.)" + "\n - gcd # #"
+ "\n The greatest common divisor of the two numbers."
+ "\n The biggest number that divides evenly into both of them." + "\n - sorted #..."
+ "\n Whether the numbers are in order from smallest to largest."
+ "\n If not, then where the first out-of-order number is." + "\n - help"
+ "\n This help message." + "\n - quit" + "\n End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after " + nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}

Catch invalid input and return to input prompt JAVA

I am very new to Java and as part of my college course I have to write a program that carries out some basic functions. Part of this program is that it needs to calculate the factorial of a number that the user inputs. If the user inputs a negative number then it must prompt for a positive number. I have got it to do this.
But if the user enters a fraction such as 2.2 then the program should present the user with an error and prompt for valid data. I believe some sort or try-catch should be implemented but so far I have had no success in getting this to work, after spending many hours on it. Any ideas how to get the program to catch the InputMismatchException error and prompt user for input again?
The relevant block of code from the program is below...
public static void factorialNumber() {
int factorial = 1;
boolean valid;
int number = 0;
do {
System.out.println("Please enter a number: ");
number = sc.nextInt();
valid = number > 0;
if (!valid) {
System.out.println("ERROR Please enter a positive number");
}
} while (!valid);
if (number < 0) {
System.out.println("***Error***: Please enter a positive number ... ");
factorialNumber();
}
if (number > 0) {
System.out.print("The factorial is: " + number + " ");
}
for (int i = 1; i <= number; i++) {
factorial *= i;
if ((number - i) > 0) {
System.out.print("x " + (number - i) + " ");
}
}
System.out.println("= " + factorial);
}
You can use Double class to parse the user input and then get only correct values. Like this:
public static void factorialNumber() {
int factorial = 1;
boolean valid;
int number = 0;
String userInput;
do {
System.out.println("Please enter a number: ");
userInput = sc.nextLine();
valid = validateUserInput(userInput);
} while (!valid);
number = Double.valueOf(userInput).intValue();
System.out.print("The factorial is: " + number + " ");
for (int i = 1; i <= number; i++) {
factorial *= i;
if ((number - i) > 0) {
System.out.print("x " + (number - i) + " ");
}
}
System.out.println("= " + factorial);
}
private static boolean validateUserInput(String userInput) {
if (userInput == null) {
System.out.println("You should enter a number!");
return false;
}
Double userInputNumber;
try {
userInputNumber = Double.valueOf(userInput);
} catch (Exception e) {
System.out.println("Please enter a valid number value.");
return false;
}
if (userInputNumber <= 0) {
System.out.println("ERROR Please enter a positive number");
return false;
} else if (userInputNumber - userInputNumber.intValue() > 0) {
System.out.println("ERROR You entered a fractional number!");
return false;
}
return true;
}

Beginner Java Program - All Numbers Entered Showing as Odd

I am taking a class on Java and the program I am working on is suppose to ask for a number and then show whether it is odd or even, all numbers show as odd. Here is the code:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int input, result;
System.out.print("Enter an integer number: ");
input = Integer.valueOf(scan.nextLine());//Needed to make the scan of the
//produce a integer rather than a string.
result = input % NUM;//Orgininal coder forgot ";" ending. Syntax type.
if (result == 0) {
System.out.println("\n\n Number " + input + " is odd.");
}
else if (result != 0) {
System.out.println("\n\n Number " + input + " is even.");
}
}
}
Any help is appreciated? I am just learning java.
check out this code:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int input, result;
System.out.print("Enter an integer number: ");
input = Integer.valueOf(scan.nextLine());//Needed to make the scan of the
//produce a integer rather than a string.
result = input%2;
if (result == 0) {
System.out.println("\n\n Number " + input + " is even.");
}
else if (result != 0) {
System.out.println("\n\n Number " + input + " is odd.");
}
}
}
Remember:
If result is an even number, the result will be 0.
import java.util.Scanner;
public class OddEven {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int input, result;
System.out.print("Enter an integer number: ");
input = scan.nextInt();
result = input%2;
if (result == 0)
System.out.println("\n\n Number " + input + " is even.");
else
System.out.println("\n\n Number " + input + " is odd.");
scan.close();
}
}
It should read input % 2
You will then have to swap odd and even since a number is even if there is 0 remainder when you divide by 2.
And it should be if (result == 0)
This code works for me:
import java.util.Scanner;
public class OddEven
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int input, result;
System.out.print("Enter an integer number: ");
input = Integer.valueOf(scan.nextLine());//Needed to make the scan of the
//produce a integer rather than a string.
result = input % 2;//Orgininal coder forgot ";" ending. Syntax type.
if (result == 0) {
System.out.println("\n\n Number " + input + " is even.");
}
else if (result != 0) {
System.out.println("\n\n Number " + input + " is odd.");
}
}
}

English Language Calculator [java]

Create a java program that will do the following:
a) Read three inputs from the keyboard,
• two input numbers each being a single digit (0…9)
• one character representing one of five operations : + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation)
b) output the description of the operation in plain English as well as the numeric results
import java.util.Scanner;
public class EnglishCalc {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
int number1 = input.nextInt();
System.out.println("Enter second number");
int number2 = input.nextInt();
System.out.println("Enter operation: +,-,*,/,^");
String operation = input.next();
int output = 0;
if(number1 < 0 || number1 > 9 || number2 < 0 || number2 > 9) {
System.out.println("Number should be between 0 and 10");
}
else if (operation.equals("+"))
{
output = number1 + number2;
System.out.println("Sum of "+number1+" and "+number2+" is: " +output);
}
else if (operation.equals("-"))
{
output = number1 - number2;
System.out.println("Subtraction of "+number2+" from "+number1+" is: " +output);
}
else if (operation.equals("*"))
{
output = number1 * number2;
System.out.println("Product of "+number1+" and "+number2+" is: " +output);
}
else if (operation.equals("/"))
{
if(number2 == 0) {
System.out.println("You cannot divide by 0");
} else {
output = number1/number2;
System.out.println("Division of "+number1+" by "+number2+" is: " +output);
}
}
else if(operation.equals('^'))
{
output = Math.pow((double)number1 , (double)number2);
System.out.println("Value of "+num1+" raised to power of "+num2+" is: " +output);
} else {
System.out.println("Invalid input");
}
}
}
for pow. i tried casting wont work. and if i dont cast, it wont accept int. must be double.
Use
s1.equals(s2)
to compare strings, instead of using:
s1 == s2
This happens because == is used to compare object references (if the are the same object), so it doesn't compare the 'contain' of that object, in this case a String.
Edit
To print each number in 'words', you could use an array:
String[] numbers = {"zero", "one", "two", ... };
and then use them as:
System.out.println(numbers[2] + " plus " + numbers[5] + ...);

Categories

Resources