How to I validate so the user only enters integers - java

Iv'e been trying to get my code to work so that the user can only input integers. However, its keeps crashing when I enter something with characters like "awsd". I've tried using a bool to help, but it only catches negative inputs. Also, the input method must start as an integer, so I cant switch it to a string. Please help.
import java.util.Scanner; // Needed for Scanner class
import java.io.*; // Needed for File I/O classes
public class Reverse {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String Continue = "yes";
int num;
//creates the file name
File fileWR = new File("outDataFile.txt");
//creates the file object
fileWR.createNewFile();
//file scanner
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR, true));
while (Continue.equals("yes")) {
System.out.print("Enter an integer number greater than 0 :");
num = keyboard.nextInt();
keyboard.nextLine();
if (fileWR.exists())
{
validate(num, output);
}
else
{
fileWR.createNewFile();
}
//option if the user wants to continue
System.out.println("Do you wish to continue?(yes or no): ");
Continue = keyboard.nextLine();
}
output.close();
}
public static void validate(int num, BufferedWriter output) throws IOException {
Scanner keyboard = new Scanner(System.in);
while(!checkNum(num))
{
System.out.print("That is not an integer greater than 0, please try again: ");
num = keyboard.nextInt();
keyboard.nextLine();
}
System.out.print("The original numbers are " + num +"\n");
output.write("\r\nThe original numbers are " + num +"\r\n");
reverse (num, output);
even (num, output);
odd(num, output);
}// end of public static void validate
public static void reverse(int num, BufferedWriter output) throws IOException {
String input = String.valueOf(num); //must output result within the void method for it to count as a void method
String result = ""; //otherwise, you cannot output it in the main method.
for (int i = (input.length() - 1); i >= 0; i--)
{
result = result + input.charAt(i)+' ';
}
result = "the number reversed "+ result +"\r\n";
System.out.print(result);
output.write(result);
}// end of public static void reverse
public static void even(int num, BufferedWriter output) throws IOException {
String input = String.valueOf(num);
String result = "";
for (int i = 0; (i < input.length()); i++)
{
if (Character.getNumericValue(input.charAt(i)) % 2 == 0)
result = result + input.charAt(i) + ' ';
}
if (result == "") {
result = "There are no even digits" + "\r\n";
} else {
result = "the even digits are "+ result +"\r\n";
}
System.out.print(result);
output.write(result);
}// end of public static void even
public static void odd(int num, BufferedWriter output) throws IOException {
String input = String.valueOf(num);
String result = "";
for (int i = 0; (i < input.length()); i++)
{
if (Character.getNumericValue(input.charAt(i)) % 2 == 1)
{
result = result + input.charAt(i) + ' ';
}
}
if (result == "") {
result = "There are no odd digits" + "\r\n";
} else {
result = "the even odd digits are "+ result +"\r\n";
}
System.out.print(result);
output.write(result);
System.out.print("------------------------\n");
output.write("------------------------\n");
}// end of public static void odd
public static boolean checkNum(int num)
{
if(num > 0) {
return true;
}
else {
return false;
}
}
}

You should first get the String, and then try to cast it:
try {
String numStr = keyboard.nextLine();
num = Integer.parseInt(numStr);
//Complete with your code
} catch (NumberFormatException ex) {
System.out.print("That is not an integer");
}

Related

BufferedReader infinite loop

