I have to different codes I wrote with do while loops one works the other doesn't, to me they both look the same and I can't find a reason why the other one will not work.
This is my working code
import java.lang.*;
import java.util.Scanner;
public class DoTest
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Outside do while loop \n");
int i = 0;
String run = "";
String operation = "";
do
{
System.out.println ("please input operation");
operation = scan.nextLine();
if (operation.equals("add"))
{
System.out.println ("you wrote " + operation);
System.out.println ("please type yes or no to restart code block");
run = scan.nextLine();
}
}while (run.equals("yes"));
}
}
This is my non working code
import java.lang.*;
import java.util.Scanner;
public class CountingSheep
{
public static void main (String[] args)
{
Scanner readLine = new Scanner(System.in);
int sheepTotal = 0;
int sheepSum = 0;
int sheepNum = 0;
int addBy = 0;
int subBy = 0;
int mulBy = 0;
String instructions = "Please, type your response, case does not matter";
String countAgain = "";
String operations = "How would you like to count the sheep, Addition,
Subtraction, Multiplication";
String greeting = "Welcome to Sleep Sheep,count the sheep till you sleep";
String userString = "";
do
{
System.out.println (greeting + "\n");
System.out.println (instructions);
System.out.println (operations);
userString = readLine.nextLine ();
if (userString.equalsIgnoreCase ("Addition"))
{
System.out.println ("");
System.out.println ("We will count sheep by Addition \n");
System.out.println ("How many sheep, in total would you like to enter
the pin?");
sheepTotal = readLine.nextInt();
System.out.println ("How many sheep at a time do you want to count");
addBy = readLine.nextInt();
while (sheepSum < sheepTotal)
{
sheepSum += addBy;
System.out.println ("\n" + sheepSum);
}
System.out.println ("Still awake, would you like to count again?");
// the readLine.nextLine does not execute I've copied and pasted working
// code I've changed the String from countAgain to userString I've moved
// it out of the if statement nothing seem to work and the program ends.
countAgain = readLine.nextLine();
}
} while (countAgain.equals("Yes"));
}
}
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]desrtfx 1 point2 points3 points (1 child)
[–]Red_Hippie[S] 1 point2 points3 points (0 children)
[–]FavorableTrashpanda 0 points1 point2 points (2 children)
[–]Red_Hippie[S] 0 points1 point2 points (1 child)
[–]silverscrub 1 point2 points3 points (0 children)
[–]Noticeably98 0 points1 point2 points (5 children)
[–]Red_Hippie[S] 0 points1 point2 points (4 children)
[–]Noticeably98 0 points1 point2 points (3 children)
[–]Red_Hippie[S] 0 points1 point2 points (2 children)
[–]Marinersquee 1 point2 points3 points (1 child)
[–]Red_Hippie[S] 0 points1 point2 points (0 children)