I'm working on another assignment and am stuck. First off, I realize I probably won't get the results I want from this code, but at the moment I can't run the code to even see how close or far away I am. I'm sure I'm missing something simple and hope that something will pop out to someone here so I can move past this point. My mother tongue is English but I'm living in Sweden and trying to learn code in a Swedish class so I added //for translations.
Again, I am working with very basic code so am not looking for an easy hack, more of just some insight to where I have gone wrong.
My assignment is to ask the user to enter 10 numbers, store those as an array. Then, offer the user 4 options to calculate those numbers and a 5th option to quit the program.
Here's what I have so far:
package inlämningsuppgift3;
import java.util.Scanner;
import java.util.Arrays;
public class Inlämningsuppgift3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal = 0;
int[] num = new int[10];
int sum = 0;
int min = 0;
int max = 0;
for (nr = 0; nr < 10; nr++) {
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr] = tal;
if (nr == 0) { //first number
min = tal;
max = tal;
}
else { // All other numbers
if (tal > max) { max = tal; }
if (tal < min) { min = tal; }
}
sum = sum + tal;
}
{
// What would you like to do?
System.out.println("Välj vad du vill göra?");
// Show largest number
System.out.println("1: Visa storsta talet.");
// Show smallest number
System.out.println("2: Visa minsta talet.");
// Show average
System.out.println("3: Visa medeltalet.");
// Show all numbers
System.out.println("4: Visa alla inmatade tal.");
// Quit
System.out.println("5: Avsluta");
}
do {
int k = input.nextInt();
if (k == 1) {
// Largest number is:
System.out.println("Storsta talet är: " + max);
}
else if (k == 2) {
// Smallest number is:
System.out.println("Minsta talet är: " + min);
}
else if (k == 3) {
// Average number is:
System.out.println("Medeltalet är: " + sum/10);
}
else if (k == 4) {
// All the entered numbers:
System.out.println("Alla tal: " + num[10] + ", ");
}
else if (k==5) {
// Goodbye
System.out.println("Hej då!");
break;
}
else {
System.out.println("Felaktigt, prova igen.");
// Unrecognized, try again.
}
while (k<5);
}
}
}
I'm getting error on the last 3 } and I'm not sure why. Are they in the wrong place? I've tried moving them around, I've tried deleting them (obviously, didn't help either) I tried changes to my {} placement above in the code and just haven't found a way around this error. Thank you in advance for any input!
java do-while syntax is:
do {
// Statements
}while(Boolean_expression);
so, change it to:
int k = 0;
do {
k = input.nextInt();
if (k == 1) {
System.out.println("Storsta talet är: " + max);
} else if (k == 2) {
System.out.println("Minsta talet är: " + min);
} else if (k == 3) {
System.out.println("Medeltalet är: " + sum / 10);
} else if (k == 4) {
System.out.println("Alla tal: " + num[10] + ", ");
} else if (k == 5) {
System.out.println("Hej då!");//good bye
break;
} else {
System.out.println("Felaktigt, prova igen.");
}
} while (k < 5) ;
and after while line must be two } now.
Hej Hej!
I made the modifications I think like you asked to make it 'just about work'
package Dunno;
import java.util.Scanner;
public class NumberCollector { //No special characters in source files,
//Can get transformed during deployment
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal =0;
int[] num = new int[10];
int sum = 0;
int min=0;
int max=0;
for (nr=0; nr<10; nr++)
{
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr]=tal;
if(nr == 0) //first number
{
min=tal;
max=tal;
}
else //all other numbers
{
if(tal>max)max =tal;
if(tal<min) min=tal;
}
sum = sum + tal;
}
System.out.println("Välj vad du vill göra?");
//what would you like to do?
System.out.println("1: Visa storsta talet.");
//Show largest number
System.out.println("2: Visa minsta talet.");
//show smallest number
System.out.println("3: Visa medeltalet.");//show average
System.out.println("4: Visa alla inmatade tal.");
//show all numbers
System.out.println("5: Avsluta");//quit
while (true) //Moved the stop condition to start of the loop makes it easier to read logically.
{
int k = input.nextInt();
if (k==1)
{
System.out.println("Storsta talet är: " + max);
//largest number is:
}
else if (k==2)
{
System.out.println("Minsta talet är: " + min);
//smallest number is:
}
else if (k==3)
{
System.out.println("Medeltalet är: " + sum/10);
//average number is:
}
else if (k==4)
{
System.out.println("Alla tal: " + num[10] + ", ");
//all the entered numbers:
}
else if (k==5)
{
System.out.println("Hej då!");//good bye
break;
}
else
{
System.out.println("Felaktigt, prova igen.");
//unrecognized, try again.
}
};
}
}
I only had to move around some braces.
It seems to broadly do what you want? It throws an exception if you ask for result 4, I'll leave that to you :)
Maybe this will be a good starting point? Consider replacing the loop with a switch/case condition would be nicer to read and maintain?
Related
I have a condition where if the user inputs a negative number or a number which is more than 100, or a string, an error message should be printed "That wasn't a valid percentage, I need a number between 0-100. Try again." and ask the user to reenter a valid number. and if the user decided to just enter, all the input should be calculated and printed the average amount.
public static void main(String[ ] args) {
int count = 0; //count to stop loop
double[ ] aGrade = new double[SIZE];
String input = new String("");
Scanner scan = new Scanner(System.in);
double total = 0;
int gTotal = aGrade.length;
boolean exit = false;
while ((count < SIZE) && (!exit)) {
System.out.print("Enter number " + (count + 1) + ": " + "\n");
try {
input = scan.nextLine();
if (Double.parseDouble(input) > 0 && Double.parseDouble(input) < 100) {
aGrade[count] = Double.parseDouble(input); //put into the array
count++; //only increment count if success
} else
System.out.println("That wasn't a valid percentage,"
+ " I need a number between 0-100. Try again.");
} catch (NumberFormatException nfe) {
exit = true; //exit loop
}
}
System.out.println("number of grades entered: " + count + "\n");
for (int i = 0; i < count; i++) {
// print entered grade
System.out.println("grade " + (i + 1) + ": " + aGrade[i]);
}
for (int i = 0; i < count; i++) {
total += aGrade[i];
}
// calculate and print the average
System.out.println("\n" + "Average grade: " + total /count);
But when I run my code, if I input letters, it won't allow the user to reinput value but prints whatever is calculated. I think it is in my if-else statement, but I am not sure how
When we try to convert String to Double it will throw java.lang.NumberFormatException. So whenever you enter String or char at that time instead of else it will go to catch block. As per your code else block only executed when user enter negative number or grater then 100 number.
I updated your code. Please review it.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
int count = 0; // count to stop loop
double[] aGrade = new double[3];
String input = new String("");
Scanner scan = new Scanner(System.in);
double total = 0;
int gTotal = aGrade.length;
boolean exit = false;
while ((count < 3) && (!exit)) {
System.out.print("Enter number " + (count + 1) + ": " + "\n");
try {
input = scan.nextLine();
if (Double.parseDouble(input) > 0 && Double.parseDouble(input) < 100) {
aGrade[count] = Double.parseDouble(input); // put into the array
count++; // only increment count if success
} else
System.out
.println("That wasn't a valid percentage," + " I need a number between 0-100. Try again.");
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
exit = true; // exit loop
}
}
if (!exit) {
System.out.println("number of grades entered: " + count + "\n");
for (int i = 0; i < count; i++) {
// print entered grade
System.out.println("grade " + (i + 1) + ": " + aGrade[i]);
}
for (int i = 0; i < count; i++) {
total += aGrade[i];
}
// calculate and print the average
System.out.println("\n" + "Average grade: " + total / count);
}else {
System.out
.println("That wasn't a valid percentage," + " I need a number between 0-100. Try again.");
}
}
}
If you type letter as an input, you will never end up in your else part of the if statement since code inside if throws an exception and you are then inside catch part. Also, you wrote inside catch part, when NumberFormatException happens(when you enter letter instead of number), set exit to true and that is the reason why program don't let you type again after you input letter. Fix those things and it will work. Also, take a look at how to debug your program, learn that skill, it will help you to solve this kind of problems in the future.
Try something like this:
boolean ok = false;
try {
input = scan.nextLine();
if ("".equals(input)) {
ok = true;
exit = true;
} else if (Double.parseDouble(input) >= 0 && Double.parseDouble(input) <= 100) {
aGrade[count] = Double.parseDouble(input); //put into the array
count++; //only increment count if success
ok = true;
}
} catch (NumberFormatException nfe) {
// nothing
}
if (!ok) {
System.out.println("That wasn't a valid percentage,"
+ " I need a number between 0-100. Try again.");
}
I'm writing a program to take in commands from the user, and output accordingly. The program keeps asking for input, until the user inputs "Quit" as a command.
Commands are:
Factorial # (takes one number as an argument)
Outputs the factorial of the number, Ex.
Factorial 5
5! == 120
GCD # # (Takes 2 numbers as arguments)
outputs the greatest common divisor between 2 numbers (Recursively.) Ex.
gcd 5 10
gcd(5, 10) == 5
Sorted # #... (Takes as many numbers as the user wants)
checks to see if the numbers after the command are in order. Ex.
sorted 1 2 3 4 5
That list is sorted.
sorted 1 2 3 5 4
Out of order: 4 after 5.
Now all this works pretty good. nothing wrong as of now, what im struggling with, when the user enters a letter instead of a number, it should try and catch an InputMismatchException, this kind of works. for example.
if the user enters a letter it would say this.
Factorial j
Not a number: For input string: j
BUT
Factorial 5 j
5! == 120
it would go on how it normally would, but it takes the "j" as the next command, for so if i type Factorial 5 quit, it would print the factorial then quit, i don't know why this is happening.
another thing is i want to throw and catch an exception if the arguments are too much for the command, so the user cant type Factorial 5 10, and it would just calculate the factorial of 5, it would print an error message, i dont know how to achieve this.
Heres my code as of now.
A09.java
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
*
*
* #author Amr Ghoneim (A00425709)
*
*/
public class A09 {
static int counter = 0;
#SuppressWarnings("resource")
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.next().toLowerCase();
// FACTORIAL
if (commands[1].startsWith(command)
&& commands[1].contains(command)) {
try {
int num = scnr.nextInt();
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// GCD
} else if (commands[2].startsWith(command)
&& commands[2].contains(command)) {
try {
int numA, numB;
numA = scnr.nextInt();
numB = scnr.nextInt();
System.out.println("gcd(" + numA + ", " + numB + ") == "
+ GCD(numA, numB));
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// SORTED
} else if (commands[0].startsWith(command)
&& commands[0].contains(command)) {
try {
List<Integer> nums = new ArrayList<Integer>();
StringTokenizer st = new StringTokenizer(scnr.nextLine(),
" ");
while (st.hasMoreTokens()) {
nums.add(Integer.parseInt(st.nextToken()));
}
sorted(nums);
} catch (NumberFormatException nfe) {
System.out.println("Not a number: For input string: ");
}
// QUIT
} else if (commands[4].startsWith(command)
&& commands[4].contains(command)) {
isValid = false;
quit();
// HELP
} else if (commands[3].startsWith(command)
&& commands[3].contains(command)) {
help();
}
}
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "\nGCD, and check to see if a list of numbers are in order"
+ "\n-----------------------------------"
+ "\nMade by Amr Ghoneim (A00425709)"
+ "\n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "\n - factorial #"
+ "\n The product of all numbers from 1 to #."
+ "\n (The argument must not be negative.)" + "\n - gcd # #"
+ "\n The greatest common divisor of the two numbers."
+ "\n The biggest number that divides evenly into both of
them."
+ "\n - sorted #..."
+ "\n Whether the numbers are in order from smallest to
largest."
+ "\n If not, then where the first out-of-order number is."
+ "\n - help" + "\n This help message." + "\n - quit"
+ "\n End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after "
+ nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}
What im missing is finding out how many arguments the user is putting, if too much print a message, and for the sorted command, i cant get it to print the letter the user puts. and for some reason when i input "Factorial 5 5" is would print the ">>>" twice instead of once. theres just some bugs here and there, can someone guide me on how i would approach this stuff, or show some examples?
Thanks!
I have modified your code so that it will work as what you have described. Just look at the code comments for details. Feel free to comment for clarifications.
Modified code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static int counter = 0;
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.nextLine().toLowerCase(); // instead of getting the input per space, get all the input per
// line
String[] userCommand = command.split(" "); // split the line by spaces
// check if the command has at least 2 parameters except for "help" and "quit"
if (!commands[3].equals(userCommand[0]) && !commands[4].equals(userCommand[0]) && userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
// since you know that the first word will be the command, you just have to get
// the value of index 0
// FACTORIAL
// use equals do not use startsWith or contains since it will hold true for
// inputs "FACTORIALINVALID 4"
if (commands[1].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 2 parameters
if (userCommand.length != 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the factorial and convert it into an int
int num = Integer.parseInt(userCommand[1]);
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// GCD
// use equals do not use startsWith or contains since it will hold true for
// inputs "GCDINVALID 4 5"
} else if (commands[2].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 3 parameters
if (userCommand.length != 3) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the GCD and convert it into an int
int numA, numB;
numA = Integer.parseInt(userCommand[1]);
numB = Integer.parseInt(userCommand[2]);
System.out.println("gcd(" + numA + ", " + numB + ") == " + GCD(numA, numB));
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// SORTED
// use equals do not use startsWith or contains since it will hold true for
// inputs "SORTEDINVALID 4 5 6"
} else if (commands[0].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must at least 2 parameters
if (userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
List<Integer> nums = new ArrayList<Integer>();
// get the list
for (int i = 1; i < userCommand.length; i++) {
nums.add(Integer.parseInt(userCommand[i]));
}
sorted(nums);
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// QUIT
// use equals do not use startsWith or contains since it will hold true for
// inputs "QUITINVALID"
} else if (commands[4].equals(userCommand[0])) {
isValid = false;
quit();
// HELP
// use equals do not use startsWith or contains since it will hold true for
// inputs "HELPINVALID"
} else if (commands[3].equals(userCommand[0])) {
help();
}
}
scnr.close();
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "\nGCD, and check to see if a list of numbers are in order" + "\n-----------------------------------"
+ "\nMade by Amr Ghoneim (A00425709)" + "\n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "\n - factorial #" + "\n The product of all numbers from 1 to #."
+ "\n (The argument must not be negative.)" + "\n - gcd # #"
+ "\n The greatest common divisor of the two numbers."
+ "\n The biggest number that divides evenly into both of them." + "\n - sorted #..."
+ "\n Whether the numbers are in order from smallest to largest."
+ "\n If not, then where the first out-of-order number is." + "\n - help"
+ "\n This help message." + "\n - quit" + "\n End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after " + nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}
I am in an intro to the java class, and for one of my assignments, I have to use a loop (for or while) to keep track of scores between myself and the computer.
Here is the exact word for word instructions from my professor:
Write a program that does this: You (as a programmer) are the dealer.
pick a random number for yourself (between 0 - 100). Ask the user to input a random number (between 0 - 100) Whoever is closer to 21 wins the game.
(part 2) -Loop (keeping a counter) rite the same program and keep it going so that it keeps playing (dealing hands and saying who wins) until the user enters 21 at which point you print out some stats and say goodbye. For example, your goodbye might look like this:
Number of rounds played: 5
Dealer won: 3
Player won:2
you're 2 for 5.
Now I have written the code and played around it for hours and hours, and cannot make it work with a loop. I've tried while, do while, and for. I have looked everywhere on the internet for similar examples but cannot make a loop work in my program whatsoever. If anyone has any suggestions I would sure appreciate the feedback.
my code:
import java.util.*;
class asd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
System.out.println("computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("the winner is the user!" + input);
dealerscore++;
gamesplayed++;
} else {
System.out.println("the winner is the computer!" + r);
userscore++;
gamesplayed++;
}
if (input == c) {
System.out.println("thank you for playing. you won.");
}
if (r == c) {
System.out.println("Thank you for playing:" + userscore);
System.out.println(userscore);
}
if (input == 0) {
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
while (input != c && r != c)
gamesplayed++;
}
// TODO code application logic here
}
Everything works fine, but I can't get the loop to work anywhere here.
You need a while loop that contains your game logic. The condition should just check if the input != c.
Then inside the loop, keep asking the user for input. Also, you mixed up userscore and dealerscore when adding the score.
Then at the end, once you come out of the loop, you can print the scores/stats.
Please read the comments below:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!: ");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
/*
This loop runs the game until the user enters 21
*/
while (input != c) {
System.out.println("Computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("The winner is the user! " + input);
userscore++; //You mixed up userscore and dealerscore
} else {
System.out.println("The winner is the computer! " + r);
dealerscore++; //You mixed up userscore and dealerscore
}
/*
User needs to keep entering guesses
*/
System.out.println();
System.out.println("Enter another guess: ");
r = rand.nextInt(max - min) + min;
input = sc.nextInt();
}
/*
You don't need any conditions since the games have already ended
But it should be outside and after the loop
*/
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
}
Change the loop with
while (input != c && r != c){
gamesplayed++;
System.out.println("Games played: " + gamesplayed );
}
you will see it is working. I would format the code better to debug it easier and always use the brackets.
Try this. Just refer to the code for explanations.
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
System.out.println("");
int min = 0;
int max = 100;
int input;
int c = 21;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 1;
Random rand = new Random();
while (true) { // so that the game will keep playing
System.out.println("----------------- ROUND " + gamesplayed + " -----------------");
int r = rand.nextInt(max - min) + min; // computer's choice
while (true) { // so that it will keep asking the user in case the user enters an invalid input
try {
System.out.print("Enter a random number! :");
input = Integer.parseInt(sc.nextLine());
break;
} catch (Exception e) {
System.out.println("Invalid input!");
}
}
System.out.println("The computer's random number is " + r);
// checking for the rounds winner
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("The winner is the user!");
userscore++;
} else {
System.out.println("The winner is the computer!");
dealerscore++;
}
if (input == c) { // checking for ending the game
System.out.println("================ GAME STATS ================");
System.out.println("Thank you for playing.");
System.out.println("Number of hands played: " + gamesplayed);
System.out.println("Dealer score: " + dealerscore);
System.out.println("User score: " + userscore);
System.out.println("You are " + userscore + " out of " + gamesplayed + "!");
System.out.println("============================================");
sc.close();
break;
}
gamesplayed++; // increment games played
System.out.println("--------------------------------------------");
}
}
}
I'm just trying to build a calculator and I have no idea how to prompt an operator before each number. I'm trying to build a calculator and have as many number inputs as specified but they can cancel out of it by pressing -1 and it will still return the final value.
But i tried using a string statements but I'm new to coding and don't know where to start.
int operator;
int howmany;
int i=0;
int all = 0;
double div;
int scan;
System.out.println("Press 1 for addition, 2 for subtraction, 3 for \n
multiplication 4 for division or 5 for modules");
operator=scanner.nextInt();
if(operator < 1 || operator >5) {System.out.println("Restart
calculator");System.exit(0);}
System.out.println("How many numbers will you be using?");
howmany = scanner.nextInt() -1 ;
if (operator == 1){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all += scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 2){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all -= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 3){
all = 1;
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all *= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 4){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all = scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 5){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all %= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
}
}
When you don't know where to start when coding, it can help to write the algorithm in sentences first, and then convert into code. For a calculator program for example, I would start with this basic structure:
// need a data structure to hold all numbers
// need a data structure to hold all operations
while(the user wishes to continue) {
while(the user has not hit =) {
// use the scanner to get the next number (if it's -1, exit program)
// use the scanner to get the next operator (if it's = then exit inner
// loop to report result)
}
// need variable to hold calculation result, instantiate to first number
for(loop through numbers data structure) {
// apply next operator to the running result and next number
}
// report result to user
}
Something else to consider: a calculator should be able to use -1 in calculations. I'm not sure if this is a requirement of what you're working on, so I left it as you described, but what would be more in line with the spirit of a calculator would be to do something like ask the user after each successful calculation if they'd like to continue (y/n).
I have a problem with my program.
Program is a HILO game which requires the user to guess a number between a range of a generated number.
The problem is that once i press 0 on my keyboard, it reveals the random number, and essentially must end the loop and ask whether the user wants to continue or end the program. Instead, it continues the loop, and whenever I press a letter on the keyboard it shows me an Exception error which describes and input Miss Match. Can some one guide me on how to fix it?, maybe I wrote the program wrong, I tried multiple ways, it still doesn't work as it supposed to work.
Thank you.
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class HILOGAME
{
public static void firstGame()
{
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
for (int exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.nextLine();
if (!choice.equalsIgnoreCase("x"))
{
Loop = true;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
Loop = false;
System.out.print("END OF GAME");
exit = 11;
}
}
if (number > answer)
{
System.out.println("TOO HIGH");
}
if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
}
}
}
}
}
EDIT 1:
This code is working perfectly for me i have tried running it:
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
int exit;
for (exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.next();
// HERE YOU ARE DOING THE WRONG THING
// What is the meaning of "not(!)" here ? !choice.equalsIgnoreCase("x")
// Remove "NOT(!)" from here your program will work as expected
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
else if (number > answer)
{
System.out.println("TOO HIGH");
}
else if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
// MADE CHANGES HERE
choice = input.next();
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
}
}
Please do copy-paste the code. Because it is working perfectly without any Exception..!!
My sample outputs:
SAMPLE 1:
Guess a number between 1 and 50 : 1
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 27
Enter x to continue to play or y to endgame
y
END OF GAME
SAMPLE 2:
Guess a number between 1 and 50 : 20
TOO HIGH
Guess a number between 1 and 50 : 19
TOO HIGH
Guess a number between 1 and 50 : 15
Your guess was correct
The number was: 15
You guess the number with: 3 guesses
Enter x to continue to play or y to endgame
x
A new numberGuess a number between 1 and 50 : 20
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 42
Enter x to continue to play or y to endgame
y
END OF GAME
Do let me know if there is any problem.
Well, if you wish to end a loop, you could use the break; command. It jumps out of a while or for loop. So you could use this if the number is 0:
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter 'x' to continue to play or y to endgame");
choice = input.nextLine();
if(choice == "y")
{
break;
}
and add:
if(choice == "y") {break;} to the very end of the while(!Loop) loop.
And with the time when the answer is correct, you set Loop to false, which means !Loop would evaluate to true. You should change Loop = false to Loop = true when they decide to continue the game.
a small modification
public class HILOGAME {
public static void firstGame() {
final int range = 50;
int answer;
int number;
int guessNum = 0;
String choice = "";
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
if (number == answer) {
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
} else {
System.out.println("you entered a wrong value");
System.out.println("do you really want to try again? press y to continue or other alphabet to exit");
choice = input.next();
playAgain(choice);
}
}
public static void playAgain(String choice) {
if (choice.equalsIgnoreCase("Y")) {
firstGame();
} else {
System.out.println("you chose to quit");
System.exit(0);
}
}