Hello everyone I am new to the site and this is my first question from my Java programming class.
I have to create a program that asks a math question and tells the user if he is right or wrong, but the requirements also state that I need to create a method that generates a new question if the first question is correct, so when the computer asks what is 5 times 5 and the user inputs 25 the method should generate two new random numbers and ask the user for a result.
This is my code so far. I don't expect the answers as this is a school assignment but if anyone could give a direction it would be greatly appreciated it as this is my first java college course.
import java.security.SecureRandom; //program uses class SecureRandom
import java.util.Scanner; //program uses class Scanner
public class CAI
{
public static void main(String[] args)
{
System.out.println("Alex - Assignment 4\n");
//create Scanner for input from command window
Scanner input = new Scanner(System.in);
//randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
//generates two random numbers from 1 to 9 excluding 0
int random1 = 1+ randomNumbers.nextInt(9);
int random2 = 1+ randomNumbers.nextInt(9);
int answer; // declares answer from user
//calculates real result of first integer times second integer
int result = (random1 * random2);
//display generated integers
System.out.printf("What is %d times %d?\n",random1, random2);
do
{
answer = input.nextInt(); //keeps taking answer from user if wrong
if(answer == result) //if correct answer then print very good!
System.out.println("Very Good!");
else // if wrong answer then print no please try again
System.out.println("No. Please try again");
}
while (answer != result);
}
I think you have the basic way that your loop statements work mixed up. A do statement is going to execute its block of code once and wont inherently loop on its own. A while loop will repeat until you tell it to stop. So without telling you exactly how to structure your assignment ;) you should look at those two things. But your code does compile and does do one run through of what you want it to do. So this means that the problem you have is in the logic aspect of your code. This means that the computer doesn't understand based on the structure of your code when to execute the sections of your code.
So my advice is to try writing it out in plain English first (pseudocode) that way you can work out how the logic of your program should run and then translate it into code. Sometimes just saying "I want x to happen when y. But I only want this to happen if event z has happened." can help you understand logical how something has to work.
Best of luck
You could add a while loop before the generation of the random numbers that would repeat until answer== "exit". Something along those lines would work fine
You should put a break; statement in the bottom else loop and put everything from your public static void declaration in an "infinite" for loop. When the user inputs an incorrect answer, the program will go to the else loop and break. Otherwise, it will keep on repeating in the "infinite" for loop. Here is a sample code showing what you could do.
import java.security.SecureRandom; //program uses class SecureRandom
import java.util.Scanner; //program uses class Scanner
public class CAI
{
public static void main(String[] args)
{
boolean loopTest = false;
while (loopTest= true)
{
System.out.println("Alex - Assignment 4\n");
//create Scanner for input from command window
Scanner input = new Scanner(System.in);
//randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
//generates two random numbers from 1 to 9 excluding 0
int random1 = 1+ randomNumbers.nextInt(9);
int random2 = 1+ randomNumbers.nextInt(9);
int answer; // declares answer from the user
//calculates real result of first integer times second integer
int result = (random1 * random2);
//display generated integers
System.out.printf("What is %d times %d?\n",random1, random2);
do
{
answer = input.nextInt(); //keeps taking answer from user if wrong
if(answer == result) //if correct answer then print very good!
System.out.println("Very Good!");
else // if wrong answer then print no please try again
System.out.println("No. Please try again");
break;
}
while (answer != result);
}
}
}
*Note that the last } was not included in your program.
Related
Create a java program to find and print all palindrome numbers within b and a
such that a<3000, b<3000and b<a.
My approach:-
import java.util.*;
class PalinDrome_Within_A_Range_Of_Two_Numbers{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter an upper limit<3000");
int a=sc.nextInt();
System.out.println("Enter a lower limit <3000,upper limit");
int b=sc.nextInt();
int c=0;
int d,e,f,j;
for(int i=b;i<=a;i++){
j=(int)(Math.log10(i) + 1);
e=0;
f=0;
d=i;
for(int k=1;k<=j;k++){
f=i%10;
f=(int)(f*(Math.pow(10,(j-k))));
i=(i-(i%10))/10;
e=e+f;
}
if(e==d){
c=c+1;
System.out.println("The "+c+"th Palindrome number between "+b+" and "+a+" is "+d);
}
else{
break;
}
}
}
}
In this program, nothing appears in the output after giving the two integers.
The reason is that the first number, if it is not a palindrome, will end the loop at the else break; statement. To fix the problem, you should also not manipulate i within its loop, but rather a copy of it.
You may think about debugging. Shows you the point of failure faster than Stackoverflow.
Are you absolutely sour you enter uper limit before entering the lower limit because I by intuition added lower limit first and it did not work any way here is a simpler soultion if you want
public class PalinDrome_Within_A_Range_Of_Two_Numbers {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter an upper limit<3000");
int a=sc.nextInt();
System.out.println("Enter a lower limit <3000,upper limit");
int b=sc.nextInt();
int c=0;
int d,e,f,j;
for(int i=b;i<=a;i++){
String num = String.valueOf(i);
String reversNum = getReversStr(num);
if(num.equals(reversNum)){
System.out.println(num);
}
}
}
private static String getReversStr(String num) {
char[] chars = num.toCharArray();
char[] revers = new char[chars.length];
for(int i = chars.length;i>0;i--)
revers[chars.length-i]=chars[i-1];
return new String(revers);
}
}
Others already suggested to use a debugger. That makes sense because your code is quite complicated. (By the way, you should keep the scope of your variables as small as possible to make your code more readable. It makes no sense to declare and initialize a variable outside a loop when it is used only inside the loop body.)
A better approach would be to simplify your code. You could split it into multiple functions and give each of these a meaningful name.
Or you could use a completely different approach. Being a palindrome is not so much a property of the number itself but of its string representation. So why not base the whole algorithm on strings:
for (int i = b; i <= a; i++) {
String num = String.valueOf(i);
String reverse = new StringBuilder(num).reverse().toString();
if (num.equals(reverse)) {
System.out.println(i);
}
}
I see two issues with your code (no guarantee that they are the only two, but solving them should get you a step further at the least).
You are using i as control variable in your outer loop, and then you are modifying i inside your inner loop (i=(i-(i%10))/10;). Since you are taking a copy of i into d anyway, there is a simple fix: do the modification on d instead of on i.
The break; statement in you else part will break out of the outer loop if the first number tried (b) is not a palindrome. I think you can just delete the else part.
I tried entering 102 as upper limit and 99 as lower. Your program correctly prints The 1th Palindrome number between 99 and 102 is 99, but then because i has been modified goes into an infinite loop. So you are on the way.
I agree with what others have said about breaking your code up in less comlex methods. This will also allow unit testing each method, which will help to locate bugs. Better variable names will help understanding the code, not least when you ask others to take a look. Finally, don’t declare a variable until you need it, this will also help readability.
I want to make a program which keeps prompting the user to input integers(from CUI) until it receives a 'X' or 'x' from the user.
The program then prints out the maximum number, minimum number and average value of the input numbers.
I did manage to get the user to input numbers until someone types 'X', but I can't seem to get it to stop if someone types 'x' and the second bit.
This is the code that I have managed to work out:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!in.hasNext("X") && !in.hasNext("x"))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Any hints on how I proceed further?
You will need to do something like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!(in.hasNext("X") || in.hasNext("x")))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Whenever you use while loop you have to use the {} in case the arguments in the while block are more than 1 line, but if they are just of a line then you can just go on without using the {}.
But the problem, you had I suppose is the use of && instead of ||. What the && (AND) operator does is execute if both the statements are true but a || (OR) Operator works if any of the conditions are true.
If you say while(!in.hasNext("X") && !in.hasNext("x")) it makes no sense as the user input is not both at the same time, but instead if you usewhile(!in.hasNext("X") || !in.hasNext("x"))` it makes sense. Understood?
And about sorry, im really new at this. but ive added the code No problem, you need not say sorry but there are a few things to keep in mind before asking a question. You must read this https://stackoverflow.com/help/how-to-ask and yeah one more thing, you should use proper English Grammar while framing your question.
Last of all, about how to calculate the average..., for that what you need to do is store all the input variables into an array and then take out the mean of that or alternatively you could think about it and code something up yourself. Like to take out mean, you could make a variable sum and then keep adding the integers the user enters and also keep a variable count which will keep the count of the number of integers entered and then at last you could divide both of them to have your answer
Update: For checking the minimum and the maximum, what you can do is make 2 new variables like int min=0, max=0; and when the user enters a new variable you can check
//Note you have to change the "userinput" to the actual user input
if(min>userinput){
min=userinput;
}
and
if(max<userinput){
max=userinput;
}
Note: At stackoverflow we are there to help you out with the problems you are facing BUT you cannot exploit this. You cannot just post your homework here. But if you are trying to code something up and are stuck at it and cannot find a answer at google/stackoverflow then you can ask a new question and in that you need to tell what all you have already tried. Welcome to SO! :D Hope you have a nice time here
This would fit your needs:
public void readNumbers() {
// The list of numbers that we read
List<Integer> numbers = new ArrayList<>();
// The scanner for the systems standard input stream
Scanner scanner = new Scanner(System.in);
// As long as there a tokens...
while (scanner.hasNext()) {
if (scanner.hasNextInt()) { // ...check if the next token is an integer
// Get the token converted to an integer and store it in the list
numbers.add(scanner.nextInt());
} else if (scanner.hasNext("X") || scanner.hasNext("x")) { // ...check if 'X' or 'x' has been entered
break; // Leave the loop
}
}
// Close the scanner to avoid resource leaks
scanner.close();
// If the list has no elements we can return
if (numbers.isEmpty()) {
System.out.println("No numbers were entered.");
return;
}
// The following is only executed if the list is not empty/
// Sort the list ascending
Collections.sort(numbers);
// Calculate the average
double average = 0;
for (int num : numbers) {
average += num;
}
average /= numbers.size();
// Print the first number
System.out.println("Minimum number: " + numbers.get(0));
// Print the last number
System.out.println("Maximum number: " + numbers.get(numbers.size() - 1));
// Print the average
System.out.println("Average: " + average);
}
Need to write a java program from pseudo code, I've got a bit of code written, its not working and I'm not sure if i've done it right or not as I simply tried to follow the pseudo code -
Read i
While i > 0
Print the remainder i % 2
Set i to i / 2
import java.util.Scanner;
import java.util.Scanner;
public class InputLoop
{
public static void main(String[] args)
{
int i = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
while (!scan.hasNextInt()) // while non-integers are present
{
scan.next();
System.out.println ("Bad input. Enter an integer.");
}
while (i>0) // while greater than 0
{
int input = scan.nextInt();
System.out.println (i%2);
i = (i/2);
}
}
}
Frankly speaking, you didn't(Ah missed it earlier) exactly followed the pseudo-code. The pseudo code tells you to read i, whereas you are reading input. That's one problem.
Second problem is that, you should read the input outside the while loop where you are doing the processing with the input. That is the 2nd thing you didn't followed.
Currently your while loop is: -
while (i>0) // while greater than 0
{
int input = scan.nextInt();
System.out.println (i%2);
i = (i/2);
}
This is read input from user on every iteration which you don't want.
So, you need to modify your code a little bit: -
int i = scan.nextInt(); // Read input outside the while loop
while (i>0) // while greater than 0
{
System.out.println (i%2);
i = i/2; // You don't need a bracket here
}
How about:
System.out.println(Integer.toBinaryString(i));
The pseudo code reads first (outside the loop), but in your code you read second (inside the loop)
I've typed it exactly as shown in Introduction to Java Programming (Comprehensive, 6e). It's pertaining to reading integer input and comparing user input to the integers stored in a text file named "lottery.txt"
An external link of the image: http://imgur.com/wMK2t
Here's my code:
import java.util.Scanner;
public class LotteryNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Defines and initializes an array with 100 double elements called isCovered.
boolean[] isCovered = new boolean[99];
// Prompts user for input and marks typed numbers as covered.
int number = input.nextInt();
while (number != 0) {
isCovered[number - 1] = true;
number = input.nextInt();
}
// Checks whether all numbers are covered.
boolean allCovered = true;
for (int i = 0; i < 99; i++)
if (!isCovered[i]) {
allCovered = false;
break;
}
// Outputs result.
if(allCovered) {
System.out.println("The tickets cover all numbers."); }
else {
System.out.println("The tickets do not cover all numbers."); }
}
}
I suspect the problem lies within the declaration of the array. Since lottery.txt does not have 100 integers, the elements from index 10 to 99 in the array are left blank. Could this be the problem?
Why does the program terminate without asking for user input?
Possible Solution:
After thinking for a while, I believe I understand the problem. The program terminates because it takes the 0 at the EOF when lottery.txt is feed in. Furthermore, the program displays all numbers not to be covered because the elements from 11 to 100 are blank. Is this right?
The program is written to keep reading numbers until a zero is returned by nextInt(). But there is no zero in the input file, so the loop will just keep going to the end of the file ... and then fail when it tries to read an integer at the EOF position.
The solution is to use Scanner.hasNextInt() to test whether you should end the loop.
And, make sure that you redirect standard input from your input file; e.g.
$ java LotteryNumbers < lottery.txt
... 'cos your program expects the input to appear on the standard input stream.
So my homework tells me to write the equation for a ODD number, the equation must be a factorial if and only if the number is odd.
In my head I the structured came like this (until I don't know how to use the factorial)
import java.util.*;
public class apple {
public static void main(String args []) {
Scanner var = new Scanner(System.in);
int m;
System.out.println("Type in your first number: ");
m = var.nextInt();
if (m==0){ //i don't know if m==0 express the condition to be whole numbers, please tell me which is.
//here I need to check how many divisors there is for my statement
}else if //Again, i don't know how to proceed here, i need to place the condition if M is ODD, how?
//here i need to state (what i guess) the equation of factorial number (in which case, if and only if is odd)
// and than print the results out. That is all the job it needs to be done.
}
}
}
So it seems like you want to print out the factorial of a number if you have an odd number and the divisors of the number if it is even. You haven't specified a way to present the divisors, so here's one way you could do it:
Scanner var = new Scanner(System.in);
int m;
long x=1; //for the factorial, we want to store in a long to combat data overflow
System.out.println("Type in your first number: ");
m = var.nextInt();
//if the input is odd we calculate its factorial
if (m%2==1){
for (int i = 1;i<=m;i++)
x*=i;
System.out.println(m+"!: "+x);
}
else{
System.out.println("1 is a divisor for "+m);
System.out.println("2 is a divisor for "+m);
if (m%3==0)
System.out.println("3 is a divisor for "+m);
//and so on for more divisors of m
}
A first note, you need to add "throws IOException" after your close parentheses in the main declaration since you are asking the computer for input.
How to detect if a number is odd. x=number.
if(x%2==1)
//Then the number is odd
else
//The number is even
How to detect if the number is a whole number: whole meaning an integer greater than 0. You already know its an integer (Thats what you are asking for with nextInt().) so all you need to say is:
if(m>0)
//Then it is whole
Please clarify on anything this did not answer, your question was a bit vague.