Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
So i got problem in java to determine who the last kid who got the candy, n is how many children, m is how many candy, and s is the number of kid who got the first candy.
so basically if n =4, m=6, and s =2 the answer is 3, because all started from 2(number of kid who got the first candy)->3->4 and restart to 1->2->3 and 3 is the last kid who got the candy.
the code run perfectly but i encounter bug at n = 3333, m =3333, and s = 1
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int s = in.nextInt();
int total = m%n;
int jaw = total+s-1;
System.out.print(jaw);
}
I assume the "bug" you're mentioning is that jaw is 0, right? That's because 3333%3333 will be 0 and thus 0 + s - 1 will be 0 as well (0+1-1 = 0).
You're on the right track, i.e. m % n would tell you how many pieces of candy are left after everyone got a fair/equal share.
Now you just distribute the "rest" (total) which means you "add" it to "first child" (s). Let's say this is c = s + total, so c is the last child that got anything. You subtract -1 because if you add anything the "cursor" advances to the next child and thus you want to track back.
However, what if you didn't have anything to distribute? Then the last child that got anything was the one before the first, which in case of 4 children and starting at 1 would be the 4th. Your calculation results in 0 which basically would express this.
Another problem you might face with your code is that if you start at the last child (say 4) and have 2 pieces of candy to distribute, then you'd get the "5th" child instead of the "1st" to be the last to get something: 2 + 4 - 1 = 5.
So how do you solve that?
Add jaw %= n to handle the "overflow" (if you start at the last child and distributed 2 more pieces of candy, the first would get it)
Check if jaw == 0 in which case the solution would be jaw = n (the last child got the last candy)
The problem is that you arrive at person 0 , who does not exist.
3333%3333 = 0
then 0 + 1 - 1 = 0
As we are in a loop 0 is the last person of the previous turn ie person number m.
We solve this by saying that, if the result is zero we return m.
import java.util.Scanner;
class sweets {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int s = in.nextInt();
int total = m%n;
int jaw = total+s-1;
if(jaw == 0){
jaw = m;
}
System.out.print(jaw);
}
}
You need to consider whenever m%n==0.
In that case jaw= n-s+1;
Just need to add an if statement to include it.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
PROBLEM DESCRIPTION
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
//----------BLANK SPACE BETWEEN TEST CASES-------------
3
5
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int i=0;i<t;i++)
{
boolean prime = true;
long m = in.nextLong();
long n = in.nextLong();
if(m<2)
{
System.out.println("2");
m=3;
}
for(int j=m;j<=n;j+=2)
{
int z = (int)Math.floor(Math.sqrt(j));
for(int k=2;k<=z;k++)
{
if(j%k==0)
{
prime=false;
break;
}
}
if(prime)
System.out.println(j);
}
System.out.println();
}
}
}
Your loops are using int datatype. It is lossy because you are comparing long with int. It will work for small numbers but constraints are too big so try using long.
Edit
I thought its because overflow without running it.
Your code has lots of problems
It will not work when m is even
you are not setting prime back to true in loop
Check these suggestions and comment is it working?
Solution
use long datatype in loop (that is not necessary)
set prime = true in inner loop
instead of incrementing by 2 i.e. j+=2, increment by 1 j+=1.
My homework is to create a program that takes a list of numbers and prints out the highest number divisible by four.
List would look like this:
12
16
87
58
25
73
86
36
79
40
12
89
32
Input should be:
40 because it is the highest number there divisible by four.
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int saved = 0;
int saved2 = 0;
for (int i = scanner.nextInt(); i % 4 == 0; i = scanner.nextInt()) {
for (boolean bull = true; bull == true; bull ^= true) {
if (i > saved) {
saved -= saved2;
saved += i;
saved2 += i;
}
}
System.out.println(saved);
}
}
}
The input of my code is
12
16
I don't really understand why this is doing it, but it seems to me that I'm adding the variables wrong. The homework page on adding variables does not specify how to add variables to each other.
Does anyone have a tip to improve the code in anyway, or find a way to make a fix my code? Thank you.
welcome to Java.
First you are saying you got input, but that is output. Input is what you enter, and output is what you get printed.
Then there is a mistake in your for loops. You have too much going on in one place. By the logic which is implemented, your program will exit first level for loop whenever your entered value is not divisable by 4.
Read on for loops if you want to learn more https://www.learnjavaonline.org/en/Loops.
I recommend to start from while loops instead. The logic whould be this:
1. create variable to hold the correct answer saved
2. create another one to hold the value read from console i
3. start the while loop with condition i = scanner.nextInt()
3.1 check if the value just entered i is divisable by 4
3.2 if it is, then compare if it's larger than the one was saved before (initially saved value will be 0)
3.3 if it is larger, then assign the read value i to the saved
4. At the end of the loop, you will have the highest number divisable by four in your saved variable. Print it.
I will provide some help, according to
How do I ask and answer homework questions?
for (int i = scanner.nextInt(); i % 4 == 0;i = scanner.nextInt())
This only reads as long as ALL inputs are divisible by 4, that is why it ends at 16, because 87 is not divisible by 4.
for (boolean bull = true; bull == true ;bull ^= true)
This needs explanation by you, but I am pretty sure that it unconditionally executes the body of the inner loop exactly once. (Not 100% sure, because the representation of true and false could be weird in your machine. Should 0 be the representation of true, i.e. really weird, then it is an endless loop, which does not match the output you describe...)
System.out.println(saved);
This executes exactly once per input, except the last one, which is not a multiple of 4.
The value of saved is identical to input, as long as it is increasing.
These hints explain the unexpected output.
If you inspect the details of what the problem is, you should be able to improve your coding attempt.
This is how I super-quickly fixed in your code.
Note that there are no statements about the possible minimum value and about how do you stop the input. Therefore the solution is pretty-straightforward, it just reads the input until integers are present there.
This article may be useful about handling the input from the Scanner.
I hope the comments in the code will help. Add comments if there are any questions. Good luck!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int currentMax = Integer.MIN_VALUE; // you may set negative or 0 if you know that all the input is positive
// int saved2 = 0; // no need for this variable
while (scanner.hasNextInt()) { // you can make a better input handling, especially if you know when it should end the input. Now it will end on any non-integer input line
int i = scanner.nextInt();
// for (int i = scanner.nextInt(); i % 4 == 0; i = scanner.nextInt()) {
// for (boolean bull = true; bull == true; bull ^= true) {
if (((i % 4) == 0) && (i > currentMax)) {
currentMax = i;
// saved -= saved2;
// saved += i;
// saved2 += i;
// }
}
}
System.out.println(currentMax); // moved out of "for" or "while" cycles. Print the value after the input has ended.
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
My assignment
I have been tasked with attempting to code this program in Java. I've coded a program I think should work, but no matter what I input as the argument it says everyone has heard the rumor in every situation. I think it has something to do with skipping my while loops and me miswriting something else later on...? I'm completely lost, and because my attempts to troubleshoot what is being executed and what isn't have been failing I don't really know how to fix it. My attempt at coding the problem is below. I've tried to put in a lot of notes to help anyone trying to help me follow along, though I'm not sure if I have out everything down in the right etiquette; sorry if I messed up!
public class ProgrammingProblem1 {
public static void main(String[] args) {
int people = Integer.parseInt(args[0]) ;
//Obtains how many people not including Alice are at the party
boolean[] guests;
double averageheard = 0.0;
// This double will be used at the end to determine on average how many people heard the rumor.
double totalheard = 0.0;
// This double is used to help calculate how many people heard the rumor over all the iterations. Keeps track of the total people who knew the rumor throughout the permutations.
double percentsuccess = 0.0;
// This double will be used at the end to determine the percent of how many times the rumor was heard by everyone against how many loops there were.
double rumorsuccess = 0;
// This keeps track of how many times the rumor went all the way around.
double rumorfail = 0;
// This keeps track of how many time the rumor did not make it all the way around.
guests = new boolean[people];
//Fills the array with as many slots as there are people at the party. Guests is the array that stores if someone has heard the rumor or not.
int runtime = Integer.parseInt(args[1]);
// Guests is to figure out how many guests besides Alice are at the party and set them in an array, and Runtime is to figure out how many simulations you are meant to run.
if (people < 1 || runtime < 0){
//This is to check if the arguments were entered correctly.
System.out.println("You entered the arguments incorrectly. The amount of people at the party besides Alice must be at least two and the simulation must be run at least once.");
}else {
for ( int i = 0; i < runtime ; i++) {
// This is for doing however many iterations through are desired.
int heard = 0;
// This variable will be used at the end to determine if everyone has heard the rumor.
int current = 0 ;
// This ensures that we start with our first person ,"Bob", as the progintor of the rumor. Current is whoever is currently telling the rumor to someone else.
for (int l = 0; l < people; l++){
guests[l] = false; }
guests[0] = true ;
// This ensures that Bob already knows the rumor.
int next = (int)(Math.random() * people) ;
// This randomly selects the first person Bob asks about it. Next is the person we are telling the rumor to
while (current == next) {
// This makes sure that the guest we are doing isn't talking to themselves
next = (int)(Math.random() * people );
}
while ( !guests[next] ) {
// This makes the loop go on until the canidate the person it would tell has already heard it
guests[next] = true;
// This line makes whoever was just told the rumor now knows the rumor
int last = current;
// This keeps track of who the last person who said the rumor was
current = next;
// This is making the person we just told the rumor to our new rumor teller.
next = (int)(Math.random() * people);
// This finds a new person to be told the rumor
while (current == next || last == next ){
// This ensures that the person we tell the rumor to next will not be the person telling the rumor to or the person who told them the rumor.
next = (int)(Math.random() * people); }
}
for ( int j = 0; j < people; ++j) {
// This is to determine how many people heard the rumor before it was terminated.
if ( guests[j] == true){
heard = heard + 1;
}
}
if ( heard == people){
//This if statement will add a counter to rumorsuccess if every person was told the rumor, and to rumorfail if everyone didn't hear it.
rumorsuccess = rumorsuccess + 1;
}
else{
rumorfail = rumorfail + 1; }
totalheard = totalheard + heard;
//This is to tally up how many people heard the rumor in total.
}
percentsuccess = (rumorsuccess / (rumorsuccess + rumorfail)) * 100 ;
// This calculates the percent of times the rumor went all the way around to everyone
averageheard = (totalheard / runtime) ;
// This calculates the average amount of times the rumor made its way around
System.out.println("Steven Mikels 20782");
System.out.println("The amount of people in the room besides Alice are: " + people + ". The amount of times the simulation was run is: " + runtime);
System.out.println("The rumor was heard by everyone in the room " + percentsuccess + " percent of the time. The average amount of people who heard the rumor was: " + averageheard);
}
}
}
EDIT 1: I have updated the code to accommodate my updating of the == related error. I have a few new issues now that the code calculates how many people heard on average correctly, though the percentage of times everyone has succeeded doesn't seem to be working. Entering "3" and then any other number into the command line correctly gives 100% of times gone through everyone hears it. Unfortunately, entering any number of people greater than 3 means the code have 0% chance to go all the way around, which is false. Additionally, entering "2" as the first number seems to make the program stall out command prompt. After some testing, it seems the variable rumorfail and rumorsuccess are always equal to each other.
EDIT 2: I'm fairly certain that I've managed to fix my problem; the variables rumorfail and rumorsuccess needed to be a double! It was rounding the number up or down, resulting in the 0% or 100% marks. Unfortunately, I'm still have an issue where my program won't allow two to be the amount of people or else it freaks out. I'm testing for more reasons on why that may be right now, but didn't want people working on the other issue since it is already solved! Strangely, 0 executes the statement correctly and prints that an invalid number has been inputted, but 1 shares the same problem that 2 did.
Off the bat i see a couple typos:
Youre while statement
while ( guests[next] = false ) { is missing a "="
it should be written like this guests[next] == false or !guests[next]
you also did the same thing in this if statement if ( guests[j] = true){
it should be guests[j] == true
The reason for this extra "=" is that "==" is the comparing operator, and "=" is the operator to set something equal to, so when you do if(x=1) your checking wheter not x CAN be set equal to 1, not if it is equal to 1;
Otherwise your code looks like it would run and calculate, just fix these syntax errors.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Edit: I have found a way to work with CompareTo to help with this problem, but for some reason I cannot get the count down to work.
It's a negative number that needs to get more negative to meet the requirements, but I am missing something here. When I execute the down section it closes the program. So to me this means that I have something messed up and the program isnt seeing the problem and closing.
We are supposed to:
Ask the user for an integer then ask the user if he/she wants to count
up or down. Display a table of numbers where the first column contains
the counter, the second column contains the counter plus 10, and the
third column contains the counter plus 100. Make it so each number
takes up 5 spaces total.
If counting up, the first column should contain numbers 1 through the
user input; If counting down, the first column should contain numbers
-1 through the the negative of the user input;
Do user input validation on the word "up" and "down". Allow for any
case.
import java.util.Scanner;
public class ps1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Comparision string already declared
String up = "up";
String down = "down";
//initialize the counters sum
int sum = 0;
//ask the user for a number
System.out.println("Enter an ending value");
int num1 = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Count up or down?");
String input = keyboard.nextLine();
while (input.equalsIgnoreCase(up) || input.equalsIgnoreCase(down)) {
System.out.println("Count up or down?");
input = keyboard.nextLine();
}
if (input.compareToIgnoreCase(up) == 0) {
if (num1 >= 0)
for (int c = 1; c <= num1; c++) {
sum = sum + c;
System.out.printf("%5d%5d%5d\n", c, c + 10, c + 100);
else
System.out.println("Up numbers must be positive");
if (input.compareToIgnoreCase(down) == 0) {
for (int c1 = -1; c1 <= num1; c1--) {
sum = sum + c1;
System.out.printf("%5d%5d%5d\n", c1, c1 + 10, c1 + 100);
}
}
}
}
}
I see you have figured out core logic. BTW, your code will not compile, there is a syntax error.
Your code would look like this:
print(a a+10 a+100)
I know that it's not valid syntax but you would be able to figure out the correct way to write the code.
To print data properly, you will need following:
https://dzone.com/articles/java-string-format-examples
I would recommend visualizing the output first. In your case, it would look like following: (_are spaces)
Enter an ending value: 2
Direction: Up
____1___11__101
____2___12__102
Also, think about error cases. What will happen in following:
Enter an ending value: -10
Direction: Up
Error: Improper data
You are allowing user to enter a positive num1 and count down using for (int counter1 = -1; counter1 >= num1; counter1--). This makes no sense as counter1 >= num1 resolves to -1 >= 1 which is never true. When direction is down the number must be negative and when direction is up the number must be positive.
You might need to loop until user provides a valid direction. Currently you go down for any input that is not up. A possible solution would be to:
String input;
do {
input = keyboard.nextLine();
} while (!input.equalsIgnoreCase("up") && !input.equalsIgnoreCase("down"));
Please use shorter variable names. counter1 is scoped just to the for loop block so call it i. It's easier to read.
Whichever editor you are using configure auto formatting :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to write the following program sequence.
The first three numbers in the sequence are 1, 1, 2. Every other number in the sequence is the sum of the three previous numbers. The program should prompt the user to enter a limit; the program will stop when the current number in the sequence is greater than or equal to this limit.
For example if I write the limit being 123 I should get: 1 1 2 4 7 13 24 44 81
I tried the following:
import jpb.*;
public class XiaolinSequence {
public static void main(String[] args) {
SimpleIO.prompt("Enter a limit on the largest number to be displayed:");
String userInput = SimpleIO.readLine();
int counter = Integer.parseInt(userInput);
int older = 1;
int old = 1;
int current = 2;
while (current < counter) {
int nextNumber = older + old + current;
older = old;
old = current;
current = nextNumber;
System.out.println(nextNumber);
}
}
}
But I am having trouble getting the sequence to print out.
You need to change how you print things.
The missing 1 1 2 are never printed because they are never stored in nextnumber, the only variable you ever print.
You will get an additional 149 because you print nextnumber without checking it its value is greater than the limit.
For me the output of the following code is 1 1 2 4 7 13 24 44 81 all on new lines.
int counter=123; // replaced IO code so I did not have to download the jar.
int older=1;
int old =1;
int current=2;
System.out.println(older); // prints the first 1
System.out.println(old); // prints the second 1
System.out.println(current); // prints the 2
while(current<counter){
int nextnumber=older+old+current;
older=old;
old=current;
current=nextnumber;
if(nextnumber <= counter)
{
System.out.println(nextnumber);
}
}
Ok since people bashed me for your SimpleIO, use whatever you want to read the input. Instead, I'm going to point out a logic flaw in your code.
For the program to function correctly, you need to print out older instead of current, like so:
while (older < counter)
{
System.out.println(older);
final int nextnumber = older + old + current;
older = old;
old = current;
current = nextnumber;
}
It works just fine.
There is no such thing as SimpleIO in java.lang.
You may want to replace String userInput = SimpleIO.readLine() with
System.out.print("Enter limit: ");
Scanner in = new Scanner(System.in);
String userInput = in.next();
then the code will work.
Oh and by the way, don't forget to print out 1 1 2 before you start the loop.