Code for only accepting integers - java

import javax.swing.*;
import java.awt.*;
public class JCD {
public static void main(String[] args) {
String input, inputs;
int input1, input2;
input = JOptionPane.showInputDialog("Enter first number");
inputs = JOptionPane.showInputDialog("Enter second number");
input1 = Integer.parseInt(input);
input2 = Integer.parseInt(inputs);
JOptionPane.showMessageDialog(null, "The GCD of two numbers " + input
+ "and" + inputs + " is: " + findGCD(input1, input2));
}// close void
private static int findGCD(int number1, int number2) {
// base case
if (number2 == 0) {
return number1;
}// end if
return findGCD(number2, number1 % number2);
}// end static
} // close class
What can I add so that it will only accept integers? If not given an integer then it will go back to ask again.....

Put your input request in a while statement, check if it's an int, if not repeat the loop, otherwise exit. Do it for both your inputs.
Something like this
public static void main(String[] args) {
String input=null, inputs=null;
int input1 = 0, input2=0;
boolean err=true;
do{
try{
input = JOptionPane.showInputDialog("Enter first number");
input1 = Integer.parseInt(input);
err=false;
}catch(NumberFormatException e){
e.printStackTrace();
}
}while(err);
err=true;
do{
try{
inputs = JOptionPane.showInputDialog("Enter second number");
input2 = Integer.parseInt(inputs);
err=false;
}catch(NumberFormatException e){
e.printStackTrace();
}
}while(err);
JOptionPane.showMessageDialog(null, "The GCD of two numbers " + input
+ "and" + inputs + " is: " + findGCD(input1, input2));
}
Note that this solution requires you to initialize your variables when you declare them
String input = null, inputs = null;
int input1=0, input2=0;

You should try with "try and catch".
input = JOptionPane.showInputDialog("Enter first number");
inputs=JOptionPane.showInputDialog("Enter second number");
try {
input1=Integer.parseInt(input);
input2=Integer.parseInt(inputs);
// establish and use the variables if the characters inserted are numbers
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, e+ "is not a number");
//display a warning to le the user know
}

You could use something like this :-
boolean inputAccepted = false;
while(!inputAccepted) {
try {
input1=Integer.parseInt(input);
input2=Integer.parseInt(inputs);
inputAccepted = true;
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog("Please input a number only");
}
... do stuff with good input value
}

Related

How to calculate the percentage of words in input strings in java

I am trying to calculate the percentage of valid inputs of words.
I'm stuck and every method I've tried doesn't work. I was starting learning java two months ago,so i am new in this and i am not shure if I have done the right code.
Could someone give me some advice on how to word it.Thanks in Advance
public class Subject3
{
public static void main (String[]args) {
Scanner scan = new Scanner(System.in);
//Creating scanner object
boolean valid = true;
int numOfStrings=0;
do {
valid = true;
System.out.print("How many strings?: ");
try{
numOfStrings = Integer.parseInt(scan.nextLine());
}catch (NumberFormatException e){
System.out.println("Not a word");
valid = false;
}
}while (!valid);
String[] stringPali = new String [numOfStrings];
String input;
for (int i=1; i<numOfStrings+1 ; i++) {
do {
valid = true;
System.out.print("Enter string no." +i );
System.out.print(":");
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9]+")){
System.out.println("Not a word");
}
}while (!valid);
}
System.out.println("Results");
System.out.println("Total number of strings: "+ numOfStrings);
System.out.println("Percentage of words:" +(percentage)("%"));
System.out.println("Words starting with capital letter: "+("%"));
}
}
System.out.println("Not a word"); this meesage is wrong. it should be not a number.
You created an array stringPali but never used it? why?
loops starting with 1 is confusing. But it's up to you.
You should first add the words to the array finally you can count.
You need the full user input to calculate percentage. So no point of counting valid strings while user is still entering input. Do it at the end.
You can use regex to match the strings that only contain letters and the strings that start with a capital letter.
import java.util.Scanner;
public class ExampleCase {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Creating scanner object
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("How many strings?: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Not a number");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
for (int i = 0; i < numOfStrings; i++) {
System.out.print("Enter string no." + i);
System.out.print(":");
String input = scan.nextLine();
stringPali[i] = input;
}
System.out.println("Results");
System.out.println("Total number of strings: " + numOfStrings);
int validStringCount = countStrings(stringPali, "^[a-zA-Z]*$");
double percentage = (double) validStringCount / numOfStrings;
System.out.println(String.format("Percentage of words: %f%%", percentage));
int startWithCapitalCount = countStrings(stringPali, "^[A-Z].*");
percentage = (double) startWithCapitalCount / numOfStrings;
System.out.println(String.format("Words starting with capital letter: %f%%", percentage));
}
private static Integer countStrings(String[] stringPali, String pattern) {
int count = 0;
for (String str : stringPali) {
if (str.matches(pattern)) {
count++;
}
}
return count;
}
}

Ask to insert numbers only

