Generating multiplication questions in Java - java

The code should output a table for Farenheit and Celsius
public static void main(String[] args) {
System.out.println("Fahrenheit\tCelsius");
System.out.println("=======================");
for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
{
System.out.printf("%5d |", temp);
double sum = (temp + (9.0/5.0)) * 32;
System.out.printf("%5d", (int)sum );
System.out.println();

You need to add a do while() loop to continue with the questions, for example:
static Scanner input;
static Scanner scanner;
static String question;
public static void main(String[] args) {
do {
int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10);
input = new Scanner(System.in);
System.out.print("What is " + number1 + " * " + number2 + "? ");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect. Please try again. What is "
+ number1 + " * " + number2 + "? ");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct. Nice work!");
System.out.println("Want more questions yes or no? ");
scanner = new Scanner(System.in);
question = scanner.next();
}
} while (question.toLowerCase().equals("yes") ||
question.toLowerCase().equals("y"));
}

Simplest way would be do while loop. Example:
do{
// What you want to repeat and make sure to change have way to get out of loop like this:
System.out.print("Want more questions yes or no? ");
question = scanner.next();
}while(question.equals("yes") || question.equals("y"));

There's a few errors in your code but instead of giving you the entire solution to your homework problem I suggest you start with the simple case of reading input until the user enters 'n':
String input = "";
Scanner scanner = new Scanner(System. in);
while (!input.equals("n")) {
System.out.println("continue y/n?");
input = scanner.nextLine();
}
Add the generation of random ints, checking of answers etc inside the while loop body. Make sure to use equals instead of == when comparing two Strings

Related

How to ensure certain requirements are met in my Java Program

public class FileAddClient {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanfile = new Scanner(System.in);
System.out.println("What is the exact name of your file?");
String doc = scanfile.next();
Scanner scanint = new Scanner(new File(doc));
int number1 = scanint.nextInt(), number2 = scanint.nextInt(),
number3 = scanint.nextInt(), number4 = scanint.nextInt(),
number5 = scanint.nextInt(), number6 = scanint.nextInt();
int sum = number1 + number2 + number3 + number4 + number5 + number6;
System.out.println("The sum of the numbers that typed is " + sum);
}
}
How can I ensure that the user enters at least 2 numbers into the file and that the only data types in the file are numbers? I am not sure how to navigate through this problem. I tried making a while loop, but, unfortunately, that is not working. Any help would be appreciated.
The method .nextInt() will throw an exception (specifically an InputMismatchException) in case the input is not an int or there is none.
You can handle that exception with a try-catch block, like this:
try {
// ... use nextInt ...
}
catch(InputMismatchException e) {
// print error message
}
My solution to this uses a while loop. The hasNextInt() function just checks if the input is of type int.
public class FileAddClient {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanfile = new Scanner(System.in);
System.out.println("What is the exact name of your file?");
String doc = scanfile.next();
Scanner scanint = new Scanner(new File(doc));
int count = 0;
int sum = 0; //total sum of numbers
while ( scanint . hasNextInt() ) { //makes sure that the input is of type int
count ++; //counts the number of correct inputs
sum += scanint.nextInt();
}
if ( count < 2 ) // file has one number or zero numbers
System.out.println ( "File has less numbers than expected. Please fix it." );
else if ( count > 6 ) //file has more than 6 numbers
System.out.println ( "File has more than 6 numbers." );
else // file has two numbers or more
System.out.println("The sum of the numbers that typed is " + sum);
}
}

Coin Flip Program With Mutiple Print Issue