I'm getting an infinite loop error but I don't know how to end the loop.
int a,b,c;
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while((line=br.readLine())!=null);
{
System.out.println("Enter the two numbers to add:");
a=Integer.parseInt(line);
b=Integer.parseInt(line);
c = a+b;
System.out.println("Sum of two numbers:"+ c);
}
You need to remove ; from the end of the while loop because now you code is like
while loop without body
while((line=br.readLine())!=null);
and code block
{
System.out.println("Enter the two numbers to add:");
a=Integer.parseInt(line);
b=Integer.parseInt(line);
c = a+b;
System.out.println("Sum of two numbers:"+ c);
}
So the code will stay in the while loop forever and just read lines
Note: a and b will convert the same line to int if your line like 10 20 you need to split it into 2 string first then get every integer in the variable
String[] number = line.split(" ");
a=Integer.parseInt(numbers[0]);
b=Integer.parseInt(numbers[1]);
or you can use Scanner to read integer by integer for example
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = a+b;
System.out.println("Sum of two numbers:"+ c);
}
Try something like this:
public static void main(String[] args) throws Exception {
int a, b, c;
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.println("Enter the two numbers to add:");
if ((line = br.readLine()) != null && !line.isBlank()) {
String[] input = line.split(" ");
a = Integer.parseInt(input[0]);
b = Integer.parseInt(input[1]);
c = a + b;
System.out.println("Sum of two numbers:" + c);
} else {
break;
}
} while (true);
}
Output:
Enter the two numbers to add:
4 5
Sum of two numbers:9
Enter the two numbers to add:
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InfLoop {
public static void main(final String[] args) throws IOException {
example1();
example2();
}
private static void example1() {
try (InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);) {
while (true) {
final String line1 = br.readLine();
if (line1 == null) {
System.out.println("First number not entered! Aborting...");
break;
}
final String line2 = br.readLine();
if (line2 == null) {
System.out.println("Second number not entered! Aborting...");
break;
}
final int number1 = Integer.parseInt(line1);
final int number2 = Integer.parseInt(line2);
final int c = number1 + number2;
System.out.println("Result of '" + number1 + "'+'" + number2 + "'='" + c + "'");
}
} catch (final Exception e) {
e.printStackTrace();
}
}
private static void example2() throws IOException {
try (InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);) {
while (true) {
final Integer number1 = readInteger(br, "Enter first number: ");
if (number1 == null) {
System.out.println("First number is invalid! Aborting...");
break;
}
final Integer number2 = readInteger(br, "Enter second number: ");
final String line2 = br.readLine();
if (line2 == null) {
System.out.println("Second number is invalid! Aborting...");
break;
}
final int c = number1.intValue() + number2.intValue();
System.out.println("Sum of '" + number1 + "'+'" + number2 + "'='" + c + "'");
}
}
}
private static Integer readInteger(final BufferedReader pBr, final String pMessage) {
if (pMessage != null) System.out.println(pMessage);
try {
final String line = pBr.readLine();
if (line == null) return null;
return Integer.valueOf(line);
} catch (final Exception e) {
return null;
}
}
}
/*
* 1) indentation was off, use IDE that does formatting for you
* 2) use try/resource(/catch/finally)
* 3) you need to read 2 separate lines, else a and b are the same
* 4) start using helper methods (readInteger), save you lots of duplicate code
* 5) there's two different ways of error handling here: handle inside the method (example1), or throw (example2),
* whatever is more useful for the calling code
* 6) usually handling errors (instead of throwing them) should only be done if it is a direct requirement to the method!
*/
/UPDATE: changed IOException to Exception in readInteger()

How do I return the second instance of a substring in Java?

