Loop not ending when it is supposed to - java

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 || ...)

Related

Is there a char.length command?

// I am stuck trying to get my program to only accept a single character from the scanner. Right now the program will accept any amount of characters as long as the first letter is one of the listed letters. I would like to rewrite this code with out the charAt(0) if possible or to add a if statement. if(sea.length > 1){} something like that. I hope I explained the issue well enough to understand. Any help is appreciated, and thank you for your time.
public static char promptForChoice(Scanner in) {
System.out.println("High, Low or Seven(H/L/S");
char sel = in.next().charAt(0);
sel = Character.toUpperCase(sel);
int i = 1;
while (i != 0) {
System.out.println("High, Low or Seven(H/L/S");
if (sel == 'H' || sel == 'L' || sel == 'S') {
i = 0;
} else {
System.out.println("You must enter only H, L or S.");
i = 1;
}
}
return sel;
}
Is there a char.length command?
No, there is no such command. You need to get the input using Scanner::nextLine() and check the length of the input String.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Test
Scanner in = new Scanner(System.in);
System.out.println(promptForChoice(in));
}
public static char promptForChoice(Scanner in) {
char sel = 0;
String input;
boolean valid;
do {
valid = true;
System.out.print("Enter H/L/S [High/Low/Seven]: ");
try {
input = in.nextLine();
sel = input.toUpperCase().charAt(0);
if (input.length() == 1 && (sel == 'H' || sel == 'L' || sel == 'S')) {
return sel;
} else {
throw new IllegalArgumentException("You must enter only H, L or S.");
}
} catch (IllegalArgumentException e) {
valid = false;
System.out.println(e.getMessage());
}
} while (!valid);
return sel;
}
}
A sample run:
Enter H/L/S [High/Low/Seven]: hello
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: High
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: M
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: H
H
Feel free to comment in case of any doubt/issue.
You could get the input from the scanner and put it into a string, then u can do string.length and check it!
the Character length is always 1, I suppose you could achieve what you need with
public static char promptForChoice(Scanner in) {
if(in.next() == "H" || in.next() == "L" || in.next() == "S") {
System.out.println("High, Low or Seven(H/L/S");
return (char) in.next();
}
else {
System.out.println("You must enter only H, L or S.");
// you must always have a return value, in this case
//e.g. the automatically initialized char value
return '\0';
}
}
with your code you could do something like
public static char promptForChoice(Scanner in) {
System.out.println("High, Low or Seven(H/L/S");
char sel = in.next().charAt(0);
if(in.next().length == 1) {
sel = Character.toUpperCase(sel);
int i = 1;
while (i != 0) {
System.out.println("High, Low or Seven(H/L/S");
if (sel == 'H' || sel == 'L' || sel == 'S') {
i = 0;
} else {
System.out.println("You must enter only H, L or S.");
i = 1;
}
}
}
else System.out.println("You must enter only one single character");
return sel;
}

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

Hollow box program with user input. Issue: Works for odd number input, not even

If the user input is odd and within the range it works fine. Can't seem to figure out how to get it to work with even number input though.
I've seen that there is an "easier" way to do this program on other posts but I got this on my own before having to look up any issues and want to see if there is any way I can make this work through this method.
import java.util.Scanner;
public class Lab7_3{
public static void main(String args []){
Scanner input = new Scanner(System.in);
char userStart;
int countA=1, countB=1, rowsColumns;
System.out.println("Do you want to start?");
userStart = input.next().charAt(0);
while (userStart == 'Y' || userStart == 'y'){
System.out.println("How many rows/columns? (5-21)");
rowsColumns = input.nextInt();
while (rowsColumns < 5 || rowsColumns > 21){
System.out.println("Invalid range. Reenter (5-21)");
rowsColumns = input.nextInt();
}//end while3
for(countA = 1; countA <= rowsColumns; countA++){
System.out.println("");
for(countB = 1; countB <= rowsColumns; countB++){
if((rowsColumns % countA) == 0 || (rowsColumns % countB) == 0)){
System.out.print("*");
}//end if
else{
System.out.print("1");
}//end else
}//end for2
}//end for
System.out.println("\nDo you want to continue? (Y/N)");
userStart = input.next().charAt(0);
}//end while
}//end main
}//end class
The line if((rowsColumns % countA) == 0 || (rowsColumns % countB) == 0)) gives wrong results.
if(countA==1 || countA == rowsColumns || countB == 1 || countB == rowsColumns) works for both odd and even numbers.

Input Validation for Java Program to check consecutive sequences

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')

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