Infinite loop on do while - loops

I'm trying to do a simple method that ask for a number, but I'm having troubles with the condition, here is my code:
private static int rows(){
int w = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.println("What is the number of rows?");
if(sc.hasNextInt()) {
w = sc.nextInt();
if (w <= 0){
System.out.println("Error: the rows can't be 0 or negative number.");
}
}
else {
System.out.println("Error: please only use digits.");
}
}
while (w<=0);
return w;
}
So, when I introduce a negative number or zero the code works fine, but if I try to introduce a letter or a invalid character like a dot or comma, the program enter in a infinite loop repeating this:
System.out.println("What is the number of rows?");
System.out.println("Error: please only use digits.");

You are not refreshing w's value. Re-enable the use to enter a new value for w. Something like:
int w = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.println("What is the number of rows?");
if(sc.hasNextInt()) {
w = sc.nextInt();
if (w <= 0){
System.out.println("Error: the rows can't be 0 or negative number.");
}
}
else {
System.out.println("Error: please only use digits.");
sc.next(); // Clear default input on invalid input
continue; // Restart the loop so it gets newer value again
}
}
while (w<=0);
return w;

w only gets changed in the case of sc.hasNextInt(). If you enter a letter / invalid character, w never gets changed, and your loop cannot end.

Related

After inputting an integer for a scanf() function, code does not continue?

My objective is to create a program that checks if a specific bit (entered by the user) is set in a hard-coded integer (in this case 159). This code compiles, however when I enter my desired integer, the console stalls for about a second and then exits the program with no error message. None of the printf() functions are executed, as nothing else is printed out on the console before it exits. I'm fairly new to C, so I need some help with this.
#include <stdio.h>
int main() {
int x = 159;
int position = 1;
scanf("%d", position);
if (position == 0) {
position = 1;
printf("if");
}
else {
for (int i = 0; i < position; i++) {
position *= 2;
}
printf("else");
}
printf("%d", position);
if ((x & position) != 0) {
printf("true");
}
else {
printf("false");
}
}
scanf function takes address of variable like this scanf("%d", &position);
not variable itself.
it will place entered value in that address so you need to add & to your scanf.
and even after that. except when your position is 0 this code will never work:
else {
for (int i = 0; i < position; i++) {
position *= 2;
}
printf("else");
}
this is an infinitive loop.It will execute until position become so large that int doesn't have enough space to store it so position become some illogical number like uninitialized variables.

Simon Asks (Comparing Character in Two Strings) Kill an Infinite loop

The rule of the game Simon Says compares the individual character of the user input character sequence with each corresponding character sequence in Simon says. (assuming both sequences have the same length). Whenever the user has the same character at the same position as "Simon Says", the user increments their score by one.
I have set up the for and while loop that compares both sequences of character individually from i=0, however, I have some issue in killing the loop.
Any comments are appreciated. Thank you.
Here's what I have:
public class SimonSays {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String simonPattern;
String userPattern;
int userScore;
int i;
userScore = 0;
simonPattern = scnr.next();
userPattern = scnr.next();
for (i=0; i<=simonPattern.length();i++) {
while(userPattern.charAt(i) == simonPattern.charAt(i)){
userScore += userScore;
continue;
}
while(userPattern.charAt(i)!=simonPattern.charAt(i)){
break;
}
}
System.out.println("userScore: " + userScore);
return;
}
}
When using continue and break in loop scope its refer to the nearest loop (as you can see here) - so when you use them in the while loop they refer to it.
This what cause the infinity loop:
while(userPattern.charAt(i) == simonPattern.charAt(i)){
userScore += userScore;
continue; // this cause your infinity loop
}
The continue is execute on the while loop and the condition neer changes therefor - infinity loop.
In order to fix your issue, consider using the following code:
int userScore = 0;
for (; userScore < simonPattern.length(); userScore++) {
if (userPattern.charAt(userScore) != simonPattern.charAt(userScore))
break;
}
//Value of userScore here is the number of times the if statement return false -> which mean mumber of same chars
As the userScore is the number of char we already check in the pattern.
Hope that helps!

How to make an array accept only numbers in c programming?

