What is causing my infinite loop? - java

I can't seem to figure out what I did wrong with my code to create an infinite loop. I would really appreciate it if someone could help explain this to me.
import java.util.Scanner;
class LoopMath1 {
public static void main(String[] args) {
Scanner inputScanner;
inputScanner = new Scanner(System.in);
//gets a number from a user and parses the string as an int
System.out.println("Please give me a positive number");
String userNum;
userNum = inputScanner.nextLine();
System.out.println("Your number is " + userNum + ".");
int number = Integer.parseInt(userNum);
printX(number); //function call
//prints 2 to the x power
System.out.print("2^" + number + "=");
int j = 1;
int twoToThe = 2;
while (j < number) {
twoToThe *= 2;
j++;
}
System.out.print(twoToThe);
//determines if the user number is prime
int i = 0;
for (i = 1; 1 < number; i++) {
int nPrime = number;
if (nPrime == 0) {
System.out.println(number + " is not prime.");
break;
} else {
System.out.println(number + " is prime.");
}
}
}
//this is a function to print a certain amount of Xs, depending on the user input
public static void printX(int nTimes) {
final int WIDTH = nTimes;
while (nTimes < WIDTH) {
System.out.print("x");
nTimes += 1;
}
}
}

for (i=1; 1 < number; i++) has a typo. 1 should be i as in for (i=1; i < number; i++)

Replace
for (i=1; 1 < number; i++) {
by
for (i=1; i < number; i++) {
Your incrementor initialized in the first part of your for loop must be tested in the second part preferably and incremented in the third one.

Related

Having trouble when counting prime numbers between two integers

I'm having issues getting all prime numbers between a given integer A and integer B.
The issue is that the output goes well beyond whatever I defined for B. I thought that the
if (isPrime){
count++;
would fix this but the output still goes well beyond the intended number of integer B.
For example if int valueA = 1 and int valueB = 100, it'll get prime numbers from around 1 to 500 before stopping, instead of just ending the check at 100.
Thank you for any assistance.
import java.util.*;
public class PrimeNumbersTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
// Ask user to input an integer value for A and B
System.out.print("Enter the value of A (must be an integer): ");
int valueA = input.nextInt();
System.out.print("Enter the value of B (must be an integer): ");
int valueB = input.nextInt();
System.out.println("The prime numbers between " + valueA + " and " + valueB + " are:");
final int LINE = 10;
int count = valueA;
int number = 2;
while (count < valueB) {
// Assume the number is prime
boolean isPrime = true;
// Test if number is prime
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true number is not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}
if (isPrime) {
count++;
if (count % LINE == 0) {
System.out.println(number);
}
else
System.out.print(number + " ");
}
number++;
}
}
}
When you want to work on a range of number, use a for loop instead of while loop to reduce confusion. You obviously want
for(int number = valueA; number <= valueB; number++){/*check if number is prime*/}
Example:
public static void main(String []args){
int valueA = 1;
int valueB = 100;
int count = 0;
for(int number = valueA; number <= valueB; number++)
{
if(isPrime(number))
{
count++;
System.out.println(number);
}
}
System.out.println("count = " + count);
}
public static boolean isPrime(int n)
{
for(int i = 2; i*i <= n; i++)
{
if(n % i == 0)
{
return false;
}
}
return n > 1;
}
For your requirement of checking isPrime inline:
public static void main(String []args){
int valueA = 1;
int valueB = 100;
int count = 0;
for(int number = valueA; number <= valueB; number++)
{
boolean isPrime = number > 1;
for(int i = 2; i*i <= number; i++)
{
if(number % i == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
count++;
System.out.println(number);
}
}
System.out.println("count = " + count);
}

How can I implement a sequence of numbers in this Prime number generator?

I'm unsure of how to create a sequence of numbers that can be placed before each iteration of printed prime numbers. Thank you for any help you can offer.
public class CountingPrimes {
public static void main(String[] args) {
int flag = 0, i, j;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 1st number: ");
int firstNum = sc.nextInt();
System.out.println("Enter the 2nd number: ");
int secondNum = sc.nextInt();
System.out.println("Counting prime numbers between "
+ firstNum + " and " + secondNum + ":");
for (i = firstNum; i <= secondNum; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
System.out.println(i);
}
}
}
}
Right now, my code outputs (after the user enters their two numbers):
Counting prime numbers between 1 and 14:
3
5
7
11
13
What I need my code to look like:
Counting prime numbers between 1 and 14:
1. 3
2. 5
3. 7
4. 11
5. 13
Also, if you could see any errors or improvements I could change, I would greatly appreciate it. Thank you again!
You can use a counter and print the counter as you print the prime number. Increment the counter each time.
int counter = 1;
int flag = 0, i, j;
.....
if (flag == 1) {
System.out.format("%d. %d\n", counter, i);
counter++;
}
a simple change:
import java.util.Scanner;
public class CountingPrimes {
public static void main(String[] args) {
int flag = 0, i, j;
int count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 1st number: ");
int firstNum = sc.nextInt();
System.out.println("Enter the 2nd number: ");
int secondNum = sc.nextInt();
System.out.println("Counting prime numbers between "
+ firstNum + " and " + secondNum + ":");
for (i = firstNum; i <= secondNum; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
System.out.println(++count + "." + i);
}
}
}
}
Just add a count variable and increment it whenever you output a number:
...
int count = 0;
for (i = firstNum; i <= secondNum; i++) {
...
if (flag == 1) {
count++;
System.out.format("%d. %d%n", count, i);
}
}
Declare Count before for loop
int count = 0;
and then increment the count on every prime number.
if (flag == 1) {
System.out.println(++count+". "+i);
}
}