So I'm trying to make a simple calculator.
How do I make when I enter the first number, it works but if I insert "abc" it will give me an error.
How I make it in order when you write "abc" to say " please enter a number "
import java.util.Scanner;
public class calculator
{
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if ( c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
}
}
You can verify the input until be a int using a scanner property Scanner.hasNextInt()
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!scanner.hasNextInt()) scanner.next();
Example:
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
while (!test .hasNextInt()) test .next(); // Scanner Validation
int x = test .nextInt();
}
JavaDoc of Scanner
The error you get is an exception. You can actually "catch" your exceptions, so that when they appear, your program doesn't break, and you can do what is in place for that error (output a "Please, insert only numeric values" feedback?)
You can find some info on try-catch blocks here try-catch blocks
Try this:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
} catch(InputMismatchException e) {
System.out.println("Please enter correct values.");
}
}
Modifications:
The error you are getting is known as RunTime Error or Exceptions due to wrong input type. In order to handle RunTime Exceptions, You need to use try and catch block.
try and catch blocks are used to handle RunTime Exceptions. If any error or exception occurs within try block then It will be thrown to catch block to be handled instead of terminating your program.
Try this:
boolean success = false;
while (!success) {
try {
y = test.nextInt();
success = true;
} catch (InputMismatchException e) {
test.nextLine();
System.out.println("Please enter a number.");
}
}
If you're willing to accept doubles instead of ints, java doubles have a built in method isNaN(), where NaN stands for Not a Number.
if (Double.isNaN(doubleValue)) {
...
}

How is nextLine() discarding input in this code?

If I remove input.nextLine() from the catch block, an infinite loop starts. The coment says that input.nextLine() is discarding input. How exactly is it doing this?
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
// Display the result
System.out.println(
"The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
input.nextLine(); // discard input
}
} while (continueInput);
}
}
One more thing.. The code listed below, on the other hand, works perfectly without including any input.nextLine() statement. Why?
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter four inputs::");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int d = input.nextInt();
int[] x = {a,b,c,d};
for(int i = 0; i<x.length; i++)
System.out.println(x[i]);
}
}
Because input.nextInt(); will only consume an int, there is still pending characters in the buffer (that are not an int) in the catch block. If you don't read them with nextLine() then you enter an infinite loop as it checks for an int, doesn't find one, throws an Exception and then checks for an int.
You could do
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required) " +
input.nextLine() + " is not an int");
}

Converting decimal to binary using Java JOptionPane

In the coding I have done, I have a problem at the very end. When the program actually converts the decimal into binary form, the JOptionPane window separates each number in the binary answer. I don't know how to fix this.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class decimalToBinary {
Scanner console = new Scanner (System.in);
public static void main(String [] args){
String digit;
String wrong = ("Enter a value greater than 0");
String binary_answer;
double entered_value;
digit = JOptionPane.showInputDialog
("Enter the decimal number: ");
entered_value = Double.parseDouble(digit);
if (entered_value < 0)
JOptionPane.showMessageDialog(null, wrong, "ERROR",
JOptionPane.ERROR_MESSAGE);
else
{
binary_answer = (binaryform((int) entered_value) + ".");
JOptionPane.showMessageDialog(null, binary_answer, "Result",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
private static Object binaryform(int number) {
double remainder;
if (number <=1) {
JOptionPane.showMessageDialog(null, number , "Result",
JOptionPane.INFORMATION_MESSAGE);
return null;
}
remainder= number %2;
binaryform( number >> 1);
JOptionPane.showMessageDialog(null, remainder , "Result",
JOptionPane.INFORMATION_MESSAGE);
{
return " ";
}
}
}
Looking at your code, I've noticed that you're calling the binaryform() multiple times.
You should stack the result in an array or collection before showing it in a joptionpane.
make it something like this
//introduce a field variable
String remainderStr='';
private static Object binaryform(int number) {
double remainder;
//if (number <=1) {
// JOptionPane.showMessageDialog(null, number , "Result",
// JOptionPane.INFORMATION_MESSAGE);
// return null;
//}
remainder= number %2;
//append on string, to display after the conversion is done.
remainderStr =remainderStr + remainder;
binaryform( number >> 1);
//move this part to main
//JOptionPane.showMessageDialog(null, remainder , "Result",
// JOptionPane.INFORMATION_MESSAGE);
//{
// return " ";
//}
}
}

need character to print in output lines

I need these lines to output when a letter is typed instead of a whole number. I am not sure how to get it to do this: I have the code and what I need posted below if you can help me solve this issue, thank you.
This is what I am getting:
Input a valid whole number: abc
Input is not a valid number
Press any key to continue . . .
This is what I need:
Input a valid whole number: **ABC**
**ABC** is not a valid number
Press any key to continue . . .
below is what i have so far:
import java.io.PrintStream;
import java.util.Scanner;
public class FinalPractice
{
public static void main(String [] args)
{
Scanner scanner = new Scanner( System.in );
PrintStream out = System.out;
out.print( "Input a valid whole number: " );
String input = scanner.next();
int number;
try {
number = Integer.parseInt(input);
} catch (Exception e) {
out.println("Input is not a valid number");
return;
}
if (number < 0) {
out.println(number + " is not a valid number");
return;
}
printDivisors(number);
}
private static void printDivisors(int x){
PrintStream out = System.out;
for (int i=1; i<x; i++) {
if (isDivisibleBy(x, i)){
out.println(x + " is divisible by " + i);
} else {
out.println(x + " is not divisible by " + i);
}
}
}
private static Boolean isDivisibleBy(int x, int divisor){
while (x > 0) {
x -= divisor;
if (x == 0){
return true;
}
}
return false;
}
}
If I'm understanding correctly, you want your error message to include what the user actually inputted.
Change
out.println("Input is not a valid number");
to
out.println (input + " is not a valid number");
This takes your variable input, merges it with the rest of the String and it will then be displayed to the output console.

Categories