a positive and negative checker with odd and even checker - java

How can I check if an input number is negative or positive, and if it is positive it will check again if it is odd or even, and if it's negative an error message will appear and ask again the user if he/she wants to check another number?
import java.util.Scanner;
public class OddEvenChecker{
public static void main(String[] args){
int integer=0;
Scanner sc = new Scanner(System.in);
while (true) {
if (integer>=0) {
System.out.print("Enter a positive Integer: ");//gets the user input
integer = sc.nextInt();
}
if (integer<0) { // checks if the entered number is a positive integer
System.out.println("Error");
System.out.print("Do you Want to Continue? y for Yes, n for No: ");
String choices = sc.nextLine();
} else if(integer>0) {
if (integer%2==0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
}
}
}

public class OddEvenChecker {
public static void main(String[] args) {
int integer = 0;
String flag = "y";
Scanner sc = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
do {
System.out.print("Enter a positive Integer: ");//gets the user input
integer = intScanner.nextInt();
if(integer>0) {
if(integer%2==0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
} else {
System.out.println("This is negative number. Try again.");
}
System.out.print("Do you want to Continue? y for Yes, n for No: ");
flag = sc.nextLine();
} while(!(flag.equals("n") || flag.equals("no")));
}
}
What do you think about this approach? Does it meet requirements?

do{
choices = sc.nextLine();
if(choices.equals("n") || choices.equals("no"){
return;
}
else if(choices.equals("y") || choices.equals("yes"){
break;
} else {
System.out.println("invalid key");
}
} while(!choices.equals("n") || (!choices.equals("no") || (!choices.equals("y") || (!choices.equals("yes"));

enter code here
public class OddEvenChecker{
public static void main(String[] args){
int integer=0;
Scanner sc = new Scanner(System.in);
while (true) {
if (integer>=0) {
System.out.print("Enter a positive Integer: ");
integer = sc.nextInt();
if(integer%2==0) {
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
if (integer<0) {
System.out.println("Error");
System.out.print("Do you Want to Continue? y for Yes, n for No: ");
String choices = sc.nextLine();
}
}
}
}//Maybe this is the best and easiest way to do this.

Related

How can I store the scanner input integers in Java so I can print the sum of a list of input integer numbers?

I'm doing the University of Helsinki's Java MOOC and there is an exercise that asks me to create a program that lets you input as much numbers as you want, but when you input a '0' it prints the sum of all the previously input numbers and ends the program. I can't figure out how to 'store' the input numbers for calculating the sum of them when you input a '0'. The program works but inputting '0' prints '0'. This is how my code looks:
public class Application {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number.");
while (true) {
try {
int number = Integer.parseInt(scanner.nextLine());
System.out.println("Input another number.");
if (number == 0) {
System.out.println(number + number);
break;
}
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}
}
How can I calculate the sum of all the input numbers?
You can create a counter and make smth like this, you don't need to save all numbers:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
System.out.println("Input a number.");
while (true) {
try {
int number = Integer.parseInt(scanner.nextLine());
sum += number;
System.out.println("Input another number.");
if (number == 0) {
System.out.println(sum);
break;
}
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}
}
In line with my comment above:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int number = -1;
while (number != 0) {
try {
System.out.print("Input a number (0 to quit): ");
number = Integer.parseInt(scanner.nextLine());
sum += number;
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}
System.out.println("Total:" + sum);
}

I would like put a optional "wrong number. Try again" when is

I have just started learn java codes, that is why might I have a simple question that is not simple for me.
I would like put a optional "wrong number. Try again" when is entered different number than secretNum. May you guys help me out on this code?
// I need learn how put "try again" when the number is != than guess number.
/* I have tried
* 1)Change the signal "==" or "!=".
* 2) do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done");
System.out.println();
System.out.println("Are you ready for the next step?");
System.out.println();
}
*/
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name:");
if(sc.hasNextLine()) {
String userName = sc.nextLine();
System.out.println("Hello " + userName + ",");
System.out.println();
}
int secretNum = 5;
int secretNum2 = 15;
int guess = 0;
do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done\n");
System.out.println("Are you ready for the next step?\n");
}
// I need learn how put "try again" when the number is != than guess number.
/* I have tried
* 1)Change the signal "==" or "!=".
* 2) do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done");
System.out.println();
System.out.println("Are you ready for the next step?");
System.out.println();
}
*/
System.out.println("Enter Yes or No");
while(!sc.next().equals("yes")&& !sc.next().equals("no"));{
System.out.print("Yes");
}
do {
System.out.println("Guess what is the number 11 to 20: ");
if (sc.hasNextInt()) {
guess = sc.nextInt ();
}
}while(secretNum2 != guess);{
System.out.println("Congratulations");
System.out.println();
System.out.println("The End");
}
}
}
````````
You don't need do{} while() for the checks you want to do here, just while(){} loops would be enough.
Please try this code instead:
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name:");
if (sc.hasNextLine()) {
String userName = sc.nextLine();
System.out.println("Hello " + userName + ",");
System.out.println();
}
int secretNum = 5;
int secretNum2 = 15;
int guess = 0;
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
while (secretNum != guess) {
System.out.println("Please try again\n");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
}
System.out.println("Well done\n");
System.out.println("Are you ready for the next step?\n");
System.out.println("Enter Yes or No");
while (!sc.next().equals("yes") && !sc.next().equals("no"))
{
System.out.print("Yes");
}
System.out.println("Guess what is the number 11 to 20: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
while (secretNum2 != guess) {
System.out.println("Please try again\n");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
}
System.out.println("Congratulations");
System.out.println();
System.out.println("The End");
}
}

if a user inputs a letter instead of a number tell them it's not a number

I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here

How to loop this simple program?

How do i loop this WHOLE program?
public class Experiments {
public static void main(String[] args) {
int n;
System.out.print("Please enter a number:");
n = TextIO.getlnInt();
while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
}
}
When it prints out the result:
The result is 14.
I want it to say something like:
Had fun? Lets do it again.
Please enter a number:
or
Had fun? Want do it again. Press y/n.
Please enter a number:
You have to do something like this:
Scanner s = new Scanner(System.in);
char c;
do {
your_code
c = s.next().charAt(0);
} while(c == 'y');
And thanks to this your program will ask you everytime if you want to continue and when you enter 'y' then it will loop again. Otherwise it will exit from the loop.
To combine your code with the example from wawek:
public class Experiments {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
do {
play();
System.out.println("Again ( press y ) else press Anykey");
c = s.next().charAt(0);
} while(c == 'y');
}
public static play(){
int n;
System.out.print("Please enter a number:");
n = TextIO.getlnInt();
while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
}
}
public class Experiments {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char c;
int n;
do{
System.out.print("Please enter a number:");
n = TextIO.getlnInt();
while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
System.out.println("Had fun? press y do it again n to exit");
c = s.next().charAt(0);
} while(c == 'y');
}
credit goes to #wawek
Just read user next line character for yes and then run the whole sequence as shwon below.
public class Experiments {
public static void main(String[] args) {
int n;
while(againFlag=='y'){
System.out.print("Please enter a number:");
n = TextIO.getlnInt();
while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
System.out.println("Had fun. Want do it again?(Press 'y')");
char againFlag = TextIO.getlnChar();
}
}
You can use recursive. Sample like this:
public class Experiments {
public static void main(String[] args) {
guess();
}
public static void guess() {
int n;
System.out.print("Please enter a number:");
n = TextIO.getlnInt();
while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
System.out.println("Had fun? Lets do it again.");
guess();
}
}

How to check if user input is String, double or long in Java

I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
One simple fix is to read the entire line / user input as a String.
Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
You can also use Integer.parseInt and then check that integer for non negativity. You can catch NumberFormatException if the input is string or a double.
Scanner scan = new Scanner(System.in);
try {
String s = scan.nextLine();
int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
Try this one. I used some conditions to indicate the input.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){
for(int y=0; y<10; y++){
if(input.charAt(x)==Integer.toString(y))
flag = true;
else{
flag = false;
break;
}
}
}
if(flag){
if(scan.hasNextDouble())
System.out.println("Input is Double");
else
System.out.println("Input is Integer");
}
else
System.out.println("Invalid Input. Please Input a number");
Try this. It will prompt for input until an int greater than 0 is entered:
System.out.println("Please enter a number");
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNext()) {
int number;
if (scan.hasNextInt()) {
number = scan.nextInt();
} else {
System.out.println("Please enter a valid number");
scan.next();
continue;
}
if (number < 0) {
System.out.println("Please enter a number > 0");
continue;
}
//At this stage, the number is an int >= 0
System.out.println("User entered: " + number);
break;
}
}
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);
while(!valid){
System.out.println("Enter the number: ");
userInput = input.nextLine();
try{
n = Double.parseDouble(userInput);
valid = true;
}
catch (NumberFormatException ex){
System.out.println("Enter the valid number.");
}
}

Categories