I'm just starting Java and this is a coin flip program that I've written recently. So it's supposed to produce sequences of coin flips that meet the requirements that the user sets, however when it gets to the end it should ask if the user wants to go again. I'm having an issue where it will print the question twice when it gets down to end. I really need to figuer this out so any suggestions/clarifications for my code would be greatly appreciated.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
outer: while (true) {
System.out.print("Ready to run a coin flip simulation. Enter the number of sequences: ");
int sequences = scan.nextInt();
System.out.print("How many heads should each sequence have? ");
int heads = scan.nextInt();
System.out.print("How many tails should each sequence have? ");
int tails = scan.nextInt();
System.out.println("Simulating Sequences");
int tFlips = 0;
int mFlips = 0;
for (int i = 1; i <= sequences; i++) {
int h = 0;
int t = 0;
String s = "";
while (t < tails || h < heads) {
if (Math.random() < 0.5) {
h++;
s += "H";
} else {
t++;
s += "T";
}
tFlips++;
}
if (t + h > mFlips) {
mFlips = t + h;
}
System.out.println(i + " - " + s);
h = 0;
t = 0;
s = "";
}
System.out.printf("The average number of flips was " + ((float) tFlips / sequences) + " and maximum was %d", mFlips);
System.out.println("\r\n");
boolean go = true;
while (go) {
System.out.print("Would you like to run another simulation? (y/n): ");
String c = scan.nextLine();
if (c.equalsIgnoreCase("y")) {
break;
} else if (c.equalsIgnoreCase("n")) {
break outer;
} else {
continue;
}
}
System.out.print("\r\n");
}
}
Your String c = scan.nextLine(); reads a new line from your scan.nextInt() calls. You can read more here Scanner is skipping nextLine() after using next() or nextFoo()?
It is good practice to call .nextLine() after every call to .nextInt() to always consume the newline character.
Change the String c = scan.nextLine(); to String c = scan.next();. And you don't really need the while(go) loop, it's more simple if you're doing this:
System.out.print("Would you like to run another simulation? (y/n): ");
String c = scan.next();
if (!c.equalsIgnoreCase("y"))
break;
P.S.: here is a good answer why the nextLine() isn't working correctly. (by #Rohit Jain)

How to find the average in a do-while loop

I have to write a program that asks the user to enter an integer value. After each value, the user has to respond with a "y" or a "n" if he/she wants to continue with the program, and each number the user enters is stated as either odd or even.
I have done this so far with a do-while loop, but I am confused on how to get the averages of the values the user enters. How would you get the average for all the numbers entered?
Here is my code so far:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
do {
int num, count = 0;
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.equals("y"));
}
}
From the Question looks like following things need to handled,
haven't add mechanism for addition into single variable.
put all variable to out from do...while loop body...
created additional variable according to requirement.
see all this things covered by me with following code snippet.
do something likewise,
String answer = "";
double sum = 0; // use for storing addition to all entered values..
int num, count = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter any number : ");
num = scan.nextInt(); // getting input from user through console
sum = sum + num; // add every input number into sum-variable
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
answer = scan.next(); // ask for still want to repeat..
count++;
} while (answer.equals("y"));
System.out.println("Average is : " + sum + "/" + count + " = "+ (sum /count));
In order to calculate Average, you need 2 things: Sum of all numbers and Count of all numbers involved in the Average calculation.
Your sum and count which involved in the Average calculation needs to be out of the do..while scope in order for them to be known at the calculation stage.
I also took the liberty of fixing your code a little bit
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
int count = 0;
int sum = 0;
String answer = "";
do {
System.out.print("Enter any number : ");
int num = scan.nextInt();
boolean isEven = (num % 2 == 0);
System.out.println(num + " is an " + (isEven ? "even" : "odd") + " number.");
sum += num;
System.out.println("do you want to continue?");
answer = scan.next();
count++;
} while (answer.toLowerCase().equals("y"));
System.out.println("Average: " + (sum/count));
}
}
Change your code like this:
import java.util.Scanner;
class ProgramTest {
public static void main(String[] args) {
String answer = "";
int avr =0;
int num, count = 0;
do {
Scanner scan = new Scanner(System. in );
System.out.print("Enter any number : ");
num = scan.nextInt();
if ((num % 2) == 0) System.out.println(num + " is an even number.");
else System.out.println(num + " is an odd number");
System.out.println("do you want to continue?");
avr += num;
answer = scan.next();
count++;
} while (answer.equals("y"));
avr = avr /count;
System.out.println("The avreage of value is:" + avr );
}
}
avr is average. that means when you input an integer. we add num and avr . and when finish looping. we divideto count. like this:
1-5-9-11
avr = 1+5+9+11;
count = 4;
avr = avr/4;