So my task is to make an array that accepts 10 characters. If the characters entered by the user are greater than 10, then an error is dispayed. If the 10 characters entered contain a letter, it displays another error.
Therefore, the array can only have 10 numbers and nothing else, if the numbers entered are less or more than 10, error is displayed as well as if there are letters in the array.
My code accepts both numbers and letters, as i cannot figure out how to display error when letters are entered.
void getTenDigitPhone(char telNum[])
{
int i;
int z = 1;
do
{
scanf("%s", telNum);
if (strlen(telNum) != 10)
{
printf("Enter a 10-digit phone number: ");
z = 1;
}
else if (strlen(telNum) == 10)
{
return telNum;
}
} while (z == 1);
}
You just need to check that telNum contains only digits:
for (int i = 0; i < 10; i++)
if (!isdigit(telNum[i])) {
// handle error because a non-digit was found.
}
I'm not going to do your homework for you but this should give you the idea.
You can use the function isdigit(x).
This returns true (non-zero) if x is a digit and returns false (zero) if not.
You have to check digit by digit.
I'm going to give an answer because you have posted your current code as your effort. As other answers you should use isdigit(x) function.
...
else if (strlen(telNum) == 10)
{
int i;
char err = 0;
for (i = 0; i < 10; i++) {
if (!isdigit(telNum[i])) {
// Your error here
printf("Non-digit character found");
err = 1;
break;
}
}
if (err == 0) {
return telNum;
}
}
...

Read the digits for a number one at a time, checking for duplicates

The program is meant to receive a number, one digit at a time, and use that digit as an index for the array to check if it's true; if so then break out of the loop and if not, set it to true and continue scanning the other digits til it reaches the last. It's supposed to tell only if a digit was repeated or not at this point.
I have this code so far but I can't seem to get it working. Can anyone help me? I noticed while troubleshooting on my own by testing the value of the variables after execution that sometimes the digits aren't even read, only the first digit entered is read.
Here's the code:
#include <stdio.h>
#define true 1
#define false 0
typedef int bool;
int main(void)
{
// Variables to contain the seen digits
bool seendig[10] = { false };
long entered;
int container;
printf("This Program Is Designed To Determine If Any Digits Has Been Repeated!\n Please Enter a Number: ");
scanf("%1d", &entered);
while (entered > 0)
{
container = entered;
if (seendig[container])
break;
seendig[container] = true;
entered /= 10;
}
if (entered > 0)
printf("\nThe Digit Was Repeated\n\n");
else
printf("The Digit Was Not Repeated\n\n");
system("pause");
return 0;
}
The part
container = entered;
if (seendig[container])
will cause out-of-range access if 10 or larger integer is inputted.
I guess
container = entered;
should be
container = entered % 10;
to get the least significant digit in decimal.
Is your code only trying to let the user input 1 number? or many number? If it is the latter then your scanf("%1d",&entered); should be inside of a loop and also I would recommend that you use a post-test loop or do-while loop since you need to let the user input a number first before checking it.
You should also consider 0 since it is a valid index value in an array
do {
printf("This Program Is Designed To Determine If Any Digits Has Been Repeated!\nPlease Enter a Number: ");
scanf("%d", &temp);
entered = temp;
if(temp >= 0){
while(temp > 0){
entered = temp % 10;
temp/=10;
}
}else{
break;
}
if(entered >= 0 && seendig[entered] != true){
seendig[entered] = true;
}else{
flag = 1;
}
printf("\n");
}while(flag == 0);
if (entered >= 0){
if(flag == 1){
printf("\nThe Digit Was Repeated\n\n");
}else{
printf("The Digit Was Not Repeated\n\n");
}
}else{
printf("The Digit You have Inputted is a Negative Value\n\n");
}
you should add this line of code to end of your while loop
scanf_s("%d", &entered);

try& catch used to provide a value

I used try and catch method in my program, but I did not procedure a value which user enter when an incorrect value is entered. For example user enter a string value and program says that please enter a number... then program do not allow that user enter a new value. What can I do? My codes are here. Thanks.
try
{
Console.Write("Please enter column number: ");
string str = Console.ReadLine();
int columno = int.Parse(str);
if (columno > 20)
{
Console.WriteLine("please enter a number between 1 and 20");
}
else
{
for (int j = 0; j < columno; j++)
{
Random rnd = new Random();
for (int i = 0; i < 6; i++)
{
int rndno = rnd.Next(1, 50);
Console.WriteLine(rndno);
}
}
}
}
catch
{
Console.WriteLine("please enter a number between 1 and 20", "Error");
}
Console.ReadLine();
}
}
}
I'm not sure for the language, probably C#, but it should be something like that:
Console.Write("Please enter column number: ");
int columno = 0;
while(true) {
try{
string str = Console.ReadLine();
columno = int.Parse(str);
if (columno < 21 && columno > 0) {
break;
}
}
catch {}
Console.WriteLine("please enter a number between 1 and 20", , "Error");
}
//Rest of the code
The problem is that you're catching the exception on your entire code instead of on input only, so you catch it and continue right after all the code. All the remaining part inside the try is not executed.

Resources