I'm making a function that returns the second occurrence of a character the user inputs. The problem is that it's not printing anything. I remember hearing something about using a nested for loop for it but I don't know. Here's the program; the function I'm having problems with is the last one.
import javax.swing.JOptionPane;
public class IntroToWHILELoops
{
public static void main(String[] args)
{
//Thiis section tests the first method
String myString = GetAndStoreInput();
System.out.println(myString);
//This section tests the second method
System.out.println("Enter a character to search for --> ");
String searchChar = System.console().readLine();
int position = SecondCharPosition(myString,searchChar);
System.out.println("The second position of " +searchChar +" is " +position);
}
//This method keeps getting input from the user until a "X" or "x" is entered
//It then stores the input in a string.
public static String GetAndStoreInput()
{
String input;
String sentence = "";
input = JOptionPane.showInputDialog("Enter something (press x to stop)");
while(!input.equals("x") && !input.equals("X") ){
System.out.println(input);
sentence = sentence + input;
input = JOptionPane.showInputDialog("Enter something else (press x to stop)");
}
return sentence;
}
//Given a string, this method returns the position of the second occurrence of a given character.
//If the character occurs less than 2 times it returns -1.
public static int SecondCharPosition(String str, String Charr)
{
String sentence = str;
int count = 1;
int position = 0;
int i = 0;
while(count < 10){
if(sentence.substring(i,i+1).equals(Charr)){
count++;
}
if(count == 2){
position = i;
}
}
return position;
}
}
#Tyler - Hope this helps you.
import java.util.Scanner;
import javax.swing.*;
class Scratch {
public static void main(String[] args) {
// Thiis section tests the first method
String myString = GetAndStoreInput();
System.out.println(myString);
// This section tests the second method
System.out.println("Enter a character to search for --> ");
final Scanner in = new Scanner(System.in);
String searchChar = in.next();
int position = SecondCharPosition(myString, searchChar);
System.out.println("The second position of " + searchChar + " is " + position);
}
// This method keeps getting input from the user until a "X" or "x" is entered
// It then stores the input in a string.
public static String GetAndStoreInput() {
String input;
String sentence = "";
input = JOptionPane.showInputDialog("Enter something (press x to stop)");
while (!input.equals("x") && !input.equals("X")) {
System.out.println(input);
sentence = sentence + input;
input = JOptionPane.showInputDialog("Enter something else (press x to stop)");
}
return sentence;
}
// Given a string, this method returns the position of the second occurrence of a given character.
// If the character occurs less than 2 times it returns -1.
public static int SecondCharPosition(String str, String Charr) {
int count = 0;
int position = 0;
for (int i = 0; i < str.length(); i++) {
if (String.valueOf(str.charAt(i)).equals(Charr))
count++;
if (count == 2) {
position = i;
break;
}
}
return position;
}
}

So my problem in this is that I cannot seem to add a void function in my code

I want to insert a void function in my code.
import java.util.*;
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
int i;
for (i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
That is my code and I want to add a void function starting in "for". I want the for loop to be in a void function but I can't seem to do it. How do I fix this?
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
tt(num,str1,str);
}
static void tt(int num , char str1, String str)
{
for(int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
Apart from the code, what you wanna achieve from this is still
unclear.
You can add a void method as static and use it directly in main method.
public class javellana {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
String str = scan.nextLine();
System.out.println("Input character: ");
char str1 = scan.next().charAt(0);
int num = str.length();
int i;
func(str, str1);
}
static void func(String str, char str1) {
int num = str.length();
for (int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
EDIT:
You can simply use System.out.println(str.lastIndexOf(str1)); line, instead of the entire for loop for your problem
public class javellana {
String str;
char str1;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input String: ");
str = scan.nextLine();
System.out.println("Input character: ");
str1 = scan.next().charAt(0);
func(); // call function here
}
static void func() {
int num = str.length();
for (int i = num - 1; i >= 0; i--) {
if (str1 == str.charAt(i)) {
System.out.println("The character " + str1 + " you intput is " + i);
break;
}
}
}
}
Try this for change
If
adding a void function
means adding(declaring) another method(function) in public static void main(String){};
then this is not allowed.
What you can do is; create an anonymous class or functional interface (Java 8). Which is not exactly what you want but somehow..
main() is static method, so only static method can be used from it.
Instead of using for loop, you can use String.lastIndexOf() method.
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Input String: ");
String str = scan.nextLine();
System.out.print("Input character: ");
char ch = scan.next().charAt(0);
lastIndexOf(str, ch);
}
}
private static void lastIndexOf(String str, char ch) {
int i = str.lastIndexOf(ch);
if (i >= 0)
System.out.println("The character " + ch + " you input is " + i);
}
You can't create a method within a method.
Currently, you're in main method.
But you can call as many methods you want from a method.
But there's some restriction. you can't call the nonstatic method within a static method.
Therefore the #pkgajulapalli answer is probably correct.

Java palindrome until EOF

I have a program that is supposed to ask the user for a number and it will determine whether it is a palindrome or not. It's supposed to keep asking for numbers until EOF is input - So far it asks for the number twice and doesn't seem to be doing the while loop correctly.
Any insight is appreciated
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
String num = scanner.nextLine();
String reverse = "";
while (scanner.hasNextLine())
{
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
num = scanner.nextLine();
reverse = "";
}
System.out.println("\nProgram ended on request");
}
}
This worked for me; unless you need num or reverse outside the while loop it should work.
import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome:");
while (scanner.hasNextLine())
{
String num = scanner.nextLine();
String reverse = "";
for ( int i = 0; i<num.length(); i++ )
{
reverse = num.charAt(i) + reverse;
}
if (num.equals(reverse))
{
System.out.println("\nEntered number IS a palindrome.");
}
else
{
System.out.println("\nEntered number is NOT a palindrome.");
}
System.out.println("\nEnter a number to check if it is a palindrome:");
}
System.out.println("\nProgram ended on request");
}
}
I would separate the palindrome test into its' own method. You could do that in a one line method like
public static boolean isPalindrome(String str) {
return new StringBuilder(str).reverse().toString().equals(str);
}
but I would prefer to iterate the first half of the characters and compare them to the second half in reverse like
public static boolean isPalindrome(String str) {
if (str == null) {
return false;
}
char[] chars = str.toCharArray();
for (int i = 0; i * 2 <= chars.length; i++) {
if (chars[i] != chars[chars.length - i - 1]) {
return false;
}
}
return true;
}
Then your main can invoke that in an infinite loop (terminating on the lack of input) like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number to check if it is a palindrome:");
if (!scanner.hasNextLine()) {
break;
}
String num = scanner.nextLine();
if (isPalindrome(num)) {
System.out.printf("%s is a palindrome%n", num);
} else {
System.out.printf("%s is NOT a palindrome%n", num);
}
}
System.out.println("Program ended on request");
}

