Is there a way to make this whole code shorter? - java

I am currently struggling with one thing about this assignment. I would just like a way to make the whole code shorter, even just a little bit (especially the if statement).
package Integers;
import java.util.Scanner;
public class SumOfInt {
public static void main(String[] args) {
int positive = 0;
System.out.println ("-Input ten non-zero integers to calculate their sum. " + "\n" + "-Input the integers at the console and press <Enter>" + "\n");
System.out.println ("Input the 1st integer:");
Scanner input = new Scanner (System.in);
int num1 = input.nextInt ();
System.out.println ("Input the 2nd integer:");
int num2 = input.nextInt ();
System.out.println ("Input the 3rd integer:");
int num3 = input.nextInt ();
System.out.println ("Input the 4th integer:");
int num4 = input.nextInt ();
System.out.println ("Input the 5th integer:");
int num5 = input.nextInt ();
{ if (num1 > 0)
positive++;
}
{ if (num2 > 0)
positive++;
}
{ if (num3 > 0)
positive++;
}
{ if (num4 > 0)
positive++;
}
{ if (num5 > 0)
positive++;
}
System.out.println ("The number of positive integers are: " + positive);
}
}

If you find yourself writing very similar code over and over again (or even copy-pasting stuff), there is always a way to generalise the code and put in into a for loop or an extra method. And that is the way to go.
In your case you could just simply use a for loop.
public static void main(String[] args) {
int positive = 0;
System.out.println("Input the integers at the console and press <Enter>");
Scanner input = new Scanner (System.in);
for (int i = 1; i <= 5; i++) {
System.out.println("Input the " + i + "st integer:");
int x = input.nextInt();
if (x > 0) positive++;
}
input.close();
System.out.println ("The number of positive integers are: " + positive );
}

Try this
Scanner input = new Scanner(System.in);
for (int i = 1; i <= 5; i++) {
String place = i + "th";
if (i == 1)
place = "1st";
if (i == 2)
place = "2nd";
if (i == 3)
place = "3rd";
System.out.println("Input the " + place + " integer:");
if (input.nextInt() > 0)
positive++;
}
input.close();
System.out.println("The number of positive integers are: " + positive);

If you want to store the variable for later use, you can Use array to make it easier.
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int positive = 0;
for (int i = 0; i < 5; i++) {
array[i]=input.nextInt();
if (array[i] > 0)
positive++;
}
System.out.println("Number of positive elements are"+ positive);

Related

How to increment a variable every time the user inputs data?

I have a program that prompts a user for integers until they type a value to continue the program onto the next step. How would I increment a variable called count every time the user inputs an integer? I'm using count++ to increment the count amount by the way, I just don't know how to make it go up when the user puts in data.
Code so far
//variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
//loop
do {
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
high = num;
low = num;
//higher or lower
if(count > 0 && num > high)
{
high = num;
}
else if(count > 0 && num < low)
{
low = num;
}
else
{
System.out.println("You did not enter any numbers.");
}
} while (num != -99);
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
It's simple. Just put count++ inside the while loop as follows,
// variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
// loop
do {
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
count++; // here it goes
high = num;
low = num;
// higher or lower
if(count > 0 && num > high)
{
high = num;
}
else if(count > 0 && num < low)
{
low = num;
}
else
{
System.out.println("You did not enter any numbers.");
}
} while (num != -99);
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
You can put count++; anywhere in your do loop.
I understand why you're using it but why use the counter at all?
The code below uses a different technique to acquire integers from the User. It also ensures that the supplied number is indeed a integer that falls within the Integer.MIN_VALUE and Integer.MAX_VALUE range:
Scanner userInput = new Scanner(System.in);
String ls = System.lineSeparator();
int high = 0;
int low = Integer.MAX_VALUE;
int num;
String input = "";
while(input.equals("")) {
System.out.print("Enter an integer, (q to quit): --> ");
input = userInput.nextLine().toLowerCase();
if (input.equals("q")) {
if (low == Integer.MAX_VALUE) {
low = 0;
}
break;
}
if (!input.matches("^-?\\d+$")) {
System.err.println("Invalid Entry (" + input + ")! "
+ "You must supply an Integer (int) value!" + ls);
input = "";
continue;
}
boolean invalidInteger = false;
long tmpVal=0;
try {
tmpVal = Long.parseLong(input);
} catch(NumberFormatException ex) {
invalidInteger = true;
}
if (invalidInteger || tmpVal < Integer.MIN_VALUE || tmpVal > Integer.MAX_VALUE) {
System.err.println("Invalid Entry (" + input + ")! " + ls
+ "Number too large (Minimum Allowable: " + Integer.MIN_VALUE
+ " Maximum Allowable: " + Integer.MAX_VALUE + ")!" + ls
+ "You must supply an Integer (int) value!" + ls);
input = "";
continue;
}
num = Integer.parseInt(input);
if (num > high) {
high = num;
}
if (num < low) {
low = num;
}
input = "";
}
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
If you want to keep track of how many entries the User made then you can still apply a counter if you like.

