Decrement by a certain amount on java - java

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.

Related

Reset a for loop inside a switch statement

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);
}

After re-run program with while loop , exception method doesn't work

I'm handling exceptions for an exercise and runs fine until I enter an invalid number (to try) after running the program for the first time, this is after the first run when asking to re-run with different values if I happen to enter invalid values it won't throw the exception and I don't know why? It's something I don't know or is it my code? Thanks
//program ReverseNumbers.java
//This program reverses the digits of each number in an array.
import java.util.Scanner;
public class ReverseNumbers{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
boolean continueInput = true; //controls loop for input
String another = "y";
while(another.equalsIgnoreCase("Y")){ //loop to re-run program
do{
System.out.print("\nEnter 5 positive integers: "); //prompt the user to enter 5 integers
//try block
try{
for(int i = 0; i < numbers.length ; i++) //initialize the array
numbers[i] = input.nextInt();
checkInput(numbers); //handler method
continueInput = false;
}
//catch block
catch(IllegalArgumentException ex){
System.out.print("\nInvalid input: ");
//input.nextLine();
}
}while(continueInput);
//outputs
System.out.print("\nEntered numbers:\t\t");
for(int e: numbers)
System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
reverse(numbers);
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
//Exception method
public static void checkInput(int[] array) throws IllegalArgumentException {
for(int i = 0; i < array.length; i++){
if(array[i]<0)
throw new IllegalArgumentException();
}
}
//method reverse.
public static void reverse(int[] array) {
//reverse order of element within the array
int i, k, t;
int n = array.length;
for (i = 0; i < n / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
reverse(array, array.length-1);
}
//helper method
public static void reverse(int[] array, int n){ //reverse the order of the number for each element in the array
// n, number of elements in the array
if(n>=0){
int Element = array[n]; //element n in array
int NewElement = -1;
int Digit = -1;
String s = "";
if(Element<10)
s = Element + "";
while(Element >= 10){ //loop up to element is reduced to one digit number
Digit = Element%10;
s = s + "" + Digit; //save the digits
NewElement = Element/10;
if(NewElement < 10) //when NewElement has 1 digit left
s = s + "" + NewElement;
Element = NewElement;
}
System.out.print(s + " "); //print digit
reverse(array, n-1); //recursive call
}
}
}
This can be fixed simply by inserting continueInput = true in your outer while loop. Without that, continueInput will always be false after the first time you enter a valid input, and your do-while loop will always exit after one iteration.
However, I wouldn't suggest throwing exceptions yourself, and you should probably handle Scanner's InputMismatchException. Also, your reverse method is unnecessarily complicated. Here's the code I got:
import java.util.Scanner;
public class ReverseNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
String another = "y";
while (another.equalsIgnoreCase("Y")) { //loop to re-run program
boolean continueInput = true; //controls loop for input
outer: do {
System.out.print("\nEnter " + numbers.length + " positive integers: ");
try {
for (int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
if (num < 0) {
System.out.print("Invalid input, found a negative integer " + num)
continue outer;
} else {
numbers[i] = num;
}
}
continueInput = false;
}
//handle bad inputs that aren't digits
catch (InputMismatchException ex) {
System.out.print("\nInvalid input, please enter integers");
}
} while (continueInput); //outputs
System.out.print("\nEntered numbers:\t\t");
for (int e: numbers) System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + (i == 0 ? "\n" : " "));
}
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
}

Validate input to ensure negative number

I'm trying to make code that asks the user to enter 10 numbers and subtracts them all. This is what i have so far. I think i have the general layout all set but i dont know what to do with the rest
import java.util.Scanner;
public class subnumbs
{
int dial;
int[] num = new int [10];
Scanner scan = new Scanner(System.in);
public void go()
{
int q=0;
dial = 10;
while (q != 0)
{
System.out.println("type numb: ");
int newinput = scan.nextInt();
q+=newInteger;
dial = cdial + 1;
}
return q;
}
}
System.out.printIn("Enter Integer: ");
int newInteger = scan.nextLine();
While (newInteger >= 0){
System.out.println("Re-enter Integer (must be negative): ");
newInteger = scan.nextLine();
}
n+=newInteger;
Counter = counter - 1;
return n;
this is one way to ensure inly negative numbers, only count down and add it if it was negative ...
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0) {
n+=newInteger;
counter -= 1;
}
else {
System.out.println("must be negative integer, please try again: ")
{
}
In general, to ensure an input you have to evaluate it at the point where you are getting the input

ending loop without use of break and convert for loop to while

this is my code
import java.util.*;
public class test3
{
public static void main (String [] args)
{
int sum = 0;
int mark;
Scanner sc = new Scanner(System.in);
for (int student = 1; student <=10; student++)
{
System.out.println("enter mark");
mark = sc.nextInt();
if (mark > 0)
{
sum = sum + mark;
}
else
{
student = 10;
}
}
System.out.println("sum is" + sum);
}
}
i want to change this code so that the loop ends without having to use student = 10 to end loop. i cant think of anything that would end the loop. and also convert it to a while loop so far i have
int student = 1 ;
int sum = 0;
int mark
Scanner sc = new Scanner(System.in);
while (student <= 10)
{
System.out.println("enter mark");
mark = sc.nextInt();
sum = sum + mark;
student++;
}
but i dont know how to end loop if 0 is input we're not allowed to use break; to exit loop could i get some help please?
The ways for ending loops are:
using break
if the condition is not satisfied in the next interation
Including the loop in a method and using return
What about this:
int student = 1 ;
int sum = 0;
int mark
Scanner sc = new Scanner(System.in);
while (student <= 10) {
System.out.println("enter mark: ");
mark = sc.nextInt();
if (mark > 0) {
sum += mark;
} else {
student = 10;
}
student++;
}
System.out.println("sum is = " + sum);
Use while (student <= 10) condition and student = 10 statement to exit the loop:
public static void main(String[] args) {
int sum = 0;
int mark;
Scanner sc = new Scanner(System.in);
int student = 1;
while (student <= 10) {
System.out.println("enter mark");
mark = sc.nextInt();
if (mark > 0) {
sum = sum + mark;
} else {
student = 10;
}
student++;
}
System.out.println("sum is" + sum);
}

How to add for loops to if statements?

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.

Categories