Validate input to ensure negative number - java

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

Related

Decrement by a certain amount on 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.

How am i going to use while loop and if else if user enter the same input twice and it will try again

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

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

Using method to find an integer repeatedly

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.

Java - Using for loops to read user input

In Java, I am having trouble running multiple loops using a single sequence of user-inputted integers. Individually, they run fine individually but together it prints out incorrect numbers.
I'm at a loss as to what is causing this problem.
Here is my code.
import java.util.Scanner;
public class SequenceTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers. " +
"Enter a non-integer to terminate");
int sequence = in.nextInt();
//Print One
int min = sequence;
while(in.hasNextInt())
{
int input = in.nextInt();
if(input < smallest)
{
smallest = input;
}
}
System.out.println(smallest);
//Print Two
int max = sequence;
while(in.hasNextInt())
{
int input = in.nextInt();
if(input > max)
{
max = input;
}
}
System.out.println(max);
//Print Three
int even = 0;
int odd = 0;
while(in.hasNextInt())
{
int input = in.nextInt();
if((input %2) == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println( even);
System.out.println(odd);
//Print Four
double total = 0;
int count = 0;
while (in.hasNextInt())
{
Int input = in.nextInt();
total = total + input;
count++;
}
double average = 0;
if (count > 0)
{
average = total / count;
}
System.out.println(average);
}
}
Your code is very fragmented, but it looks like you can achieve what you want with one loop since the loop condition is the same in all of them. This, of course, is only based on the vague description you gave us.
while(in.hasNextInt()) {
int input = in.nextInt();
if(condition1) {
//do stuff
} else if (condition2) {
//do other stuff
} else if (conditionN) {
//do other other stuff
} else {
//last of the stuff to do
}
}

Categories