The code that I have runs, but when I do the do-while loop, the for loop does not reset back to 1 when the user chooses Yes to rerun the program. I hope I am making myself clear.
int choice;
int num;
int i;
String input;
int b = 1;
switch (choice) {
case 1:
do {
System.out.println("The starting number is 1.");
//Input
System.out.print("Enter a value: ");
num = sc.nextInt();
for (i = 1; i <= num; i++) {
b = b * i;
//Output
System.out.printf("%d! = %d\n", i, b);
}
System.out.print(
"Run the program again? (Y for Yes, N for No): ");
input = sc.next();
} while (input.equalsIgnoreCase("Y"));
if (input.equalsIgnoreCase("N")) {
System.out.println(
"Have a great day!");
System.exit(0);
}
break;
}
I tried a while loop instead of the for loop and I was not getting the results at all. I am new to Java so I am still learning.
I added a break at the end of the for loop, but that ends the loop only after 1 increment.
You don't need a switch expression. Also, declare the variables in the narrowest scope. In this case, except for sc, they should be declared in the do/while loop, or in the case of b, in the for loop.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("The starting number is 1.\n");
System.out.print("Enter a value: ");
// Input
int num = sc.nextInt();
for (int i = 1, b = 1; i <= num; i++) {
b = b * i;
// Output
System.out.printf("%d! = %d\n", i, b);
}
System.out.print(
"Run the program again? (Y for Yes, N for No): ");
String input = sc.next();
if (input.equalsIgnoreCase("N")) {
System.out.println(
"Have a great day!");
sc.close();
System.exit(0);
}
} while (true);
}
Related
i'm trying to create a program where the number that the user has input would decrease by a certain amount. something that would like this:
Update by (Increment/Decrement):decrement
Enter starting number:15
Enter update number:3
Enter end number:3
loop#1 value=15
loop#2 value=12
the end number is where the loop would stop and the update number is how much the starting number should decrement by. so far this is the code I have and I'm stuck on how to keep the loop going until the end number.
package jaba;
import java.util.Scanner;
public class loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String Decrement = scan.nextLine();
System.out.print("Enter starting number:");
String number = scan.nextLine();
System.out.print("Enter update number:");
String upnumber = scan.nextLine();
System.out.print("Enter end number:");
String endnumber = scan.nextLine();
int i,j;
i = 15;
j = 1;
do {
System.out.println("loop#" +j+ "\tvalue="+i);
j++;
}while(i<15);
i = i-3;
System.out.println("loop#" +j+ "\tvalue="+i);
};
}
how about something like this:
public class loop {
public enum Operation {INCREMENT, DECREMENT, INVALID}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String operationString = scan.nextLine();
System.out.print("Enter starting number:");
String numberString = scan.nextLine();
System.out.print("Enter update number:");
String upnumberString = scan.nextLine();
System.out.print("Enter end number:");
String endnumberString = scan.nextLine();
// Determine and parse stuff
int startNumber = Integer.parseInt(numberString);
int updateNumber = Integer.parseInt(upnumberString);
int endNumber = Integer.parseInt(endnumberString);
// Parse operation, but assume invalid operation
Operation operation = Operation.INVALID;
if (operationString.equalsIgnoreCase("increment")) {
operation = Operation.INCREMENT;
} else if (operationString.equalsIgnoreCase("decrement")) {
operation = Operation.DECREMENT;
}
// now do the "meat" of the assignment
int loopNumber = 0; // we'll keep the loop number as a separate counter
switch (operation) {
case INCREMENT:
for (int i = startNumber; i < endNumber; i = i + updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i);
}
break;
case DECREMENT:
for (int i = startNumber; i > endNumber; i = i - updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i)
}
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
}
private static void performAssignmentPrinting(int loopNumber, int value) {
System.out.println("loop#" + loopNumber + "\tvalue=" + value);
}
}
or the do/while version:
// now do the "meat" of the assignment
int currentNumber = startNumber;
int loopNumber = 0; // we'll keep the loop number as a separate counter
do {
loopNumber++;
switch (operation) {
case INCREMENT:
currentNumber += updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case DECREMENT:
currentNumber -= updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
} while (currentNumber != endNumber);
you have i = i-3; out of loop.
Move decrementation of i into loop:
do {
System.out.println("loop#" + j + "\tvalue=" + i);
j++;
i = i - 3;
} while (i > endnumber);
For loop is the solution for your program. for(a ; b ; c) {...}
Google how a for loop works. And try to understand how the 3 parts a,b,c works.
Pseudo:
// if decrease mode
// for (i = upperbound ; i >= lowerbound ; i-= decrement)
// print i
// if increase mode
// for (i = lowerbound ; i <= upperbound ; i+= increment)
// print i
Update: This is sufficient to get you started and add more validation on your journey.
I want to apply this function in java. Inside while loop, you need to input number of repetition you want to input a number. if you input a number that equals to the number that you enter previously, it will repeat a loop and enter a number again. This code is not finish yet. I hope u understand what i want to achive. thank you
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == input){
System.out.println("It is already taken");
}
}
}
}
Let's use a temp variable to store the value of previous input. If new input is same as previous input, the iterator i should not increase, so we use i--
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
int temp=0;
int inputArray[] = new int[times];
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == temp){
System.out.println("It is already taken");
i--;
}else {
inputArray[i-2]=input;
}
temp=input;
}
}
The thing with that solution is that is only checks for the number just entered before the current one. I understood that you want to check that the number the user entered is unique and it has to be checked against every number that he/she has entered before.
See the code for that:
import java.util.Scanner;
import java.util.ArrayList;
public class testMe{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of times: ");
int times = scanner.nextInt();
int i = 0;
ArrayList<Integer> listWithEntries = new ArrayList<Integer>();
while (i < times){
System.out.print("Enter a number : ");
int input = scanner.nextInt();
if(listWithEntries.size() == 0){
listWithEntries.add(input);
i++;
} else {
for(int j = 0; j < listWithEntries.size(); j++){
if(input == listWithEntries.get(j)){
System.out.println("It is already taken!");
break;
}
if(j == listWithEntries.size()-1 && input !=
listWithEntries.get(j)){
listWithEntries.add(input);
i++;
break;
}
}
}
}
}
}
I put the code in a do-while loop. It asks the user which menu option they want and it computes the equation for them. The code is supposed to keep on going until the user hits 4 which is the quit option, but it stops after one sequence. I dont know what I need to change or add so it keeps on going.
import java.util.Scanner;
import java.text.DecimalFormat;
class Lab5
{
public static void main(String[] args) //header of the main method
{
Scanner in = new Scanner(System.in);
int choice;
int rem = 0;
int num;
do
{
//user prompt
System.out.print("Choose from the following menu\n1) Calculate the sum of integers 1 to m\n2) Factorial of a number\n3) Repeat the first number\n4) Quit\n:");
choice = in.nextInt();
switch(choice)
{
case 1:
int m, sum =0;
int i = 1;
System.out.print("Enter the number:");
m = in.nextInt();
while (i <= m)
{
sum=sum+i;
i++;
}
System.out.print("The sum of:" + m + ' ' + "is" + ' ' + sum);
break;
case 2:
int number, fact =1;
System.out.print("Enter the number:");
number = in.nextInt();
i=1;
for (int factor = 2; factor <= number; factor++)
{
fact = fact*factor;
}
System.out.print("The Factorial of +:" + number + ' ' + "is" + ' ' + fact);
break;
case 3:
System.out.print("Enter the number:");
num = in.nextInt();
while(num!=0)
{
rem = num%10;
num = num/10;
}
System.out.print("The leftmost digit is:" + rem);
break;
default:
break;
}
} while (choice == '4');
System.out.print(" ");
}
}
You wrote this as do ... while ( choice == '4' ), which means it will only continue if the user enters a 4.
Sounds like you want choice != '4'.
Hello my purpose is this:
Write a method that can accept values only between 10 and 50.Sample execution:Enter a number between 10 and 50Enter a number: 5Enter a number between 10 and 50Enter a number: 12Number Entered: 12.Enter a number: 0Good ByeSo as you can see it only finishes when user enters 0.And it says different things when number is between 10 and 50 or not.I deleted again my code and started but i got stuck on some points and i gave up.My final code was:
import java.util.Scanner;
public class A{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter case number: ");
int caseVal = scan.nextInt();
switch(caseVal){
case 1:
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number: ");
int num = scan.nextInt();
betweenMethod(num);
if(num == 0){
System.out.println("Good Bye");
break;
}
while(num != 0){
betweenMethod(num);
}
break;
case 2:
System.out.println("Enter a number to display its divisors: ");
int x = scan.nextInt();
System.out.println("The divisors of " + x + " are:");
divisorsMethod(x);
break;
}
scan.close();
}
public static void divisorsMethod(int a){
if(a <= 0)
System.out.println("The number should be greater than 0");
else{
for(int b = 1; b <= a; b++){
if(a % b == 0 && b != a)
System.out.print(b + ", ");
else if(b == a)
System.out.println(b);
}
}
}
public static void betweenMethod(int a){
Scanner inputscan = new Scanner(System.in);
if(a >= 10 && a <= 50){
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else if((a < 10 || a > 50) && a != 0){
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else{
System.out.println("Good Bye");
}
inputscan.close();
}
}
Sorry for uncut version.It is case 1.Every time i tried it didnt work fully.If anyone can help i would appreciate it.I'm sorry if i didnt write this question in rules.(Sorry for the grammar as well)THIS IS WHERE I AM STUCK= When i type 0 it doesnt say GoodBye and end the loop.Thats where i need help.TO EVERYONE THAT NEEDS ANSWER TOO:I figured out what to do.Basically we say while its not equal to zero right?I wrote a new method that (after last inputscan for variable)checks if the number is zero and prints good bye.So with this way it prints good bye and it goes to starting.But it cannot do anythink else because we said while not equal to 0.Anyway thats one solution.
Don't close() System.in
When you call inputscan.close() that closes the underlying InputStream, which is System.in.
Return the Value
Your method should be prompting for input between two values and returning a single value. Also, you could move your Scanner to a static (or class) field. Something like
private static Scanner inputscan = new Scanner(System.in);
public static int betweenMethod(final int a, final int b) {
int min = Math.min(a, b);
int max = Math.max(a, b);
while (true) {
System.out.printf("Please enter a number between %d and %d%n", min, max);
int in = inputscan.nextInt();
if ((in == 0) || (in >= min && in <= max)) {
return in;
}
}
}
Primitives1 are Passed-By Value
You need to assign the result of the call back to your value when you loop. Something like,
int num = betweenMethod(10, 50);
while (num != 0) {
System.out.printf("Number Entered: %d.%n", num);
num = betweenMethod(num);
}
System.out.println("Good Bye");
break;
1and Everything Else in Java.
In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.