I've been doing a Java MOOC, and I'm stuck on a submission as my program does not terminate although I get desired output.
The problem says:
Create a method called printText which prints the phrase "In a hole in the ground there lived a method" and a newline. Then expand the program so that the main program asks the user for the number of times the phrase will be printed (i.e. how many times the method will be called).
I think the problem might be in my while loop not getting terminated.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How many times?");
int n = Integer.valueOf(scanner.nextLine());
int a = 0;
while (true) {
if (a < n) {
printText();
a++;
}
}
}
public static void printText() {
System.out.println("In a hole in the ground there lived a method");
}
Your a < n condition should be associated with your loop. Although the if ensures that printText() is only called n times, it does not prevent the infinite loop from continuing forever:
while (a < n) {
printText();
a++;
}
Alternatively, you can keep your infinite loop but break when a >= n:
while (true) {
if (a < n) {
printText();
a++;
} else {
break;
}
}
But the first solution is more readable, in my opinion.
You are almost on track, get rid of outer loop while loop and change if (a < n) to while(a<n)
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How many times?");
int n = Integer.valueOf(scanner.nextLine());
int a = 0;
while(a < n) {
printText();
a++;
}
}
public static void printText() {
System.out.println("In a hole in the ground there lived a method");
}
}
Related
I'm working on a Farkle assignment in Java, and I need the round to end and points to be lost for that turn if no 1s or 5s are rolled on the dice. The code I have will end the round if the first roll of the dice doesn't have any 1s or 5s, but the game will keep letting me roll until I get nothing but 1s and 5s if that makes sense. The prompt for this portion reads:
"The inner do-while loop
controlls each round of the game, ending when the user chose to secure their earned points
or when no further points were rolled."
Here's what I've got this far:
import java.util.Scanner;
import java.security.SecureRandom;
public class Farkle
{
static int[] rolls = new int[]{0,0,0,0,0};
static int round=0, totalScore=0, count1s5s =0;
public static void reset()
{
for(int i=0;i<5;i++)
rolls[i]=0;
}
public static int returnPoints()
{
int sum=0;
for(int i=0;i<5;i++)
{
if(rolls[i] == 1)
sum=sum+100;
if(rolls[i]==5)
sum=sum+50;
}
return sum;
}
public static void countFace()
{
for(int i=0;i<5;i++)
{
if(rolls[i] == 1 || rolls[i]==5)
count1s5s++;
}
}
public static void rollDice()
{
SecureRandom rand = new SecureRandom();
for(int i=0;i<5;i++)
{
if(rolls[i]!=1 && rolls[i]!=5)
{
int randValue = rand.nextInt(6)+1;
rolls[i] = randValue;
}
}
}
public static void display()
{
for(int i=0;i<5;i++)
{
System.out.print(rolls[i]+" ");
}
System.out.println();
}
public static void main(String[] args)
{
while(totalScore<1000)
{
char ch;
round++;
System.out.println("Beginning round "+round);
do
{
count1s5s = 0;
System.out.printf("Your roll: ");
rollDice();
display();
countFace();
System.out.printf("Keep rolling? (y/n) ");
Scanner in = new Scanner(System.in);
ch = in.next().charAt(0);
if(count1s5s == 0)
{
System.out.println("No new points scored; the round ends in a loss");
break;
}
}
while(ch!='n');
totalScore = totalScore+returnPoints();
System.out.println("Round "+round+" complete. Your current score is "+totalScore);
reset();
}
}
}
I've tried placing my if statement in my main class in different places within the do-while, but that hasn't done what I was hoping it would and rearranging the do-while hasn't done it either. I'm stuck and any help would be appreciated. Please let me now if there's any further clarification needed.
The problem is that you're not differentiating between what you rolled previously vs. what you rolled this round. countFace() can't tell whether a 1 or 5 was rolled this round or last round. Split this into two different arrays / Collections to solve the problem.
Right now, you're asking the user whether to keep rolling even if no 1's or 5's are rolled; is that what you want?
Also, create a SecureRandom just once, not every time through the loop.
Here is my main method, I am trying to call the Fibonacci sequence to tell me what number would be at the location the user inputs:
import java.util.Scanner; //import Scanner
public class Main {
public static void main(String[] args) {
System.out.println("enter number");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
Fibonacci fibonacci_test = new Fibonacci();
fibonacci_test.Recursivefibonacci(n);
}
}
Here is my Fibonacci code that I have:
public class Fibonacci {
//Fn=F(n-1)+F(n-2)
//The recursive Fibonacci method
public int Recursivefibonacci(int n) {
if(n==0) {
return 0;
} if(n==1) {
return 1;
}else {
int fib = Recursivefibonacci(n-1)+Recursivefibonacci(n-2);
return fib;
}
}
}
I cannot get this thing to print anything. How can I fix this?
It's because you're not printing anything else.
Your method doesn't print anything (just returns a value), and your main doesn't print anything (aside from "enter number").
You can try changing: fibonacci_test.Recursivefibonacci(n); to println (fibonacci_test.Recursivefibonacci(n));
It would be more appropriate to return Recursivefibonacci(n-1)+Recursivefibonacci(n-2);rather than storing it in a variable.
I did this in python, you can have a look, try to adapt it to java, this might help you. Recursivity can be a headache but seems good.
def fib(n):
if n == 0:
return 0
if n <= 1:
return 1
res = (fib(n-1)+ fib(n-2))
return res
///////
Probably your code will look somehow like this:
public int Recursivefibonacci(int n) {
if(n == 0){
return 0;
}
if(n <= 1) {
return 1;
}
int fib = Recursivefibonacci(n-1)+Recursivefibonacci(n-2);
return fib;
}
Try it! and let me know if it worked.
i'm new in coding and tried to do some open university tasks. Maybe you guys can give some helping hand. I really even don't know how to start this task, witch is divide three Integers from main to method. Example 2, 10 where I should print 3, 6, 9 or 2, 6 where I should print 3, 6.
import java.util.Scanner;
public class divideByThree {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
divideByThree(2, 10);
}
public static void divideByThree(int start, int end) {
while(true) {
if (start % 3 == 0) {
start++;
}
if (end % 3 == 0) {
System.out.println(end);
}
System.out.println(start);
}
}
}
How about the following implementation about divideByThree method?
public static void divideByThree(int start, int end) {
for(int i = start; i <= end; ++i){
if(i%3==0){
System.out.print(i+" ");
}
}
}
Do not use while(true) because it creates an infinite loop which will unnecessarily make your program complex.
You need to increase start by 1 in each iteration and terminate the loop when the value of start value goes beyond end.
Whenever start % 3 == 0 becomes true, print start.
Given below is a sample code which you can use to understand the points mentioned above.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter the start number: ");
int start = reader.nextInt();
System.out.print("Enter the end number: ");
int end = reader.nextInt();
divideByThree(start, end);
}
public static void divideByThree(int start, int end) {
while (start <= end) {
if (start % 3 == 0) {
System.out.println(start);
}
start++;
}
}
}
A sample run:
Enter the start number: 3
Enter the end number: 9
3
6
9
Recursive Approach
import java.util.Scanner;
public class DivideByThree {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int start = reader.nextInt();
int end = reader.nextInt();
divideByThree(start, end);
reader.close();
}
public static void divideByThree(int start, int end) {
if(start % 3 == 0) {
System.out.println(start);
}
if( start <= end) {
divideByThree(++start, end);
}
}
}
The while(true) is an endless loop (something you would want to avoid). It will only stop if you add a break statement somewhere inside it, which you do not have.
I assume this is the issue you need to solve. The key to solving it is simply making sure that your loop stops at some point. How do you do that?
True is a boolean value. a while loop runs again and again for as long as the specified condition remains true, and in your case - it is always true. What you need to do is replace while(true) with while(some condition that will be false at some point). In your specific case, while(start <= end) seems appropriate - just make sure to increment start at every iteration.
Another way of doing it would be using a for loop, i.e:
for (int i = start; i <= end; i++) {
// your code
}
This type of loop takes care of stating the conditions for which the loop should keep on running, and also takes care of incrementing the index i to make sure the loop stops running at some point.
I will make some small changes in your code only so that you will be able to understand quickly.
public static void divideByThree(int start, int end) {
while(start! =end) {
if (start % 3 == 0) {
System.out.println(start);
start++;
}
}
}
So I've written this code in java which should output numbers on the screen from 1 to n(given by the user) and it should write "-prime" near the ones that are prime.
import java.util.Scanner;
public class primeMass {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
int i,j;
System.out.print("Dati n: ");
n = sc.nextInt();
for(i=1;i<=n;i++)
for(j=2;j<=n/2;j++)
{
if(i%j==0)
System.out.println(i);
else System.out.println(i +"-prime");
}}
}
If I input 6 for example i get :
Dati n: 6
1-prime
1-prime
2
2-prime
3-prime
3
4
4-prime
5-prime
5-prime
6
6
I'm new to this, and i'm really struggling with my algorithmic, could you tell me how should i change my program so it outputs correct values, and explain to me what i did wrong ? Thank you
UPDATE:
I've done it, thank you everyone for helping me out : this is the outcome:
import java.util.Scanner;
public class primeMass {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
int i,j;
boolean gasit = false;
System.out.print("Dati n: ");
n = sc.nextInt();
for(i=1;i<=n;i++) {
gasit=false;
for(j=2;j*j<=i;j++)
{
if(i%j==0) gasit=true;}
if(!gasit) {System.out.println(i+"-prime");}
else {
System.out.println(i);}
}
}
}
You print something on every iteration of the inner loop.
Instead, you should print something after all iterations have completed, e.g.
boolean found = false;
for(j=2;j<=n/2;j++) {
if(i%j==0) found = true;
}
if (!found) {
System.out.println(i + "-prime");
} else {
System.out.println(i);
}
Additionally, you shouldn't be going up to n/2: you perhaps mean i/2 (a number doesn't have any factors greater than itself); but you can make it even tighter, since you don't have to check for factors greater than sqrt(i). Or, stated another way, that j * j <= i.
So you can make your loop declaration:
for(j=2; j*j<=i; j++) {
The problem is that the second loop goes until n/2, it should go until i/2 to check if i is prime. A more optimzed version of the primality check algorithm goes until sqrt(i), as suggested in comments.
The next issue is that you are concluding, in a false way, that if in the first case if(i%j==0) you say not prime, otherwise you say it is prime, which is not true necessairly. You should iterate the whole interval of values between [2:i/2] to conclude that i is prime.
Hi I have to make a program(java) on which you input a number and it outputs the number of factors it has(EX: 4 ---> 3)
Code:
package Class;
import java.util.Scanner;
public class Profgrams {
public static void main(String[] args) {
System.out.println("Enter the number;");
Scanner scan = new Scanner(System.in);
long n = scan.nextLong();
for(int i=1, f=0; i <= n; i++){
if(n % i == 0){
f++;
}
System.out.println(f);
}
}
}
Thanks for help.
Declare and initialize f before the loop, and then print the result after the loop terminates. That way printing will not occur at each iteration of the loop.
int f = 0;
// ...
System.out.println(f);