How can I increment the Array

I am not sure if what I am asking is right, but originally i had this run 5 times in the main. however i felt that a do/while loop could do the same thing. But now I cannot get the array shotsMade to change from shotsMade[0] to shotsMade[1] etc, and the shotCount to store to it. It will only store the last run of the while loop. What can I change to make those 2 items increment so the methods still calculate the data correctly
import java.util.*;
public class Final {
public static void main(String[] args) {
int myGameCounter = 1;
int [] shotsMade = new int [5];
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game
do{
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
int shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
System.out.println("");
shotsMade[0]= shotCount;// I need shotsMade[0] to change each loop, shotsMade[1], shotsMade[2], shotsMade[3], shotsMade[4]
} while (myGameCounter <=5);
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game free throws made: " + max(shotsMade));
System.out.println("Worst game free throws made: " + min(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 50");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static int average (int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
int average = total*10 / nums.length;
return average;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max = nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
public static int min(int nums[]) {
int min = nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] < min)
min = nums[i];
}
return min;
}
}
Two things:
Move myGameCounter++; just below where you set shotsMade[]
Otherwise, you are increasing the game counter to 2 before the first game finished.
It should look like:
shotsMade[myGameCounter-1]= shotCount;
myGameCounter++;
} while (myGameCounter <=5);
Set shotsMade[myGameCounter-1]= shotCount; instead of shotsMade[0]= shotCount;
Otherwise, you are overwriting the value of shotsMade[0]
This way, you are re-using a counter as index for the array. Since myGameCounter will increase by one after each game (after you changed point 1) and it starts from 1, using myGameCounter - 1 will yield the correct index for your array shotsMade.

How to find a specific number from a user set upperbound and lowerbound in java