The number occurrence of a character is to be counted in a given line string. Can anyone point out where the error is? The code compiles correctly

The idea is to count the number of occurrence of a given character that a user inputs in a line of string that also is imputed by the user. The idea is to use recursion in Java rather than some sort of loop. The code compiles correctly and runs correctly. But the result does not give a correct answer (does not count the asked character correctly in a given line of string.) Can anyone point out?
import java.util.Scanner;
public class numberOfLetters {
public static int letterCounter(String line, String x)
{
if(line.isEmpty())
{
return 0;
}
else
{
if(line.charAt(0) == 'x')
{
return 1 + letterCounter(line.substring(1), x);
}
else
{
return 0 + letterCounter(line.substring(1), x);
}
}
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of a string >_ ");
String inputLine = keyboard.nextLine();
System.out.println("Enter the character to count >_ ");
String charac = keyboard.nextLine();
int count = letterCounter(inputLine, charac);
System.out.println("The number of '"+ charac + "' in the input '"+ inputLine + "' is "+ count);
keyboard.close();
}
}
You're testing for 'x' instead of the variable:
if(line.charAt(0) == 'x')
you need:
if(line.charAt(0) == x)
Also pass x in as a char instead of String.
You need to check character against character x
import java.util.Scanner;
public class LetterCounter {
public static int letterCounter(String line, char x)
{
if (line.isEmpty()) return 0;
if(line.charAt(0) == x) {
return 1 + letterCounter(line.substring(1), x);
}
else {
return 0 + letterCounter(line.substring(1), x);
}
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of a string >_ ");
String inputLine = keyboard.nextLine();
System.out.println("Enter the character to count >_ ");
String charac = keyboard.nextLine();
char c = charac.charAt(0);
int count = letterCounter(inputLine, c);
System.out.println("The number of '"+ c + "' in the input '"+ inputLine + "' is "+ count);
keyboard.close();
}
}
You say you want to count the number of occurrences of characters, but your "x" parameter is a string. I'd recommend you use "char" to fit with your purpose. If you want "x" to be a string indeed, then your algorithm would need to be somewhat more elaborated and deal with substrings of varying size.
Another issue, you are checking in your "if" statement against the constant 'x', not your parameter.
proposed code (don't have Java on this machine, so untested):
public static int letterCounter(String line, char x)
{
if(line.isEmpty())
{
return 0;
}
else
{
if(line.charAt(0) == x)
{
return 1 + letterCounter(line.substring(1), x);
}
else
{
return 0 + letterCounter(line.substring(1), x);
}
}
}
A simpler solution:
//Input validation should be performed in main
//Invoke from main
int count = letterCounter(inputLine, charac.charAt(0));
public static int letterCounter(String line, char x) {
int counter = 0;
for (char c : line.toCharArray())
if (c == x)
counter++;
return counter;
}

Categories

Resources