Building a program that can check if a random number is = to a specific number. Here is what I have so far. I am generating a random number 10 times. And I want it to print out "The number (int var) was found (How ever many times it generated) times.". I keep running into problems such as trying to pull static variable from non-static variable. I'm not sure how to check if the integer is = to the random number.
import java.util.Random;
public class Driver{
public static void main(String[] args)
{
Loop.loop4(4);
}
public class Loop
{
public static void loop4(int val)
{
for(int iteration = 1; iteration <=10; iteration ++)
{
Random number = new Random();
number.nextInt(10);
}
System.out.println("The number " + val +" was found " (Dont know how to do this part);
}
}
You should try something like:
int count = 0;
for(int iteration = 1; iteration <=10; iteration ++) {
Random number = new Random();
int n = number.nextInt(10);
if(n == val) count++;
}
System.out.println("The number " + val +" was found " + count + " number of times");
Just compare val with the random number generated and see if they are equal in the if() {...}, keep a counter to keep track of how many times the random number was equal to val.
#thegauravmahawar 's answer seems decent and interesting.
Nonetheless, here's a suggestion on how to enhance your code:
(Don't mind if it's got any minor errors; I wrote it all on nano)
package loop;
import java.util.Random;
public class Loop {
public static void main(String[] args){
int number = 100, range = 100 // Type in any ints
if looper(number, range) { System.out.println("Number %i found!", number) }
else { System.out.println("Number not found!" ) }
}
public bool looper(int numberToBeFound, int range){
guard numberToBeFound<=range else { System.out.println("number to be found is
greater than range!") }
for (int i = 1; i<=range; i++) {
Random randomNumber = new Random();
randomNumber.nextInt(range)
if randomNumber == NumberToBeFound { break; return true } // Unsure if this'll work
}
return false
}
}
Related
I'm using a method to print the largest, second largest, smallest, and second smallest integers. This is what I have so far for the base:
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
This is the method being called so far:
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
The actual output is to formatted like
(largest,secondlargest),(smallest,secondsmallest)
I've never used an array before, and I'm not sure how to use loops with it to find the values. How do I begin this?
Here is the complete code for my program. You can disregard the second and third case, however, I still need help with the third. I need to display all prime numbers in order. Here is the requirement: Twin Prime Numbers: This should let the user specify a limit n (I used limit instead) (if n is 1000, then consider 1
to 1000), and lists the pairs of twin primes up to n. The sample run is (3,5),(5,7),(11,13),(17,19)
The complete code:
import java.util.Scanner;
public class PatternChecker{
// The scanner is accessible for every method included
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// Variables
int limit;
System.out.println("List of Pattern Checker problems:\n1) Largest and Smallest Pairs\n2) Patterns of Triangles\n3) Twin Prime Pairs\n4) Quit");
System.out.print("Choice: ");
int choice = input.nextInt();
// The switch statement for the variable "choice" and each case
switch (choice) {
default:
System.out.println("\n*** INVALID OPTION");
break;
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
case 2:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(triangleOne(limit));
System.out.println(triangleTwo(limit));
System.out.println(triangleThree(limit));
System.out.println(triangleFour(limit));
break;
case 3:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(primePairs(limit));
break;
case 4:
System.out.println("\n*** End");
break;
}
}
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle One)
public static String triangleOne(int limit) {
System.out.println("*** Patterns of Triangles");
for (int x = 1; x <= limit; x++) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Two)
public static String triangleTwo(int limit) {
for (int x = limit; x > 0; x--) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Three)
public static String triangleThree(int limit) {
for (int row = 1; row <= limit; row++) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = row; num > 0; num--) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Four)
public static String triangleFour(int limit) {
for (int row = limit; row >= 0; row--) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = 1; num <= row; num++) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 3 Method: Twin Prime Pairs
public static String primePairs(int limit) {
System.out.println("*** Twin Prime Numbers up to " + limit);
return "";
}
}
Ok based on the comment i have written a quick answer with arraylists. hope this helps.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MaxMin {
private List<Integer> alist = new ArrayList<Integer>();
public static void main(String args[]) {
MaxMin maxmin = new MaxMin();
maxmin.init();
}
public void init() {
System.out.println("Welcome!!!");
readFromUser();
printUserList();
doSort();
display();
}
public void readFromUser() {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.print("Enter the total number of elements :");
Integer totalElements = scanner.nextInt();
for (int i=0;i<totalElements;i++) {
System.out.print("Enter the " + i +" number");
alist.add(scanner.nextInt());
}
}catch(Exception e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
public void printUserList() {
System.out.println("user entered list is :");
System.out.println(alist);
}
public void doSort() {
Collections.sort(alist);
}
public void display() {
System.out.println("(" +alist.get(alist.size()-1)+ "," +alist.get(alist.size()-2)+ ")" + "(" +alist.get(0)+"," +alist.get(1) +")");
}
}
I hope this isn't a homework problem, but the idea is to use a loop with the array, and keep track of the largest and smallest numbers.
Start with assigning the smallest number variable to Integer.MAX_VALUE, so the first number you check will be assigned to the smallest number, because all integer values except 2^31 - 1 are smaller than Integer.MAX_VALUE, and you do that for biggest too, but with Integer.MIN_VALUE.
And then whenever you assign the biggest number again, you assign the secondBiggest variable to the "biggest" variable.
With that in mind, you just need to loop through the values of the array and check if they're larger than the biggest (in which you re-assign it) or smaller than the smallest(same thing as biggest).
int[] array = new int[]{5, 3, 4, 1, 2};
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
^
Example of looping through an array
I created an example for you.
First of all it generates a list of prime numbers till the limit (in this case hardcoded 100). Next it asks for all prime pairs and prints them. The pairs are stored in an ArrayList so it is very easy to get the first and the last pair.
It's not realy hard to understand so I don't know what to explain. Take a look at the code and if you have any questions feel free to ask.
import java.util.ArrayList;
public class PatternChecker {
public ArrayList<Integer> primes = new ArrayList<>();
public static void main(String[] args) {
PatternChecker pc = new PatternChecker();
pc.detectPrimes(100);
ArrayList<int[]> numbers = pc.getPairs();
System.out.println("Print all pairs: ");
numbers.stream().forEach((intA)->System.out.println(intA[0]+" / "+intA[1]));
System.out.println("Print just the greatest and the smallest pair: ");
System.out.println("("+numbers.get(0)[0]+","+numbers.get(0)[1]+")");
System.out.println("("+numbers.get(numbers.size()-1)[0]+","+numbers.get(numbers.size()-1)[1]+")");
}
public void detectPrimes(int limit) {
for(int i=2;i<limit;i++)
if(isPrime(i))
primes.add(i);
}
protected boolean isPrime(int no) {
for(int i=0;i<primes.size();i++)
if(no % primes.get(i) == 0) return false;
return true;
}
public ArrayList<int[]> getPairs() {
ArrayList<int[]> result = new ArrayList<>();
int last = primes.get(0);
for(int i=1;i<primes.size();i++) {
if(primes.get(i)==last+2) {
int[] resH = new int[2];
resH[0] = last;
resH[1] = primes.get(i);
result.add(resH);
}
last = primes.get(i);
}
return result;
}
}
I tried different things in my code, but I always get errors.
The instructions for the program is that I need to have a function (besides from main) that receives arguments for an array of integer values and a second argument telling the desire value to look in the array by the user.
It must also return how many times the desire value is repeated on the array.
The errors are related to the counter and also some are in the main function.
I think I am not returning the counter value correctly.
This is my current code:
import java.util.Scanner;
import java.util.Arrays;
public class ArregloBusqueda2
{
static int findRepetition(int listOfValues[], int targetValue, int counter)
{
int i;
boolean found = false;
for(i=0; i<listOfValues.length; i++)
{
while((counter < listOfValues.length))
{
if(listOfValues[i] == targetValue)
{
counter = counter + 1;
}
}
}
return counter;
}
public static int main(String[] args)
{
Scanner input = new Scanner (System.in);
int targetValue;
int listOfValues[] = {1,6,3,8,5,8,3,4,8,3};
System.out.println("Please enter the desire number to look for: ");
targetValue=input.nextInt();
findRepetition(targetValue, counter);
if(counter != 0)
{
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
}
else
{
System.out.println ("The number " + targetValue + " is not contained in the array list");
}
}
}
Multiple issues in your code.
public static int main(String[] args) should be public static
void main(String[] args)
findRepetition takes three arguments,
but you are passing two agruments
counter variable is not declared
Logical flaw, while((counter < listOfValues.length)) will keep on executing if counter value is less than listOfValues.
static int findRepetition(int listOfValues[], int targetValue) {
int i;
int counter = 0;
for (i = 0; i < listOfValues.length; i++) {
if (listOfValues[i] == targetValue) {
counter = counter + 1;
}
}
return counter;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int targetValue;
int listOfValues[] = { 1, 6, 3, 8, 5, 8, 3, 4, 8, 3 };
System.out.println("Please enter the desire number to look for: ");
targetValue = input.nextInt();
int counter = findRepetition(listOfValues, targetValue);
if (counter != 0) {
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
} else {
System.out.println("The number " + targetValue + " is not contained in the array list");
}
}
You made your method accept three parameters.
static int findRepetition(int listOfValues[], int targetValue, int counter)
Ask yourself - do you want to "pass in a counter", or only return it? The instructions say the latter.
When you call this method, you are not providing the correct inputs.
findRepetition(targetValue, counter);
What about the listOfValues? You want to findReptition on listOfValues for targetValue, right? So provide the correct parameters into that method call.
Again, you likely do not need the counter passed-in. Because Java is always pass-by-value
Rather, you want to return counter, as you have written. You are looking for this.
int counter = findRepetition(listOfValues, targetValue);
Fixing the remainder of the code is a learning exercise.
You are not calling findRepetition() with required parameters, findRepetition method takes 3 arguments, but you are passing only 2 arguments.
So right I was creating a program that made palindromic numbers based on this project. My program would work for the smaller numbers, but integer can only compute a small amount of numbers, so I changed necessary integers to BigInteger(). After doing this Ive ran into some problems that Im not really sure of. Would anyone have any advice as to how to make this work?
public class Main {
public static final boolean DEBUG = false;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//gets the number from the console
int number = input.nextInt();
if(DEBUG) System.out.println("Got your number!");
if(DEBUG) System.out.println("Bout to makePalendrome!");
makePalendrome(number);
}
public static boolean isPalendrome(BigInteger number){
String numberString = number.toString();
for(int i = 0; i < numberString.length(); i++){
if(numberString.charAt(i) != numberString.charAt(numberString.length() - 1 - i)) return false;
}
return true;
}
public static void makePalendrome(int input){
int steps = 0;
BigInteger number = new BigInteger((input + ""));
if(isPalendrome(number)) printResult(input, steps, number);
while(!isPalendrome(number)){
String numberString = number.toString();
String reversed = "";
for(int i = 0; i < numberString.length(); i++){
reversed += numberString.charAt(numberString.length() - 1 - i);
}
BigInteger numReversed = new BigInteger(reversed);
number.add(numReversed);
steps++;
}
printResult(input, steps, number);
}
public static void printResult(int number, int steps, BigInteger palendrome){
System.out.printf("The number %d becomes palendromic after %d steps, and becomes the number: %d%n", number, steps, palendrome);
System.exit(0);
}
}
Your code goes into infinite loop while(!isPalendrome(number)) because,
number.add(numReversed);
this doesn't change the value of number. You need assign it back.
number= number.add(numReversed);
I need my lottery program to count the number of times 0,1,2,3,4 or 5 numbers match after 10 runs, then display them. It is also supposed to keep track of the total jackpot by adding a certain amount to the jackpot depending on how many numbers won. My problem is that is is counting this correctly for each individual run but not for all ten runs total. here is what I have.
package assignment5;
import javax.swing.JOptionPane;
import java.util.Random;
public class assignment5
{
public static void main(String[] args)
{
for(int i = 0; i <10; i++)
{
lottery pic=new lottery();
pic.Get_player_numbers();
pic.Get_jackpot_number();
pic.Check_winner ();
pic.Write_data();
}}
}
class lottery
{
int[] picks= new int[5];
int[] cpick=new int[5];
int i;
int j,c;
int match=0;
void Get_player_numbers ()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="User Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
JOptionPane.showMessageDialog(null,Jackpot,"Output:",JOptionPane.INFORMATION_MESSAGE);
}
//void jackpot()
void Get_jackpot_number()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="Computer Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
JOptionPane.showMessageDialog(null,Jackpot,"Output:",JOptionPane.INFORMATION_MESSAGE);
}
void Check_winner ()
{
for(int i=0;i<=4;++i)
{
for(int j=0;j<=4;++j)
{
if(picks[i]==cpick[j])
{
match=match+1;
}
}
}
}
void Write_data ()
{
String print = "";
int jackpot = 2500000;
int counter0 = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
if(match==0)
{
counter0++;
print=print+"There is no match"+"\n";
print=print+"please try again "+"\n";
jackpot=jackpot+25000;
}
else
if(match==1)
{
counter1++;
print=print+"There is one match"+"\n";
print=print+"You won 100 Dollars "+"\n";
jackpot=jackpot+100000;
}
else
if(match==2)
{
counter2++;
print=print+"There are two matches"+"\n";
print=print+"You won 1,000 Dollars"+"\n";
jackpot=jackpot+250000;
}
else
if(match==3)
{
counter3++;
print=print+"There are three matches"+"\n";
print=print+"You won 10,000 Dollars "+"\n";
jackpot=jackpot+500000;
}
else
if(match==4)
{
counter4++;
print=print+"There are four matches"+"\n";
print=print+"You won 100,000 Dollars "+"\n";
jackpot=jackpot+1000000;
}
else
if(match==5)
{
counter5++;
print=print+"There are five matches"+"\n";
print=print+"You won "+jackpot+" Dollars"+"\n";
jackpot=2500000;
}
JOptionPane.showMessageDialog(null,print,"Output:",JOptionPane.INFORMATION_MESSAGE);
System.out.println("zero matchers occured " +counter0+ " times");
System.out.println("The current jackpot is " +jackpot+ "");
}
}
//end of class lottery
Firstly, I'm not sure to understand everything as your code is a little messy and uncommented, you should try to clear it, it will be easier for you to understand and to find errors.
Concerning the problems that I am seeing:
If I correctly understand you want to keep the "Jackpot" over the 10 rounds. This is not happening because in your main function you are doing
for(int i = 0; i <10; i++)
{
lottery pic = new lottery();
....
}
Therefore you are creating a NEW lottery for each run and it replace the previous lotery by an empty one at each runs. Maybe this instead would work:
lottery pic = new lottery();
for(int i = 0; i <10; i++)
{
....
}
As well be careful to your variables "match" in your lotery class. At the end of "Write_data" I would advice you to do "match = 0;" otherwise matches will not restart at 0 for each run
Trying to write a program with two methods. First one takes an integer and prints its divisors as well as the sum of its divisors, the second is a boolean function that returns if the given integer is equal to the sum of its divisors (a perfect number).
I have the first method done fine but I want to take the integer sum from it and use it in the second method, is this even possible? Iv spent about quite a while trying to research it with no success.
As usual any and all advice appreciated. Code so far is below.
import java.util.Scanner;
import java.io.*;
class arrayTest {
public static int sumFacs(int n) {
int sumDiv[] = new int[50];
int c = 0;
int sum=0;
if(n<0){
System.out.println("Sorry I dont do negatives!");
}
else {
for(int i=1; i<=n; i++){
int j = n%i;
if(j==0){
System.out.println( i + " is a divisor of " + n + "\n");
sumDiv[c] = i;
c++;
}
}
for (int i=0; i<sumDiv.length; i++){
sum += sumDiv[i];}
System.out.println("The sum of the divisors of " + n + " is: " + sum);
}
return sum;
}
public static boolean isPerfect(int n, int sum) {
boolean b = (n == sum);
if(b){
System.out.println( n + " is a perfect number.");
}
else {
System.out.println( n + " is not a perfect number.");
}
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a positive integer.");
int n = scanner.nextInt();
sumFacs(n);
int sumDivisors = sumFacs(n);
System.out.println(isDivisors(sumFacs(n), n));
isPerfect(n, sum);
}
}
Your sumFacs returns an integer, so you can definitely use whatever it yields in your isPerfect method. As you are doing it now, you are passing the same number to the methods. To do what you want, you will need to do something like so:
int sumFacsResult = sumFacs(n); //Take whatever value sumFacs yields, store it in sumFacsResult
System.out.println(isPerfect(sumFacsResult, n); //Take the result of sumFacs and pass it to the isPerfect method
or shorthand:
System.out.println(isPerfect(sumFacs(n), n)); //It is usually recommended to use the other approach, for readability purposed.
And your isPerfect method should be something like so:
public static boolean isPerfect(int sum, int number)
{
return sum == number;
}
your sumFacs(int n) has a return type of int and you are returning sum but where you call that method you are not setting it to anything so what you want to do is:
int foo = sumFacs(n);
isPerfect(n,foo);
and make your isperfect class
public static void isPerfect(int n, int foo)
{
if((n==foo)
{
System.out.println( n + " is a perfect number.");
}else{
System.out.println( n + " is not a perfect number.");
}
}
However this would all be easier in one class not two