The purpose of my code is to determine the number of times the number 3 appears between a range of numbers, the lower and upper bounds determined by the user.
So far, I can check if the number 3 is in the ten's place my using the modulus. But I am having trouble figuring out if a 3 resides in the hundreds, thousandths, etc. I know I need to use a nested loop, but I can't quite figure out how to code it.
Here is my code so far.
public class JavaThree {
public static void main (String [] args) {
int count = 0;
int num;
System.out.print("Enter lower end: ");
int lowerEnd = IO.readInt();
System.out.print("Enter upper end: ");
int upperEnd = IO.readInt();
if (lowerEnd > upperEnd) {
IO.reportBadInput();
return;
} else {
for(num = lowerEnd; num <= upperEnd; num++) {
if(num % 10 == 3) {
count = count + 1;
} else {
count = count;
}
}
}
IO.outputIntAnswer(count);
}
}
here is proper for loop for your task:
for(num = lowerEnd; num <= upperEnd; num++)
{
int nNum = num;
while (nNum > 0)
{
if( (nNum % 10) == 3)
count = count + 1;
nNum = nNum / 10;
}
}
Another solution, although not as efficient as the solution proposed #Ilya Bursov is to convert the number to a string and count the appearences of the char '3':
int threeCount = 0;
for (int num = lowerEnd; num < upperEnd; num++) {
String strNumber = String.valueOf(num);
for (int i = 0; i < strNumber.length(); i++) {
if (strNumber.charAt(i) == '3') {
threeCount++;
}
}
}

Count of most occurring digit... Find the digit that occurs most in a given number

the following s the code to
Find the number of occurrences of a given digit in a number.wat shall i do in order to Find the digit that occurs most in a given number.(should i create array and save those values and then compare)
can anyone please help me ..
import java.util.*;
public class NumOccurenceDigit
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a Valid Digit.(contaioning only numerals)");
int number = s.nextInt();
String numberStr = Integer.toString(number);
int numLength = numberStr.length();
System.out.println("Enter numer to find its occurence");
int noToFindOccurance = s.nextInt();
String noToFindOccuranceStr = Integer.toString(noToFindOccurance);
char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0);
int count = 0;
char firstChar = 0;
int i = numLength-1;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr)
{
if(i >= 0)
{
firstChar = numberStr.charAt(i);
if(firstChar == noToFindOccuranceChar)
//if(a.compareTo(noToFindOccuranceStr) == 0)
{
count++;
}
i--;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
else
{
System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count);
System.exit(0);
}
}
}
/*
* Enter a Valid Digit.(contaioning only numerals)
456456
Enter numer to find its occurence
4
The number of occurance of the 4 is :2*/
O(n)
keep int digits[] = new int[10];
every time encounter with digit i increase value of digits[i]++
the return the max of digits array and its index. that's all.
Here is my Java code:
public static int countMaxOccurence(String s) {
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++) {
int j = s.charAt(i) - 48;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for (int i = 1; i < 10; i++) {
if (digits[i] > count) {
count = digits[i];
digit = i;
}
}
System.out.println("digit = " + digit + " count= " + count);
return digit;
}
and here are some tests
System.out.println(countMaxOccurence("12365444433212"));
System.out.println(countMaxOccurence("1111111"));
declare a count[] array
and change your find function to something like
//for (i = 1 to n)
{
count[numberStr.charAt(i)]++;
}
then find the largest item in count[]
public class Demo{
public static void main(String[] args) {
System.out.println("Result: " + maxOccurDigit(327277));
}
public static int maxOccurDigit(int n) {
int maxCount = 0;
int maxNumber = 0;
if (n < 0) {
n = n * (-1);
}
for (int i = 0; i <= 9; i++) {
int num = n;
int count = 0;
while (num > 0) {
if (num % 10 == i) {
count++;
}
num = num / 10;
}
if (count > maxCount) {
maxCount = count;
maxNumber = i;
} else if (count == maxCount) {
maxNumber = -1;
}
}
return maxNumber;
}}
The above code returns the digit that occur the most in a given number. If there is no such digit, it will return -1 (i.e.if there are 2 or more digits that occurs same number of times then -1 is returned. For e.g. if 323277 is passed then result is -1). Also if a number with single digit is passed then number itself is returned back. For e.g. if number 5 is passed then result is 5.

Categories