Java - Using for loops to read user input - java

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

Related

Working on a Java Program that utilizes For Loops to separate Even, Odd, and Negative Inputted Integers. Try Catch Handler Gives Out-of-bounds Error? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 12 months ago.
I am working on a Java program that determines Evens, Odds, and Negative numbers from 12 inputted integers.
It then separates them into different arrays. The course I am following suggests building an exception handler and I utilized the Try-Catch Method for the Exception error I may receive.
It then creates an Out of Bounds error for counting these numbers when I enter a String.
I've commented on the area in which I have trouble reprompting the user. So far, I've tried prompting at the error with twelveInt [i] = in.nextInt(); and just in.next();.
Why is the program affected outside of the loop?
Here is the program:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
boolean ehandle = true;
for (int i = 0; i < twelveInt.length; i++) {
while(ehandle){
try{
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt [i] = in.nextInt();
ehandle = false;
}
catch(Exception e){
System.out.println("Please enter integers only");
// Unsure of what to add here to handle the errors and allow me to reprompt. in.next();
//does not work nor does twelveInt [i] = in.nextInt();
}
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
The problem in your code is that after you run your loop and enter your first number, you then define ehandle = false.
This means that you never enter the rest of your loop since you exit the while loop. Therefore, you never increment the values of countEven, countOdd, or countNeg.
This results in an error because when you try running this line: int [] evens = new int [countEven]; , countEven is still 0, so you get an error when you try to iterate it.
To avoid this error, you can modify your try catch error as so:
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
for (int i = 0; i < twelveInt.length; i++) {
System.out.println("Enter the #" + (i + 1) + " integer.");
boolean error = true;
while (error) {
try {
twelveInt [i] = in.nextInt();
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
error = false;
}
catch (Exception e) {
System.out.println("Please enter integers only");
in.next();
}
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
}
}
We first try taking in the user input, and if we get an exception error, we will use the catch so our code does not terminate. NOTE: we must do in.next() otherwise we will get an infinite loop (since integers leave a trailing newline, resulting in infinite exceptions).
I hope this helped! Please let me know if you need any further clarifications or details :)
If you want to reiterate your while(ehandle) loop when you get an exception, you can put continue in your catch block. But you should set ehandle back to true at the top of your for-loop.
for (int i = 0; i < twelveInt.length; i++) {
ehandle = true;
while (ehandle) {
try {
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt[i] = in.nextInt();
ehandle = false;
} catch(Exception e) {
System.out.println("Please enter integers only");
continue;
}
...

Int array pushed through while loop until it reaches -1

I have to take a single line of user input, and calculate the average of all the numbers until it reaches -1 using a while loop. An example of user input could be something like 2 -1 6 which is why I've done it this way. I've figured out how to split this into an int array, but I can't figure out how to do the while loop portion.
System.out.println("user input")
String user = scan.nextLine();
String[] string = user.split(" ");
int[] numbers = new int[string.length];
for(int i = 0;i < string.length;i++) {
numbers[i] = Integer.parseInt(string[i]);
}
while ( > -1){
}
Class java.util.Scanner has methods hasNextInt and nextInt.
import java.util.Scanner;
public class Averages {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter series of integers on single line separated by spaces.");
System.out.println("For example: 2 -1 6");
int sum = 0;
int count = 0;
while (scan.hasNextInt()) {
int num = scan.nextInt();
if (num == -1) {
break;
}
sum += num;
count++;
}
if (count > 0) {
double average = sum / (double) count;
System.out.println("Average: " + average);
}
else {
System.out.println("Invalid input.");
}
}
}
Note that you need to cast count to a double when calculating the average otherwise integer division will be performed and that will not give the correct average.
I am assuming you mean, when user input number is -1. we should take average of all number before -1. that is was I am doing here.
System.out.println("user input")
String user = scan.nextLine();
int totalSum = 0;
double avg = 0;
String[] string = user.split(" ");
int[] numbers = new int[string.length];
for(int i = 0;i < string.length;i++) {
numbers[i] = Integer.parseInt(string[i]);
if(numbers[i]==-1){
avg = (double)totalSum / i;
break;
}
totalSum += numbers[i];
}
With only while loop
System.out.println("user input");
String user = scan.nextLine();
int totalSum = 0;
double avg = 0;
String[] string = user.split(" ");
int[] numbers = new int[string.length];
int i = 0;
numbers[i] = Integer.parseInt(string[i]);
while(numbers[i]!=-1) {
totalSum += numbers[i];
i++;
numbers[i] = Integer.parseInt(string[i]);
}
avg = (double)totalSum / i;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("user input");
String user = scan.nextLine();
boolean found = false;
Double average = 0.0;
String[] string = user.split(" ");
int[] numbers = new int[string.length];
for(int i = 0;i < string.length && found == false ;i++) {
numbers[i] = Integer.parseInt(string[i]);
}
int t = 0;
while (found == false && t < string.length){
if(numbers[t] == - 1){
average = average/t;
found = true;
}
else{
average = (Double) average + numbers[t];
t++;
}
}
System.out.println("Average = " + average);
}
}

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

Why is my code not incrementing?

So my professor had us do an assignment that asks the user for 5 numbers that are valid (51-99) and unique (non-repeating). I just can't figure out why my nested for loop inside the while loop is not incrementing the i, I suspect it is the break; but without that the for loop keeps looping. Any help would be awesome. Thank you.
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
I got it guys! I just had to remove the for loop and put this in:
userArray[i] = count;
i++;
real++;
Thank you schmidt73 and everyone that helped!
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
I guess this is what you are trying to do.
First, you also need to test if the array contains the value you are trying to add (in validate). You could do something like
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
Then your main method might be written like
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));

Java try-catch statement inside while loop

I have this method and it works fine. I need to put a try/catch statement so
the method can continue if the user puts in a letter. I don't know where to put the statement, It seems everywhere I put it it get's wrong. Could somebody please show me where to put this statement?
public void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
number = in.nextInt();
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}
if (!end) {
System.out.println("I cant find number " + number
+ " in the array, please try again ");
}
}
}
Your for loop I can't explain, you need only check values between 0 and 20,
And when you call try catch, you have to skip loop after exception
public static void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number=0;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
//check symbol
try{
number = Integer.valueOf(in.next());
}catch(Exception e)
{
System.out.println("It's not a number! ");
continue; //skip loop
}
if((number>=0)&&(number<=20))
{
System.out.println(array[number]);
end=true;
}
else
System.out.println("I cant find number " + number
+ " in the array, please try again ");
/* why do you use loop here???
* u need to check if number between 0-20
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}*/
}
}
public static void main(String[] args) {
Test test = new Test();
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
System.out.println("Please give an number between 0-20: ");
do{
try{
number = Integer.parseInt(in.next());
}
catch(Exception e){
System.out.println("Please give an number between 0-20: ");
number = -1;
}
}
while(!(number <= 20 && number >=0 ));
System.out.println(array[number]);
}
System.out.println("Please give an number between 0-20: ");
try{
number = in.nextInt();
}catch(Exception e){
number = 1; //Put random number of default number here
}

Categories