Changing the input I receive from a program from a int to a string beginner

I wrote a program that is supposed to simulate grading quizzes, but I want to change the input I receive from a int to a string, so I can type in a, b, c, d, as the answer to a quiz. How should I do this?
import java.util.Scanner;
public class Quizzes1
{
public static void main(String[] args)
{
int Questions;
int answers;
int Quizzes;
int numOfQs = 0;
String phrase= "";
Scanner scan = new Scanner(System.in);
System.out.println("How many questions are in the quizz?");
Questions = scan.nextInt();
char[] key = new char[numOfQs];
int[] canswers = new int[Questions];
for (int i=0; i<canswers.length; i++)
{
System.out.println("Please give the correct answers " + (i+1) + ": ");
canswers[i] = scan.nextInt();
}
while (!phrase.equals("n"))
{
double Correct = 0;
double Incorrect = 0;
for (int i=0; i<canswers.length; i++)
{
System.out.println("What are the answers that the students put");
answers = scan.nextInt();
if (answers == canswers[i])
Correct++;
else
Incorrect++;
}
System.out.println("There are " +Correct + " correct answers and " +Incorrect
+" incorrect answers");
double Percent = ((Correct / (Correct + Incorrect)) * 100);
System.out.println("The percentage correct is " +Percent +"%");
phrase = scan.nextLine();
System.out.println("Would you like to grade another quiz y/n");
phrase = scan.nextLine();
}
}
}
as a,b,c and d are singls letters, why don't you read characters instead of int or even string?
Just try
scanner.nextLine().charAt(0);
using characters, you can still use this part of your code:
if (answers == canswers[i])
Correct++;
else
Incorrect++;
}
That's pretty similar to dasblinkenligh's answer

A Quiz In Java (Average Guesses Made)

I am coding a quiz game in Java and I can't figure out how to find the average number of guesses a user makes. Here is the game in simple code:
import java.util.Scanner;
import java.io.File;
public class JavaQuiz
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
File file = new File("questions.txt");
Scanner scan = new Scanner(file);
String line;
double lineNum = 0;
int skip = 0;
int correct = 0;
double guesses = 0;
while(scan.hasNextLine()){
// Counting of the line number
lineNum = lineNum + 1;
// Scanning the next line
line = scan.nextLine();
// Declaring the delimeter.
String delimiter = "\\|";
// Splitting the line
String[] temp = line.split(delimiter);
// Print out the questions
System.out.println(temp[0]);
// Wait for the user to input
String keyboard = input.next();
// Take the space off the answer
String two = temp[1].replaceAll("\\s","");
if(keyboard.equals("q")){
skip = skip + 1;
}
else{
while(!(keyboard.equals(two)) && !(keyboard.equals("q"))){
keyboard = input.nextLine();
if(keyboard.equals("q")){
skip = skip + 1;
} else {
System.out.println("Incorrect. Please Try Again");
}
}
if(keyboard.equals(two)){
correct = correct + 1;
}
}
}
System.out.println("You got " + correct + " Questions Correct.");
System.out.println("You skipped " + skip + " questions.");
System.out.println("And for the questions you completed, you averaged " + avg + " guesses.");
}
}
Should I do something like this?
double avg = guesses / lineNum;
I am getting an answer of 0 no matter what though.
After this Line :String keyboard = input.next();
You should do something like this:
if(!(keyboard==null))
guesses++;
then you are right when: avg=guesses/lineNum;
*Tip guesses & lineNum should be int where guesses represents the number of times he answered and lineNum represents the number of lines.There is no need to double here
int takes less space than double on Ram

Categories

Resources