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.
Related
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.
I'm having an issue where I want to keep asking the user for input while it is between 0-8, and if it isn't, or if it's already in the hash set, to ask it again.
HashSet<Integer> hash = new HashSet<Integer>(9);
list = new ArrayList<Integer>(9);
System.out.println("\n Enter your own 8-Puzzle Configuration of non-repeating numbers ranging from 0-8.");
int num = 0;
int i = 0;
do {
try {
System.out.println("Enter #" + i + ": ");
num = kb.nextInt();
if (hash.contains(num)) {
System.out
.println("This is number was already entered. Please try again.");
System.out.println("Enter #" + i + ": ");
num = kb.nextInt();
}
if (num <= 0 || num > 8) {
System.out
.println("# must be in the range of 0-8.");
System.out.println("Enter #" + i + ": ");
num = kb.nextInt();
}
list.add(num);
hash.add(num);
i++;
} catch (InputMismatchException e) {
System.out.println("Not a valid number. Try again");
}
kb.nextLine();
} while (i < 9);
You were adding incorrect values if two incorrect values were added in a row. Also, you don't need to use a set - the ArrayList also has a contains method.
ArrayList list = new ArrayList(9);
System.out.println("\n Enter your own 8-Puzzle Configuration of non-repeating numbers ranging from 0-8.");
do {
int index = list.size() + 1;
try {
System.out.println("Enter #" + index + ": ");
int num = kb.nextInt();
if (list.contains(num)) {
System.out
.println("This is number was already entered. Please try again.");
} else if (num <= 0 || num > 8) {
System.out.println("# must be in the range of 0-8.");
} else {
list.add(num);
}
} catch (InputMismatchException e) {
System.out.println("Not a valid number. Try again");
}
} while (list.size() < 8);
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);
I am creating a program that will determine and print the number of odd, even, and zero digits in an integer from the keyboard. I have tried a few different ways and have gotten the same result with each. I cannot get java to recognize 0 as 0, but only as an even number. Ex. 1005 will give 2 Odds and 2 Evens.
public static void main(String[] args) {
int odd = 0;
int even = 0;
int zero = 0;
int input;
Scanner scan = new Scanner (System.in);
System.out.println("Input an integer please: ");
input = scan.nextInt();
System.out.println("Your number is: " + input);
String x = Integer.toString(input);
for (input = 0; input < x.length(); input++){
char a = x.charAt(input);
System.out.println(a);
Character.getNumericValue(a);
if (a==0){
System.out.println ("+1 Zero");
zero++;
}
else if (a%2 == 0 && a>1){
System.out.println("+1 Even");
even++;
}
else {
System.out.println("+1 Odd");
odd++;
}
}
System.out.println("There are " + odd + " odd numbers!");
System.out.println("There are " + even + " even numbers!");
System.out.println("There are " + zero + " zero numbers!");
}
you haven't assigned Character.getNumericValue(a) to int value .
char a = x.charAt(input);
System.out.println(a);
int y= Character.getNumericValue(a);
if (y==0){
System.out.println ("+1 Zero");
zero++;
}
else if (y%2 == 0 && y>1){
System.out.println("+1 Even");
even++;
}
else {
System.out.println("+1 Odd");
odd++;
}
the Character.getNumericValue(a); method returns an int. It does not implicitly change the parameter (the character variable 'a' in this case).
Thus, you should compare the return value of the getNumericValue method and not the original character.
I would like to write a game about who would take the last marble and I've successfully run it. But when I attempted to add some error messages to it, such as showing "Incorrect range" when the inputs are out of range, it doesn't work properly. I know the problem is due to the incorrect recognition of variable "totalNum", but how to solve it? Thanks in advance :)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pn = 1;
System.out.print("Intial no. of marbles [10 ~ 100]: ");
int totalNum = in.nextInt();
int input = 0;
int from = 1;
int to = totalNum/2;
if (totalNum < 10||totalNum > 100) {
System.out.println("Incorrect range. Try again!");
System.out.print("Intial no. of marbles [10 ~ 100]: ");
totalNum = in.nextInt();
}
else {
while (totalNum > 1) {
totalNum = in.nextInt();
System.out.print("Player" + pn + " [" + from + " ~ " + to + "]: ");
input = in.nextInt();
if (input < from||input > to) {
System.out.println("Incorrect range. Try again!");
continue;
}
totalNum = totalNum - input;
System.out.println("Remaining no. of marbles: " + totalNum);
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
}
}
System.out.println("Player" + pn + " takes the last marble.");
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
System.out.println("Player" + pn + " wins!");
}
I imagine this line in the while loop is the problem:
totalNum = in.nextInt();
It keeps trying to take the next input from the user but there isn't a second integer. Not sure what happens after that.
Also, your entire program seems to be roughly equivalent to doing
totalNum%2+1
and printing the answer.