Input Validation for Java Program to check consecutive sequences - java

My Java program takes a sequence of numbers entered by a user, and should determine if the string is a series of up to 10 consecutive sequence numbers or if the number sequence contains the same number.
The numbers entered are separated by the dash character. The program should display “Correct consecutive sequence”, “Incorrect consecutive sequence”, “Pair of numbers found”, “Pair of numbers not found” and/or “Invalid Input”.
I am struggling with input validation. I have been working on the code for hours. The iterative loop still runs if I input "n" for it to stop running, when the only thing it should accept is "y" or "Y". Also, the code breaks if I attempt to input a "w" when it should say "invalid input".
Lastly, a pair is not detected if it is not entered first. For example 3-3-4-5 is detected as a sequence with a pair, but it does not also include that is it consecutive. If I enter 3-4-5-5-6, it will not detect the pair. I cannot figure out why it is doing this. Please Help. My code is shown below.
import java.util.Scanner;
public class JavaApplication12 {
/**
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char ch = 'y';
//LOOP TO CONTINUOUSLY TAKE INPUT
while(ch != 'n' || ch != 'N'){
System.out.println("Enter a sequence of numbers");
String num = sc.next();
// WE WILL TAKE STRING INPUT SO WE WILL SPLIT IT WITH DELIMITER
String arr[] = num.split("-");
if(arr.length < 10){
int arrint[] = new int[arr.length];
for(int i=0;i< arr.length;i++){
arrint[i] = Integer.parseInt(arr[i]);
}
// PRESCRIBED CONDITOIONS AND USE OF 2 FUNCTIONS
if(arrint[0] == arrint[1]){
System.out.println("Pair Found");
}else if(arrint[0] == (arrint[1] + 1)){
new func().decreasing(arrint);
}else if(arrint[0] == (arrint[1] - 1)){
new func().increasing(arrint);
}
}else{
System.out.println("Invalid Input");
}
//CODE THAT ASKS USER TO CONTINUE OR NOT
System.out.println("Want to enter more (Y/n)");
ch = sc.next().charAt(0);
}
}
}
// CLASS THAT CONTAINS LOGIC OF FUNCITONS
class func{
public void increasing(int[] arr){
int flag = 1;
for(int i=0;i<arr.length - 1;i++){
if(!(arr[i] == (arr[i+1] - 1))){
flag = 0;
break;
}else if(arr[i] == (arr[i+1])){
flag = 2;
break;
}
}
if(flag == 0){
System.out.println("Incorrect consecutive sequence");
}else if(flag == 1){
System.out.println("Correct consecutive sequence");
}else if(flag == 2){
System.out.println("Pair of numbers found");
}
}
public void decreasing(int[] arr){
int flag = 1;
for(int i=0;i<arr.length - 1;i++){
if(!(arr[i] == (arr[i+1] + 1))){
flag = 0;
break;
}else if(arr[i] == (arr[i+1])){
flag = 2;
break;
}
}
if(flag == 0){
System.out.println("Incorrect consecutive sequence");
}else if(flag == 1){
System.out.println("Correct consecutive sequence");
}else if(flag == 2){
System.out.println("Pair of numbers found");
}
}
}

The following statement will always be evaluated as true, how can a character equals to two different characters at the same time?
while (ch != 'n' || ch != 'N')
Change it to while (ch != 'n' && ch != 'N')

Related

Do while loop for Try again program not working correctly (java)

I created a program that convert text to ASCII value and now when i press Y to try again and input a new string there will be a error that string is out of range etc.
I am new in this field, I will appreciate your help.
And here is the Error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 17,length 17
at java.base/java.lang.String.checkIndex(String.java:3278)
at java.base/java.lang.AbstractStringBuilder.charAt(AbstractStringBuilder.java:307)
at java.base/java.lang.StringBuffer.charAt(StringBuffer.java:242)
at com.company.Main.main(Main.java:26)
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
boolean Flag; // The Boolean variable for the do while lopp
int n,l,j=0,m,i,ch;
char t;
StringBuffer data = new StringBuffer();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter any string and it will convert into numbers:- ");
data.append(input.nextLine());
l = data.length();
m = l;
System.out.println(l);
for (i = 0; i < m; i++) {
t = data.charAt(j);
n = (int) t;
System.out.print(n);
System.out.print(",");
j++;
}
data.delete(0, m-1);
System.out.println("\nDo you want to try again? Y/N");
ch = input.nextInt();
//Those are the condition for that the program should be run again or not
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
}
while(Flag=true);
System.out.println("Thanks, Come Again");
}
}
while(Flag=true);
this doesn't check whether the value of Flag is true, it sets it to true, and thus automatically returns true.
What you want is:
while(Flag==true);
or,
while(Flag);
for short.
You may also want to read up about naming conventions.
As for your Exception:
Y is not an int, change your
ch = input.nextInt();
to
ch = input.nextLine().charAt(0);
this will solve the initial problem, but still might lead to false results with unexpected input (or lack there of)
int n,l,j=0,m,i,ch;
This declaration is invalid. If all of these values are supposed to be
0, the declaration should look like:
int n, l, j, m, i, ch = 0
Also your logic in the nextInput section is incorrect.
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
Instead of the AND ( && ) this should be an OR ( || ). If it's 'Y' OR it's 'y'. It will likely never be both Y and y. This should be fixed as follows:
if (ch == 'Y' || ch == 'y') {
Flag = true;
} else if (ch == 'N' || ch == 'n') {
Flag = false;
}
Also, as mentioned by #Stultuske, you'll want to change your while condition to:
while (Flag == true)
One thing that's niggling at me here is that ch is an integer, but you're asking it if that value is 'Y, y, N, n' those are characters and not integers. I'm guessing that's why you got the 'Input_Mismatch_Exception'. Hope this helps.
Edit: Formatting

How to turn a user given String into Pig Latin?

Im trying to turn a string taken from the user into Pig Latin. I cannot use any special classes, methods, or arrays. I can only use a Scanner to create a object to take the string from the user and .length and .charAt, in addition to any type of looping. (Also cannot use switch statements or the break keyword)
Here is an example of what my output is suppose to be:
Enter a line of text: this is a test.
Input : this is a line of text.
Output: his-tay is-way a-way ine-lay of-way ext-tay.
Here is my code, I can only get my code to work with one word and it must have a space at the end. Only one loop works at a time depending on the loop. Im not sure what to do if I get an entire String.
I know that when the user enters a space that signals a new word, and when they enter a period, that signals the ending.
I had a hard time understanding your code. (It looks like you are trying to do it two ways at once?) Regardless, I believe I was able to understand your question. Here is a compilable and runnable example:
import java.util.Scanner;
public class PigLatin
{
public static void main(String[] args)
{
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
if (text != null && text.length() > 0)
{
int i = 0;
// this iterates through the whole string, stopping at a period or
// the end of the string, whichever is closer
while (i < text.length() && text.charAt(i) != '.')
{
// these three variables only exist in this code block,
// so they will be re-initialized to these values
// each time this while loop is executed
char first = '\0'; // don't worry about this, I just use this value as a default initializer
boolean isFirst = true;
boolean firstIsVowel = false;
// each iteration of this while loop should be a word, since it
// stops iterating when a space is encountered
while (i < text.length()
&& text.charAt(i) != ' '
&& text.charAt(i) != '.')
{
// this is the first letter in this word
if (isFirst)
{
first = text.charAt(i);
// deal with words starting in vowels
if (first == 'a' || first == 'A' || first == 'e' || first == 'E'
|| first == 'i' || first == 'I' || first == 'o' || first == 'O'
|| first == 'u' || first == 'U')
{
System.out.print(first);
firstIsVowel = true;
}
// make sure we don't read another character as the first
// character in this word
isFirst = false;
}
else
{
System.out.print(text.charAt(i));
}
i++;
}
if (firstIsVowel)
{
System.out.print("-tay ");
}
else if (first != '\0')
{
System.out.print("-" + first + "ay ");
}
i++;
}
System.out.print('\n'); //for clean otuput
}
}
}
There are a few comments in there that might help guide you through my logic. This is almost definitely not the most efficient way to do this (even with your limitations), as I only whipped it up as a example of the type of logic you could use.
You could break it up into words, then process the current word when you hit a space or period:
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
String curWord = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' || text.charAt(i) == '.') {
if (curWord.charAt(0) == 'a' || curWord.charAt(0) == 'e' ||
curWord.charAt(0) == 'i' || curWord.charAt(0) == 'o' ||
curWord.charAt(0) == 'u') {
System.out.print(curWord + "-way ");
} else {
for (int j = 1; j < curWord.length(); j++) {
System.out.print(curWord.charAt(j);
}
System.out.print("-" + curWord.charAt(0) + "ay ");
//System.out.print(curWord.substring(1)+"-"+curWord.charAt(0)+"ay ");
}
curWord = "";
} else {
curWord += text.charAt(i);
}
}

So I have this code here, it calculates the vowels in a given phrase. I'm trying to get it to repeat if the user says yes

I was wondering as to how I could get the end of the program to repeat if the user does respond with a 1. Do I need to reorganize it so that it is part of the if statement?
Scanner input = new Scanner(System.in);
System.out.println("Count Vowels \n============");
System.out.println("Type a sentence and this program will tell you\n\nhow many vowels there are (excluding 'y'):");
String string1;
string1 = input.nextLine();
string1 = string1.toLowerCase();
int vowels = 0;
int answer;
int i = 0;
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase() + Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
}
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
answer = input.nextInt();
if (answer == 1) {
System.out.println("You have chosen to count the vowels in another phrase");
} else {
System.out.println("Have a nice day");
}
You can do this with a do/while loop. The skeleton for this kind of loop looks like this:
Scanner input = new Scanner(System.in);
do {
// do your stuff here
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
} while(input.nextInt() == 1);
System.out.println("Have a nice day");
It asks the user and evaluates the entered number in the while(input.nextInt() == 1) statement. If this comparison returns true (i.e. user entered 1), then the loops starts again. If not (i.e. user entered something else than 1), the loop stops and you'll get the "Good Bye" message instead.
you can split this up into more than one method and using one primary method call other methods inside a while loop. for example:
boolean continueCounting = false;
void countingVowels() {
//some start game method to make continueCounting = true
//something like "press 1 to start"
//if (input == 1) { continueCounting = true; }
while(continueCounting) {
String userInput = getUserInput();
countVowels(userInput); //count vowels in word from user input and prints them out to console
getPlayAgainDecision(); //ask user to put 1 or 2
if (answer == 1) {
continue
} else if (answer == 2) {
continueCounting = false;
} else {
System.out.println("incorrect input, please choose 1 or 2");
}
}
}
There are many ways to do this. A search on Google would have lead you to the correct answer in less time than it took you to ask the question. However, since you took the time to ask the question here is the answer:
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int answer = 0;
System.out.println("Count Vowels \n============");
// the do-while loop ensures that the code is executed at least once
do {
// on the first run answer equals zero, but on other runs it will equal one
if(answer == 1) {
System.out.println("You have chosen to count the vowels in another phrase");
}
System.out.println("Type a sentence and this program will tell you\n\nhow many vowels there are (excluding 'y'):");
String string1;
string1 = input.nextLine();
string1 = string1.toLowerCase();
int vowels = 0;
int i = 0;
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i'
|| letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase()
+ Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
}
System.out.println("Would you like to check another phrase in the Vowel Counter? If so type 1 if not type 2 and press enter");
answer = input.nextInt();
} while (answer == 1);
System.out.println("Have a nice day");
}
}
In your code you assert that a letter is a vowel if it is in the set a, e, i, o and u which is true. However, the letter y can be a vowel in certain situations.
In general, the Y is a consonant when the syllable already has a vowel. Also, the Y is considered a consonant when it is used in place of the soft J sound, such as in the name Yolanda or Yoda.
In the names Bryan and Wyatt, the Y is a vowel, because it provides the only vowel sound for the first syllable of both names. For both of these names, the letter A is part of the second syllable, and therefore does not influence the nature of the Y.
You could expand on your code even more by checking if the letter y is a vowel or not.
This is a more elegant way to do the counting (I updated the code to satisfy Johnny's comment that my previous answer didn't answer OP's question. The code now loops without unnecessary code):
public static void main(String... args)
{
int answer = 0;
Scanner input = null;
do
{
input = new Scanner(System.in);
System.out.print("Type a sentence and this program will tell you\nhow many vowels there are (excluding 'y'):");
String sentence = input.nextLine();
int vowels = 0;
String temp = sentence.toUpperCase();
for (int i = 0; i < sentence.length(); i++)
{
switch((char)temp.charAt(i))
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++;
}
}
System.out.println("The sentence: \"" + sentence + "\" has " + vowels + " vowels");
System.out.print("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press any other key... ");
String tempNum = input.next();
try
{
answer = Integer.parseInt(tempNum);
} catch (NumberFormatException e)
{
answer = 0;
}
System.out.println();
} while (answer == 1);
input.close();
System.out.println("Have a nice day");
}
Notice that at the end, I catch a NumberFormatException for more robustness validation of the user's input.
Just put the main for loop inside a do-while loop, like so:
do
{
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase() +
Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
answer = input.nextInt();
}
} while (answer == 1);
System.out.println("Have a nice day");
Additionally, there are better ways to do the counting, for example:
for (char c : string1.toCharArray())
{
c = Character.toLowerCase(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}

Loop not ending when it is supposed to

I am trying to get my loop to end when the user inputs the character N or n but when I run my program it will not end properly. It seems like the char for answer isn't being read by the loop itself so can someone please help me?
import java.util.Scanner;
public class Project4_Baker
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
char answer;
System.out.println("=============");
System.out.println("Prime or Not?");
System.out.println("=============");
do
{
System.out.print("Enter a whole number ==>");
int n = s.nextInt();
System.out.println();
if(isPrime(n))
{
System.out.println(n + " is a prime number.");
}
else
{
System.out.println(n + " is a composite number.");
}
System.out.println();
System.out.print("Do another (Y/N)==>");
answer = s.next().charAt(0);
}while(answer != 'N'|| answer != 'n');
}
public static boolean isPrime(int n)
{
if(n <= 1)
{
return false;
}
for (int i = 2; i < Math.sqrt(n); i++)
{
if (n%i==0)
{
return false;
}
}
return true;
}
}
my code will not end when it is supposed to
It should be while(answer != 'N' && answer != 'n');. With while(answer != 'N' || answer != 'n');, if somebody inputs N then it will continue because answer is equal to N but it is not equal to n.
try
while(answer != 'N' && answer != 'n');
You want the case where the character is NOT EQUAL to 'N' AND is also NOT EQUAL to 'n'
The problem resides in the loop condition.
while(answer != 'N' || answer != 'n')
The condition above will always be true.
Use this instead:
while(answer == 'Y' || answer == 'y')
You try to compare String with Char in your while lopp statement.
Convert your char to int and use unicode table to look up charcode, ex. n would be 110
Before your loop:
int a = 0;
Whithin your loop:
a = (int)answer;
...(while a != 110 || ...)

Counting the '1's in a binary number string - Java

This is part of my code, I was instructed to write a program that accepts a binary number as a string, and that will only show "Accepted" if the total number of 1's is 2. There is more to it, but getting to the point where it is counting the 1's is my problem at the moment. If anyone could point me in the direction of my error, it would be most appreciated.
import java.util.Scanner;
public class BinaryNumber
{
public static void main( String [] args )
{
Scanner scan = new Scanner(System.in);
String input;
int count = 0;
System.out.print( "Enter a binary number > ");
input = scan.nextLine( );
for ( int i = 0; i <= input.length()-1; i++)
{
char c = input.charAt(i);
if ((c == '1') && (c == '0'))
if (c == '1')
{count++;}
if (count == 2)
{System.out.println( "Accepted" );
}
if (count != 2)
{System.out.println( "Rejected" );
System.out.print( "Enter a binary number > ");
input = scan.nextLine( );
}
The problem is that if ((c == '1') && (c == '0')) will never be true.
You need to check if the character is 1 OR 0 and then check if it's a '1' to increment your counter.
int count;
Scanner scan = new Scanner(System.in);
String input;
boolean notValid = false; //to say if the number is valid
do {
count = 0;
System.out.print("Enter a binary number > ");
input = scan.nextLine();
for (int i = 0; i <= input.length()-1; i++){
char c = input.charAt(i);
if(c == '0' || c == '1'){
if (c == '1'){
count++;
if(count > 2){
notValid = true;
break; //<-- break the for loop, because the condition for the number of '1' is not satisfied
}
}
}
else {
notValid = true; // <-- the character is not 0 or 1 so it's not a binary number
break;
}
}
}while(notValid); //<-- while the condition is not reached, re-ask for user input
System.out.println("Done : " + input);

Categories

Resources