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.
}
}
Related
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 :)
New to programming.
Before you comment: I understand that their are more efficient ways to do this, and already have. I just feel that understanding the process here will make me a better programmer.
Following pseudo code I saw in class. I wrote a program that takes a integer and prints every prime number up to and including the integer(userinput).
This is what I came up with:
//Import Scanner.
import java.util.Scanner;
//Create class.
public class QuestionTwoA2
{
public static void main(String[] args)
{
System.out.println("Enter an integer:"); //Ask for user input.
int userInteger; //Create scanner object and collect user input.
Scanner keyboard = new Scanner(System.in);
userInteger = keyboard.nextInt();
boolean primeFlag = true; //Condition required for prime number loop.
int outer; //I localised these variables outside the loop so that I
int inner; //could test output by printing it.
//Checks natural numbers in between 2 and userInteger.
for (outer = 2; outer < userInteger; outer++)
{
for (inner = 2; inner < outer; inner++)
{
if (outer % inner == 0)
{
primeFlag = false;
//System.out.println(outer + " " + inner);
break;
}
}
if (primeFlag) //I think this statement causes a logic problem.
System.out.println(outer);
}
}
}
I have/had print statements in various parts of my code just to visualise what values I am comparing to get a remainder. My current output is (for any integer input):
Enter an integer:
9
2
3
Logically my code looks fine but obviously doesn't work, help explaining what is actually going on would be much appreciated.
You should put "boolean primeFlag = true;" inside the first for and before the second for.
Since second for is for detecting whether the "outer" variable is a prime number or not, so before going into that you should set your flag true which is your assumption at first, and in second loop when you are checking all smaller values to see whether it is actually prime or not and change the flag if not.
The purpose of this program is to take in positive integers and once the sentinel value (-1) is hit the program will return the 2 lowest numbers. My program works, but in some scenarios it doesn't. for example if I enter 10,15,20,-1 the program will result in 10 rather than 10 and 15. Here is my program:
public class Small{
public static void main(String [ ] args){
int number;
number=IO.readInt();
int lowest=number;
int lowest2=number;
while (number!=-1){
number=IO.readInt();
if(number>0){
if(number<lowest && number!=-1){
lowest=number;}
else{if((number<lowest2||!(number>=lowest2))&& number!=-1){
lowest2=number;}
}
}
}
IO.outputIntAnswer(lowest);
IO.outputIntAnswer(lowest2);
}
}
The main problem with your code is that you set lowest and lowest2 to the first value you enter. If all the other numbers you enter are higher than the first number, it will never be able to find anything lower.
With your example, the first number is 10 which you assign to lowest and lowest2. When you enter 15, it's not lower than 10, so neither variable can be reset. Same with 20.
You've also got a lot of redundant checks in your if-statements.
public class Small {
public static void main(String [ ] args) {
int number;
int lowest = Integer.MAX_VALUE;
int lowest2 = Integer.MAX_VALUE;
while (number!=-1) {
number=IO.readInt();
if (number > 0) {
if(number < lowest) {
lowest=number;
}
else if (number < lowest2) {
lowest2=number;
}
}
}
}
IO.outputIntAnswer(lowest);
IO.outputIntAnswer(lowest2);
}
The problem is with your logic flow of the program. Here's what the code is doing:
Read in one number, store in both lowest and lowest2.
Go through loop to read in more numbers
2a. If the number is positive, check against lowest.
2a1. If the read in value is lower than lowest, change lowest's value to the read in value.
2a2. Otherwise, if the read in value is lower than lowest2, change lowest2's value to the read in value. Only do this if lowest was not changed.
2b. If the read in value is -1, end the loop.
2c. If the read in value is negative but not -1, continue but don't add the number to lowest or lowest2.
Print out the values for lowest and lowest2.
If you see the error, it's in 2a2. This is linked to the fact that your setup before the while loop is formatted as you did: you made both lowest and lowest2 that first value.
This code would normally run correctly, except for one instance: what if that first value were to be the smallest positive value you entered, with all other values greater than it? lowest2 would be set to that value, and you're checking to see if any other values are smaller than it (which they're not, because they're all going to be greater than it).
Tips for when you're coding:
1) Attempt to develop a logical thinking mentality. Think through how you want to create algorithms for your program. Make sure you don't run into any situations where your program does not run the way you want it to, like in this case (this is called a logic error).
2) Run through your programs by hand when you're finished coding, or after you've run it and got an error. Step through every line of your code, and try to see where and why your code isn't working the way you want it to. Or have someone else see, like a fellow programmer. Sometimes, even the best eyes do not catch their own mistakes.
EDIT:
There are various ways to solve this particular problem. One way is to do what Seeker and Rick did:
1) Set both values to the largest possible Integer value, and thus all values entered will be lower than the first values.
2) Ask for the first two inputs at the beginning before the loop, and check them against each other to set the first two lowest values.
However, I believe there are certain things to watch out for when you're doing something like this. These should all be outlined before you code, of course.
1) What if the user is entering only one or zero valid values? Seeker's method wouldn't work, unless he checks that the first/second value is negative/-1. Rick's method wouldn't work either because at least one of the lowest/lowest2 values would still be that max Integer value.
2) What if there were no positive values entered before the -1? This is similar to number 1, and your ints would be null.
You can certainly use Seeker's and Rick's algorithms, but you should check for these conditions if you use them.
import java.util.Scanner;
public class Small {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Number");
int lowest = scanner.nextInt();
System.out.println("Enter Number");
int lowest2 = scanner.nextInt();
if (lowest > lowest2) {
int t = lowest;
lowest = lowest2;
lowest2 = t;
}
while (true) {
System.out.println("Enter Number");
int number = scanner.nextInt();
if (number == -1)
break;
if (number < lowest2 && number < lowest) {
lowest = number;
} else if (number < lowest2) {
lowest2 = number;
}
}
System.out.println("lowest:" + lowest);
System.out.println("lowest2:" + lowest2);
scanner.close();
}
}
I'm having problems tyring to keep score in my "guessing" game. I have to use a for loop or while loop. I have it so 10 random numbers are created in a text file called mystery.txt and a file reader reads these numbers from the text file.
Your score starts at 0. If the user guesses the correct number from the text file they get -10 points. If they get the number wrong they add the the absolute value difference of the number they guessed from a number in the file. The lower the score in the end the better.
When I only run my if else statement once, it works correctly. Once I loop it more than once it starts to act up.
I have to use an if else statement and a for or while loop. Thanks!
Edit- Turns out I have to use a for loop not a while loop, I'm completely lost now.
How it should work:
When you run the program a text file gets generated with 10 different numbers (I already have the code for that ready) The user gets asked to enter a number, the number the user enters gets compared to the first file on the text file. If it is the same never they get -10 points to their score. If they get it wrong they get the difference of the number the guessed and the number in the text file added to the score. This is suppose to repeat ten times.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class lab4Fall15 {
public static void numberGuessingGame() throws IOException {
Scanner myscnr = new Scanner (System.in);
PrintWriter mywriter = new PrintWriter("mysteryNumber.txt");
int randomNumber;
int i = 0;
i=1;
while (i<=10) {
Random randomGen = new Random();
randomNumber= randomGen.nextInt(11);
// then store (write) it in the file
mywriter.println(randomNumber);
i = i + 1;
}
//Decided to use a loop to generate the numbers-------
mywriter.close();
FileReader fr = new FileReader("./mysteryNumber.txt");
BufferedReader textReader = new BufferedReader(fr);
int numberInFile;
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
int score= 0;
int a = 1;
while (a<=10) {
a=a+1;
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
if (userNumber==numberInFile){
score = score-10;
}
else{
score = score + Math.abs(userNumber-numberInFile);
}
System.out.println ("current score is: "+score);
}
System.out.println ("your score is "+score);
textReader.close();
}
public static void main(String[] args) throws IOException {
// ...
numberGuessingGame();
}
}
if (userNumber==numberInFile){
score = score-10;
}
I don't understand what you going to mean. but I can guess this. your above code not show any error. normally , you check your , above part of code. you take variable 'numberInFile'. sometime , your file reader take this with 'whitespace or String or e.t.c' . first you check this out put .you put manual data to this variable and check out put. if it work fine , you correct that function.
OK, first, let's just go over for loops, since that's what your question was asking about. From the code you provided, it seems that you already understand while loops, and that's good, because in Java, for loops are (usually) just while loops in disguise. In general, if you have this while loop,
int a = 0;
while (a < 10) {
// do stuff with a
a = a + 1; // or ++a or a++
}
You can always rewrite it like this:
for (int a = 0; a < 10; a = a + 1) {
// do stuff with a
}
By convention (and this convention is useful when you study arrays and Collection types) you'll want to index your loops from 0 rather than 1. Since you're just learning, take my word for it for now. Loop from 0 to n-1, not from 1 to n.
With that out of the way, let's tackle why you're getting the wrong answer (which, incidentally, has nothing at all to do with loops). Rewritten as a for loop, the ask-and-score part of your program looks like this.
for (int a = 0; a < 10; ++a) {
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber = myscnr.nextInt();
if (userNumber == numberInFile){
score = score - 10;
} else {
score = score + Math.abs(userNumber - numberInFile);
}
System.out.println ("current score is: "+score);
}
You will note that nowhere in this section do you update the value of numberInFile. That means that every run of this loop is still looking at whatever value that variable had at the beginning of the loop. That value came from this line:
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
That line is executed exactly once, before the loop runs. If you want to load the next number every time the user guesses a number, you'll need to move it inside the loop. I'll leave that as an exercise to the reader.
You are not actually capturing the number the user is entering. Try this:
int userNumber = Integer.parseInt(KeyIn.readLine());
folks... the XOR Gate is still giving me a hard time. I'm really close to finishing it but some of the test cases are failing. My specs say that if I have more than two of 1 (High Signals) such as:
111100 or 111 or 11 or 00 or 0000 so the output should be 0 (Low Signal).
Else if any input signal is 'X' the output is also X such as
XX00111 or XX10 or 0X01 then the output should also be X
Else if all the input signals are known (no X signals) and there is EXACTLY one 1 signal then the output is 1 such as
000001 or 10000 or 01 or 10 then the output should be 1
Note: All of the getters and setter methods are correct (tested) and Signal.HI ==1, Signal.LO = 0 and Signal.X = X.
Could smb help me with this method? When the inputs signals are 011 the output should be 0 when Im getting 1. Secondly, when the inputs are XX Im getting 0 when it should be X. Could smb please hint me or help me? Thanks in advance!
#Override
public boolean propagate()
{
Signal inputSignal;
int countHI = 0;
List<Wire> inputs = getInputs();
Signal temp = getOutput().getSignal();
for(int i = 0; i < inputs.size(); i++)
{
inputSignal = inputs.get(i).getSignal();
if(inputSignal == Signal.X)
{
getOutput().setSignal(Signal.X);
break;
}
else if(inputSignal == Signal.HI)
countHI++;
else if(inputSignal == Signal.LO)
getOutput().setSignal(Signal.HI);
}
if(countHI > 2 || countHI == 0)
getOutput().setSignal(Signal.LO);
....................................further unnecessary code for this problem
Here is what is happening:
When you are detecting an input signal of X, you are setting the output as X, and breaking out of the loop... but the last IF statement is still being executed, and so because your input is 'XX', countHI is zero, and so the last if condition is satisfied and you end up overriding the output signal by setting it to 0 at the end of your code. The break only breaks out of the loop it is currently in.
Your code only checks if hiCount is greater than 2 in the last if statement, but you expect it to be false when there are two or more 1's, so when you have exactly two 1's, you do not enter that if condition.
You need to think about your solution logically and run through it yourself and then you will realize why it is not working as you expect.
Here's how I would code it. Note that I only set the signal when I'm sure that it's the correct value: after the loop.
Also note that I make all the cases mutually exclusive.
boolean hasX = false;
boolean hiCount = 0;
for (Wire wire : inputs) {
Signal inputSignal = wire.getSignal();
if (inputSignal == Signal.X) {
hasX = true;
// optimization: break out of the loop early since we know
// that, whatever the number of HI and LO, if there is one
// X, the result is X
break;
}
else if (inputSignal == Signal.HI)
hiCount++;
}
}
if (hasX) {
getOutput().setSignal(Signal.X);
}
else if (hiCount == 1) {
getOutput().setSignal(Signal.HI);
}
else {
getOutput().setSignal(Signal.LO);
}