How should I loop this program? - java

Basically I need to loop this. I created a game where you answer questions about fish in runescape and I would like it to loop like say would ‘you go again’ or something. How would I go about this?
import java.util.Scanner;
public class GameDriver
{
public static void main(String a[])
{
Game g = new Game();
Scanner s = new Scanner(System.in);
String buf = null;
for(int i = 0; i < 4; i++)
{
System.out.print(g.askQuestion());
buf = s.nextLine();
if(g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
}
}

You could do while (true) loop and then if the user enters quit just break the loop like so:
if (buf.equals("quit"))
break;

PFB complete code for ‘you go again’ program:
import java.util.Scanner;
public class GameDriver {
public static void Gamer(Scanner s) {
Game g = new Game();
String buf = null;
for (int i = 0; i < 4; i++) {
System.out.print(g.askQuestion());
buf = s.nextLine();
if (g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
}
public static void main(String a[]) {
Scanner s = new Scanner(System.in);
try {
while (true) {
System.out.print("Press Enter to continue; Type Exit to quit");
if (s.nextLine().equalsIgnoreCase("exit")) {
s.close();
break;
}
Gamer(s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

As per i understand your question,you want to loop over the for loop.Kindly correct me if i m wrong.
char c='y';//'y' means user wants to go again
while(c=='y')// to check the user reply.
{
for(int i = 0; i < 4; i++)
{
System.out.print(g.askQuestion());
buf = s.nextLine();
if(g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
System.out.println("Do you wanna go again?");
c=s.next.charAt(0);
}

This is shortest solution keeping all your code logic as is :
import java.util.Scanner;
public class GameDriver {
public static void Gamer(Scanner s) {
Game g = new Game();
String buf = null;
for (int i = 0; i < 4; i++) {
System.out.print(g.askQuestion());
buf = s.nextLine();
if (g.confirm(buf))
System.out.println("You're Right!");
else
System.out.println("You're Wrong...");
}
System.out.println("You got a " + g.getScore());
System.out.print("Press Enter to continue; Type Exit to quit");
if (s.nextLine().equalsIgnoreCase("exit")) {
s.close();
System.exit(0);
}
Gamer(s);
}
public static void main(String a[]) {
Gamer(new Scanner(System.in));
}
}

Related

How to end this program when user inputs "end"?

So basically I am trying to figure out how to stop this program using Integer.valueOf(String s) or Integer.parseInt(String s) by typing "end" for the user input
import java.util.Scanner;
public class monkey1{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int sum = 0;
int lol = 1;
do {
System.out.print("Enter a number: ");
lol = s.nextInt();
sum += lol;
if (lol > 0) {
System.out.println("Sum is now: " + sum);
}
} while (lol>0);
}
}
First - you need to change lol=sc.nextInt() to String tmp = s.nextLine()
Second - do
try {
if (tmp.equals("END")) {
break; // This will exit do-while loop
}
lol = Integer.parseInt(tmp);
} catch (NumberFormatException e) {
e.printStackTrace();
// Here you can also exit loop by adding break. Or just ask user to enter new text.
}
you should learn how to use try/catch.
Here we go:
String text = "";
int lol = 1;
do {
System.out.print("Enter a number: ");
text = s.nextLine();
try {
lol = Integer.valueOf(text);
}catch (Exception e){
System.out.println("Exit");
System.exit(0);
}
Here is your code
package Phone;
import java.util.Scanner;
public class monkey1{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int sum = 0;
int hi = 1;
do {
System.out.print("Enter a number: ");
String lol = s.nextLine();
if(lol.equals("end")) {
break;
}
hi = Integer.parseInt(lol);
sum += hi;
if (hi > 0) {
System.out.println("Sum is now: " + sum);
}
} while (hi > 0);
}
What I did here is I changed lol to hi for adding and took String input so that you can input end...
I would suggest checking if s.equals("end") before converting to int so something like this:
do {
System.out.print("Enter a number: ");
String userValue = s.nextLine();
if(userValue.equals("end")
break;
lol = Integer.parseInt(userValue);
sum += lol;
if (lol > 0){
System.out.println("Sum is now: " + sum);
}
}while (lol>0);

For two integer user inputs, how to detect that a string has been passed on the very first input?

This is my code. A program to check for prime numbers between user inputs, 'start' and 'stop'.
import java.util.*;
public class test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("Enter start: ");
String start = sc.nextLine();
if(start.equalsIgnoreCase("stop"))
{
break;
}
System.out.println("Enter stop: ");
String stop = sc.nextLine();
if(stop.equalsIgnoreCase("stop"))
{
break;
}
try
{
int s1 = Integer.parseInt(start);
try
{
int s2 = Integer.parseInt(stop);
for(int i = s1; i<=s2;i++)
{
if(p1.isPrime(i))
{
System.out.print(i+" ");
}
}
System.out.println("");
}
catch(java.lang.NumberFormatException er)
{
System.out.println("Invalid Input");
}
}
catch(java.lang.NumberFormatException er1)
{
System.out.println("Invalid Input");
}
}
}
}
When taking start input, if I enter any string, I want the code to instantly detect NumberFormatException and ask for the same input again.
What happens instead, is that, it takes both inputs, whether string and integer, and only then evaluates whether it's a string.
I don't use sc.nextLine() because I want the stop functionality. I want the program to stop execution if I input "stop" anywhere.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int start = -1;
int stop = -1;
while (true)
{
if (start == -1)
{
System.out.println("Enter start: ");
if (sc.hasNextInt())
{
start = sc.nextInt();
} else if (sc.nextLine().equalsIgnoreCase("stop")) break;
else
{
System.out.println("Invalid Input");
continue;
}
}
if (stop == -1)
{
System.out.println("Enter stop: ");
if (sc.hasNextInt())
{
stop = sc.nextInt();
} else if (sc.nextLine().equalsIgnoreCase("stop")) break;
else
{
System.out.println("Invalid Input");
continue;
}
}
for (int i = start; i <= stop; i++)
{
// Prime number method call here
System.out.print(i + " ");
}
System.out.println();
start = stop = -1;
}
}

How do I get my program (Lottery game) to check the tips again?

I am trying to write a lottery program (based on a hungarian game, 5 numbers from 1 to 90), it works almost fine, the first time i give it faulty numbers (more than 90 or 0) it tells me that I did wrong. But the second time it doesn't. It keeps on executing the game with the invalid numbers. What were your tips, and what would you Guys do differently?
Thank you for your time.
The code:
import java.util.*;
class Lottery {
static int hits = 0;
Integer[] tippek = new Integer[5];
Random rand = new Random();
ArrayList<Integer> nums = new ArrayList<Integer>();
static Lottery lot = new Lottery();
public static void main (String[] args){
lot.wnums();
lot.tipread();
lot.tipcheck();
lot.wincheck();
lot.result();
}
public void wnums () {
// GENERATING THE WINNER NUMBERS
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; set.size() < 5; i++){
int x = rand.nextInt(90) + 1;
set.add(x);
}
nums.addAll(set);
}
public void tipread (){
// READING THE TIPS
System.out.println("Please write 5 different number from 1 to 90.");
try{
Scanner scan = new Scanner(System.in);
tippek[0] = scan.nextInt();
tippek[1] = scan.nextInt();
tippek[2] = scan.nextInt();
tippek[3] = scan.nextInt();
tippek[4] = scan.nextInt();
}catch (InputMismatchException ex){
System.out.println("Error.");
}
}
public void tipcheck() {
int fault = 0;
List<Integer> tips = Arrays.asList(tippek);
try{
for(int tipp : tippek){
System.out.println(tipp);
if(tipp == 0 || tipp > 90){
fault++;
}
}
if(fault == 1){
System.out.println("One of your tips is invalid ");
System.out.println("Write other numbers");
lot.tipread();
}
if(fault > 1){
System.out.println(fault + " of your tips are invalid ");
System.out.println("Write other numbers");
lot.tipread();
}
for(int tipp : tips){
for(int i = 0; i < tips.size(); i++){
if(tips.indexOf(tips.get(i)) != tips.lastIndexOf(tips.get(i))){
System.out.println("You can write a number only once");
lot.tipread();
}
}
}
}catch (NullPointerException ex){
System.out.println("Error.");
}
}
public void wincheck () {
// CHECKING THE TIPS
try{
for(int tipp : tippek){
for(int i = 0; i < 5; i++){
if(nums.get(i) == tipp){
hits++;
}
}
}
}catch(Exception ex){
System.out.println(" ");
}
}
public void result() {
try{
Arrays.sort(tippek);
Collections.sort(nums);
String tippeksor = Arrays.toString(tippek);
System.out.println("Your tips in ascending order: " + tippeksor);
System.out.println("You have " + hits + " hits.");
System.out.println("The winning numbers are: " + nums);
}catch(Exception ex){
lot.tipread();
}
}
}
Include lot.tipcheck() as the last statement inside tipread():
public void tipread (){
// READING THE TIPS
System.out.println("Please write 5 different number from 1 to 90.");
try{
Scanner scan = new Scanner(System.in);
tippek[0] = scan.nextInt();
tippek[1] = scan.nextInt();
tippek[2] = scan.nextInt();
tippek[3] = scan.nextInt();
tippek[4] = scan.nextInt();
lot.tipcheck();
}catch (InputMismatchException ex){
System.out.println("Error.");
}
}
so to ensure that every time the user inputs valid numbers they will be checked.
Other modifications:
remove lot.tipcheck(); from main()
After every lot.tipread(); in tipcheck() add a return;
instead of calling tipread directly from tipcheck
tipcheck returns true if everything is ok, false otherwise
and use do-while in main.
public static void main (String[] args){
lot.wnums();
do {
lot.tipread();
} while(!lot.tipcheck());
lot.wincheck();
lot.result();
}
and
public boolean tipcheck() {
int fault = 0;
List<Integer> tips = Arrays.asList(tippek);
try{
for(int tipp : tippek){
System.out.println(tipp);
if(tipp < 1 || tipp > 90){
fault++;
}
}
if(fault == 1){
System.out.println("One of your tips is invalid ");
System.out.println("Write other numbers");
// lot.tipread();
return false;
}
if(fault > 1){
System.out.println(fault + " of your tips are invalid ");
System.out.println("Write other numbers");
// lot.tipread();
return false;
}
for(int tipp : tips){
for(int i = 0; i < tips.size(); i++){
if(tips.indexOf(tips.get(i)) != tips.lastIndexOf(tips.get(i))){
System.out.println("You can write a number only once");
// lot.tipread();
return false;
}
}
}
}catch (NullPointerException ex){
System.out.println("Error.");
return false;
}
return true;
}
like this.

newbie to nested if statements

I am learning to use Java and code on my own, I am network Tech and wanted to learn how to Code. I am learning from a site called programming by doing and I am stuck on one assignment:
https://programmingbydoing.com/a/twenty-questions.html
below is my code, it will compile but the issue is with the nested if statement not working properly please help!!!
import java.util.Scanner;
public class twentyQuestions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String question1, question2, guess;
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I will try to guess it.");
System.out.println();
System.out.println("Question 1: Is it an animal, vegetable, or mineral?");
question1 = keyboard.next();
System.out.println();
System.out.println("Question 2: Is it bigger than a bread box?");
question2 = keyboard.next();
if (question1.equals("animal"))
{
if (question2.equals("no"))
{
guess = "squirrel";
}
else {
guess = "moose";
}
}
else if (question1.equals("vegetable"))
{
if (question2.equals("no"))
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (question1.equals("mineral"));
{
if (question2.equals("no"))
{
guess = "paper clip";
}
else
{
guess = "Camaro";
}
}
System.out.println("You're thinking of a " + guess);
}
}
}
First off all, you need to remove the semicolon after
else if (question1.equals("mineral"))
Then, you need to add a final else block at the end of the if statement to catch input that does not match any of the three inputs. Then it will be able to compile:
...
else if (question1.equals("mineral"))
{
if (question2.equals("no")) {
guess = "paper clip";
} else {
guess = "Camaro";
}
}else{
System.out.println("Invalid input");
return;
}
...
THANK YOU ALL here is my final code that works thanks to everyone...:
import java.util.Scanner;
public class twentyQuestions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String question1, question2, guess = "";
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I will try to guess it.");
System.out.println();
System.out.println("Question 1: Is it an animal, vegetable, or mineral?");
question1 = keyboard.next();
System.out.println();
System.out.println("Question 2: Is it bigger than a bread box?");
question2 = keyboard.next();
if (question1.equals("animal"))
{
if (question2.equals("no"))
{
guess = "squirrel";
}
else {
guess = "moose";
}
}
else if (question1.equals("vegetable"))
{
if (question2.equals("no"))
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (question1.equals("mineral"))
{
if (question2.equals("no"))
{
guess = "paper clip";
}
else
{
guess = "Camaro";
}
}
else{
System.out.println("Invalid input");
return;
}
System.out.println("You're thinking of a " + guess);
}
}

Hangman, exits the game without getting the user response (loop)

I got a couple issues with my code. I know it is not the best looking design/coding but I don't claim to be a good programmer yet. I have to other classes does their work correctly. Dictionary class which contains a word list and HangmanAnimation class which draws the hangman onto console.
Now, I want my game to ask to player if he/she wants to play again after the game finished. Actually, it does asking if player wants to play again but exits the game before the player can type anything.
I would appreciate any other suggestions aswell. Thanks in advance! You guys really rock! :)
public class HangmanGame {
public static void main(String[] args) {
HangmanUI ui = new HangmanUI();
ui.initialize();
String input = "";
if(ui.newGame(input).equalsIgnoreCase("yes"))
main(null);
}
}
public class HangmanUI {
private final Dictionary d = new Dictionary();
private final HangmanAnimation ha = new HangmanAnimation();
private String wordInProgress = d.getWordInProgress();
Scanner sc = new Scanner(System.in);
private int maxTries = 5;
String word;
public void initialize() {
int easyWords = 1;
int hardWords = 2;
System.out.println("Welcome to Hangman game.");
System.out.println("=========================");
System.out.println("Rules: You need to find the given word in 5 tries.");
System.out.println("You will continue guessing letters until you can either");
System.out.println("solve the word or all five body parts are on the gallows.");
System.out.println("In that case you will lose the game. Try not to enter");
System.out.println("same letter more than once. Those are counts too.");
System.out.println();
System.out.println("Choose your game level or Quit:");
System.out.println("1) Easy");
System.out.println("2) Hard");
System.out.println("3) Quit");
try {
int playersChoice = sc.nextInt();
switch (playersChoice) {
case 1:
d.wordList(easyWords);
break;
case 2:
d.wordList(hardWords);
break;
case 3:
System.out.println("Thank you for your time!");
System.exit(0);
default:
System.out.println("Invalid input. Try again!");
initialize();
}
word = d.pickRandomWord(d.getWordList());
hideWord(word);
while(maxTries > 0) {
if(wordInProgress.contains("-")) {
System.out.println(wordInProgress);
revealLetter(notifyGuess());
} else {
System.out.println("Good work! You found the word.");
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Use only digits!");
}
}
//TODO: Do not count same letter more than once & let player to know.
public char notifyGuess() {
ArrayList<Character> charSet = new ArrayList<>();
System.out.print("Please enter a letter: ");
char c = sc.next().charAt(0);
if(Character.isDigit(c)){
System.out.println("You can't use numbers. Please enter a letter.");
notifyGuess();
} else if(charSet.contains(c)) {
System.out.println("You already used '" + c + "' before.");
notifyGuess();
} else
charSet.add(c);
return c;
}
public void hideWord(String word) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < word.length(); i++) {
sb.append("-");
}
wordInProgress = sb.toString();
}
public void revealLetter(char c) {
try {
String temp = wordInProgress;
char[] charArray = wordInProgress.toCharArray();
for (int i = 0; i < word.length(); i++) {
if(c == word.charAt(i))
charArray[i] = word.charAt(i);
}
wordInProgress = new String(charArray);
if(temp.equals(wordInProgress)){
maxTries--;
ha.drawHanging(maxTries);
} else {
System.out.println("Good! There is '" + c + "' in the word.");
}
} catch (StringIndexOutOfBoundsException e) {
System.err.println("You have to enter a character!");
}
}
public String newGame(String input) {
System.out.println("Do you want to play again? (yes/no)");
input = sc.nextLine();
return input;
}
}
Try using this:
System.out.println("Do you want to play again? (yes/no)");
input = sc.next(); //<== here is the change
return input;

Categories

Resources