Find Two largest numbers in a list without using Array

I'm Stuck with my homework. Basically,we need to Create a program to find the largest and smallest integers in a list entered by the user.And stops when the user enters 0. However we are not allowed to user arrays for this problem.
and one more condition : If the largest value appears more than once, that value should be listed as both the largest and second-largest value, as shown in the following sample run.
I have met the first condition of the program however I cannot meet the 2nd condition.
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
if(num >= max1st && num >= max2nd) {
max1st = num;
}
if(num >= max2nd && num < max1st) {
max2nd = num;
}
count++;
}
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
I have tried to use this code.
if(num >= max2nd && num <= max1st) {
max2nd = num;
}
however when I run the program
https://imgur.com/a/YMxj9qm - this shows.
It should print 75 and 45 . What can I do to meet the first condition and meet the second condition?
If you exceed your maximum number (max1st), your new maximum number will be set to num. But your second largest number will be the current maximum number. So try this condition:
if (num > max1st) {
max2nd = max1st;
max1st = num;
} else if (num > max2nd) {
max2nd = num;
}
Please user If else in those cases. You have used two if statements that is replacing the value of max2nd.
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
if(num >= max1st && num >= max2nd) {
max1st = num;
}
else if(num >= max2nd && num < max1st) {
max2nd = num;
}
count++;
}
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
I changed the conditions, please take a look
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
num = sc.nextInt();
while(num != 0) {
System.out.print("Integer No." + count + " ");
if(num > max1st) {
if(max1st > max2nd) {
max2nd = max1st;
}
max1st = num;
} else {
if(num > max2nd) {
max2nd = num;
}
}
count++;
num = sc.nextInt();
}
System.out.println("");
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
Here is a much simpler method.
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
do
{
num = sc.nextInt();
max2nd = (num >= max1st) ? max1st : (num > max2nd) ? num : max2nd;
max1st = num > max1st ? num : max1st;
}
while(num != 0)
System.out.println("\nThe largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
If you need any more explanation I will be happy to help.
You can try below approach, this should solve your issue =>
import java.util.*;
public class BackedList {
private static Scanner sc;
public static void main(String args[]){
sc = new Scanner(System.in);
int num = 1;
List<Integer> integersList = new ArrayList<Integer>();
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
integersList.add(num);
}
Collections.sort(integersList, Collections.reverseOrder());
if(integersList.get(0) == integersList.get(1)){
System.out.println("The number " + integersList.get(0) + " is first largest and "
+ integersList.get(1) + " is the second largest number");
}
else
{
System.out.println("The largest number is :" + integersList.get(0) + " and the smallest one is :"
+ integersList.get(integersList.size()-1));
}
}
}
You can use the collection to get the largest and second largest like :
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(5);
list.add(2);
Collections.sort(list);
int firstLargest = list.get(list.size()-1);
int secLargest = list.get(list.size()-2);
import java.util.Scanner;
public class FindTwoLargest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = 1, max1st = 0, max2nd = 0;
int count = 1;
System.out.println("This program allows the user to create a list integers until the user enters 0");
System.out.println("The program will print the Largest value and the Second largest value from the list!");
while(num != 0) {
System.out.print("Integer No." + count + " ");
num = sc.nextInt();
if(num > max1st) {
max2nd=max1st;
max1st = num;
}
else if(num == max1st ) {
max2nd = num;
}
count++;
}
System.out.println("The largest value is " + max1st);
System.out.println("The second largest value is " + max2nd);
}
}
you are over complicating things with && in your if. if a number is greater than 1st 1sr gets changed if a number is same as first 2nd gets changed if its not bigger or same nothing happens.

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

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.

if and else statements not working java

Hi I am trying to take in an integer between 1 and 10.
If the user does not do so would like the program to run again.
I believe that I need to use an else if statement that calls on my function but I do not know how to call functions in java.
Here is my code so far:
import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
if (num1 >= 1 && num1 <= 10); {
System.out.println("Input = " + num1);
}
else if {
???
}
}
}
if-else always work.
You made a mistake in the if statement.
there is no ; for an if
if (num1 >= 1 && num1 <= 10) {//no semicolon
System.out.println("Input = " + num1);
}
else if(num < 0) {//should have a condition
...
}
else
{
...
}
What happens if I put a semicolon at the end of an if statement?.
How do I ask the user again if the input is not in between 1 and 10?
Loop until you get what you want :)
Scanner sc = new Scanner(System.in);
int num = 0;
while(true)
{
num = sc.nextInt();
if(num > 0 && num < 11)
break;
System.out.println("Enter a number between 1 and 10");
}
System.out.println(num);
Since you are expecting a number between 1 to 10, but you don't know how many numbers you will get until you get a valid number, I'd suggest to use a while loop, like so:
import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
while (num1 < 1 || num1 > 10) {
System.out.print("Invalid number, enter another one: ");
num1 = in.nextInt();
}
System.out.println("Input = " + num1);
}
}

Categories