I must write a do loop that reads integers and computes their sum. Stop when reading a zero or the same value twice in a row. For example, if the input is 1 2 3 4 4, then the sum is 14 and the loop stops. Same thing if user input is 0. I need to know if I can use multiple parameters for the do while statement or if i need to nest another do while stamenent.
int input = 0;
int total = 0;
int update = 0;
System.out.println("Enter any number");
total = inputDevice.nextInt();
do
{
System.out.println("Enter any number");
input = inputDevice.nextInt();
// Do i have to nest a do-while statement here?
total = total + input;
}while((input != 0); // Or How would i insert a second parameter that stops the loop when a number is entered twice in a row?
For the above parameters I know i would do && to start the second parameter, I just cannot figure out the logic statement I would insert as the parameter.
System.out.println("The sum of the numbers is " + total);
}
}
You need to save the last input in a variable and then compare it with the actual input (and break the while loop if they're equal)
Try this:
int last_input = 0;
int input = 0;
int total = 0;
int update = 0;
Scanner inputDevice = new Scanner(System.in);
do
{
System.out.println("Enter any number");
input = inputDevice.nextInt();
total = total + input;
if(last_input == input)
break;
last_input = input;
}while(input != 0); // Or How would i insert a second parameter that stops the loop when a number is entered twice in a row?
System.out.println("The sum of the numbers is " + total);
This is fairly simple and you can do it with a "normal" while loop, e.g. by replacing the do-while statement with
while (true) {
System.out.println("Enter any number");
input = inputDevice.nextInt();
total = total + input;
if ((input == 0) || (input == update)) {
break; // Exit the loop
} else {
update = input; // Remember the last value
}
}
The above example reuses the update variable which does not seem to be used for anything else. If it is needed for another purpose, it can of course be replaced with another variable, declared in the same area with input.
int prevInput = 0;
bool bFirstRun = true
do
{
System.out.println("Enter any number");
if(!bFirstRun)
{
prevInput = input
}
input = inputDevice.nextInt();
bFirstRun = false;
total = total + input;
if(prevInput == input)
break;
}while((input != 0);
I would add a prevInput parameter as above and a boolean to check if its the first time through the loop. If it is then dont check the previous input, if its not the first time through then check the input to the previous (after it was added to the total) and if its the same then break from the loop.
Here... try this. It's simpler
int num1 = 0, num2 = 0, total = 0;
do {
num2 = num1;
System.out.println("Enter any number");
num1 = inputDevice.nextInt();
total += num1;
System.out.println("The sum of the numbers is " + total);
} while (num1 != num2 && num1 != 0);
Related
Using a while loop to prompt the user to enter 3 ints to average them out, need to reprompt when the input isn't an int, so I decided to take a step back in the loop when the input isn't an int, but when I enter a non int, it's as if it consistently goes to the condition that it isn't a int, and continues to reprompt, without rechecking for a new input.
Scanner scnr = new Scanner(System.in);
String prompt = "Type an integer: ";
int num = 0;
int i = 0;
while (i < 3) {
System.out.print(prompt);
if (scnr.hasNextInt()) {
int input = scnr.nextInt();
num += input;
} else i -= 1;
i += 1;
}
double average = num / 3.0;
System.out.println("Average: " + average);
hasNextInt() only returns true if an int is already there -- it doesn't actually get input. That's what your call to nextInt() is doing. But that's never being called because hasNextInt() is always false, as you've never actually taken user input, so i is being decremented in the else block and then incremented again forever.
An alternative approach would be to use a try/catch block with nextInt() to get the next input value, and step back if that catches an exception (meaning the input was not an int).
As a previous user has mentioned the main problem is that the hasNextInt() only checks and doesn't advance your scanner forward.
Here is how I would do this code, I hope it solves the issue:
int counter = 0;
boolean flag = false;
int sum = 0;
while(!flag){
System.out.println(prompt);
if (scnr.hasNextInt()){
int input = Integer.parseInt(scnr.nextLine());
sum = sum + input;
counter++;
}else{
scnr.nextLine();
System.out.println("You didn't enter an Integer.");
}
if (counter == 3){
flag = true;
}
}
double avg = sum / 3;
System.out.println("Average: " + avg);
There are probably better ways of doing it than mine but I hope it helps, good luck!
The point of the program is to have a user input an amount of integers endlessly (until they enter something other than an integer), and for each integer the user inputs, it should check if the integer is greater than or less than the value entered.
The problem: When the program runs, everything is fine until reaching
number = scanner.nextInt();
At this point, the user inputs their integer, but never makes it inside the following if statements. I would love a hint instead of an answer, but I'll take what I can get.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
} while (true);
scanner.close();
}
}
Your minNumber and maxNumber declarations should be out side of the loop. Also, you need to initialize the values as below to get correct min and max comparison with the entered values only:
int minNumber = Integer.MAX_VALUE;
int maxNumber = Integer.MIN_VALUE;
In print statement instead of minNumber you are printing number!
It's not reaching the if statements, because if it did, the user input would update to the value entered I would think. It doesn't. It outputs the values initially declared.
You're not getting the right output and you have a hypothesis that the cause is the code not entering the if statements. Following the scientific method, the next step is to test your hypothesis.
If you put printouts inside the if statements you'll see that they are indeed running. That's not it. The mistake must be elsewhere. You should collect more evidence and develop a new hypothesis.
Hint: Try printing out the values of your variables at the beginning and end of each iteration. I've marked the places below. Are they what you expect them to be? You're going to see an anomaly that should point you in the right direction.
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
// Print number, minNumber, and maxNumber.
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
// Print number, minNumber, and maxNumber.
} while (true);
I'm having some problems splitting a string that is read in from an input file, making sure it's valid, then saving it to a variable.
Let's say this is the first string:
12345 5 59.28
I would want to split the 12345, 5, and 59.28.
After verifying that they are the correct format ( 00000-99999, 0-5, 000.00 0 100.00 ), I would then assign it to a variable.
My main two obstacles are that I CANNOT use arrays in this program, so I'm not sure how to split the string. I have tried just pulling each section as an int, but that doesn't seem to work.
My other problem is that I'm not sure how to validate it. Would I be using something like this:
//Assuming I have a scanner set up and a class, method declared
//Declare variables
int numbers;
int studentID;
while(fileInput.hasNext())
{
numbers = fileInput.nextInt(); //Not sure how to pull a part of the string
}
//Used to validate that it is within the range
if(numbers < 00000 || numbers > 99999)
{
studentID = numbers;
}
I am a beginner at Java so please do excuse my confusion.
If you know what the structure of the file is, for example if it's always formatted like this:
int int double
Then you can simply callnextInt(), nextInt(), and then nextDouble() to parse the data from it that way.
Maybe something like this
do
{
num1 = scanner.nextInt();
num2 = scanner.nextInt();
num3 = scanner.nextDouble();
} while (scanner.hasNextInt());
And do that in order to collect all of your data, but you'll likely need lots of variables if you have any substantial amount of data you're reading in
Or if there's bad data sometimes with it's correct data immediately after it you could so something like this to skip over the bad one, even though it's not very pretty
do
{
if (scanner.hasNextInt())
{
num1 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num1 = scanner.nextInt();
}
if (scanner.hasNextInt())
{
num2 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num2 = scanner.nextInt();
}
if (scanner.hasNextDouble())
{
num3 = scanner.nextDouble();
}
else
{
scanner.next() // move past whatever bad data there was
num3 = scanner.nextDouble();
}
} while (scanner.hasNext());
I think your teachers give this assignment to practice your if-else condition or switch statement and for loop(fundamental) skills.
Here what I did, this may be not completely match with your assignment question but using this you can get complete idea and think of a way to reduce this. Hey! because of we are not here to do your assignment. you have to tackle with your problem and get familiar with those.
Try to understand these, do changes look what happen:
public static void main(String[] args) {
Scanner fileInput = new Scanner(System.in);
//Declare variables
String numbers = "";
String firstNum = "";
String secondNum = "";
String thirdNum = "";
int studentID = 0;
int secondDigit = 0;
double thirdDigit = 0;
System.out.print("Input: ");
numbers = fileInput.nextLine();
int firstIndex = 0;
int secondIndex = 0;
int thirdIndex = 0;
firstIndex = numbers.indexOf(" ");
if(firstIndex <= 4){
System.out.println("Number should be 5");
}else{
firstNum = numbers.substring(0, firstIndex);
numbers = numbers.substring(firstIndex+1);
studentID = Integer.parseInt(firstNum);
if(studentID > 0 && studentID < 99999){
System.out.println("First num: " +firstNum);
}else{
System.out.println("first digits not in a range ");
}
}
secondIndex = numbers.indexOf(" ");
if(secondIndex == 0){
System.out.println("no number");
}else{
secondNum = numbers.substring(0, secondIndex);
numbers = numbers.substring(secondIndex+1);
secondDigit = Integer.parseInt(secondNum);
if(secondDigit >= 0 && secondDigit <= 5){
System.out.println("Second num: " +secondNum);
}else{
System.out.println("second digit not in a range ");
}
}
thirdIndex = numbers.length();
if(thirdIndex < 3){
System.out.println("3 numbers should be there");
}else{
thirdNum = numbers.substring(0, thirdIndex);
thirdDigit = Double.parseDouble(thirdNum);
if(thirdDigit >= 0 && thirdDigit <= 100){
System.out.println("third num: " +thirdNum);
}else{
System.out.println("third digit not in a range ");
}
}
}
I'm not going to explain this also. You have to try, if you have any problem after tackling with this code. ask any question in comment.
Hope this will help!
Try this. Invalid formats will throw an exception during the next method call.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner("12345 5 59.28");
in.useDelimiter(" "); // reads per space
String next = in.next("\\d{5}"); // reads next 5 digits
int numbers = Integer.valueOf(next);
System.out.println(numbers);
next = in.next("\\d{1}"); // reads next 1 digit
int studentId = Integer.valueOf(next);
System.out.println(studentId);
next = in.next("\\d{2}\\.\\d{2}"); // reads next a decimal with two digits before and after point
float floatingNumbers = Float.valueOf(next);
System.out.println(floatingNumbers);
}
}
<script src="//repl.it/embed/IWzC/0.js"></script>
I am trying to validate my code by error checking. I want to make sure the integer people enter does not contain a letter or more.
Here is my code. I am supposed to solve this problem using a one dimensional array. I got the code working but I am having problems with adding the error checking in.
Any help would be appreciated. Thanks
public void getNumbers() {
Scanner keyboard = new Scanner(System.in);
int array[] = new int[5];
int count = 0;
int entered = 0;
int k = -1;
while (entered < array.length) {
System.out.print("Enter a number ");
int number = keyboard.nextInt();
if (10 <= number && number <= 100) {
boolean containsNumber = false;
entered++;
for (int i = 0; i < count; i++) {
if (number == array[i]) // i Or j
{
containsNumber = true;
}
}
if (!containsNumber) {
array[count] = number;
count++;
} else {
System.out.println(number + " has already been entered");
}
} else {
System.out.println("number must be between 10 and 100");
}
//what does %d do?
for (int j = 0; j < count; j++) {
System.out.printf("%d ", array[j]);
}
System.out.println();
}
}
}
I'm assuming that you would want your program to ask the user to re-enter a number if they do not input a number the first time. In this scenario you might want to try something along the lines of this:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while(!sc.hasNextInt()) {
//print some error statement
sc.nextLine();
}
int number = sc.nextInt();
System.out.println("Number is: " + number); // to show the value of number
// continue using number however you wish
Since hasNextInt() returns a boolean determining whether or not the input is an Integer, the program will never leave the while-loop until the program can confirm that the user has entered an integer.
keyboard.nextInt() will throw a InputMismatchException if you input a String.
If you want to check whether Scanner has an integer to read, you can use keyboard.hasNextInt().
Alternatively, you can read the input as
String s = keyboard.next() which will take the input as a String, and then use s.matches(".*\\d+.*") to detect whether or not it is an integer.
UPDATE: To answer questions -
keyboard.hasNextInt() will return a boolean. So for example, after System.out.print("Enter a number"), you could have an if statement checking to see if keyboard can receive numerical input, ie. if(keyboard.hasNextInt). If this is true, that means the user has entered numerical input, and you could continue with sayingint number = keyboard.nextInt(). If it is false, you would know that the user input is non-numerical.
I have a programming assignment that's asking me to have the user input 10 (or less) integers and put them in an array, then take the average of them and output it. If they input a period, the program should stop asking for integers and do the averaging.
My problem is that whenever the user inputs an integer, the for loop executes more than once.
My code is below. Any ideas on how to fix this?
int[] intArr = new int[10];
int entered;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(entered = 0; entered < 10; entered++){
System.out.println("Please enter an integer: ");
int input = br.read();
if(input == '.') break;
else{
intArr[entered] = input;
}
}
int total = 0;
for(int i : intArr){
total += i;
}
System.out.println("Average: " + total/entered);
System.out.println("Entered: " + entered);
Use String input = br.readLine() to read an entire line.
To check for ".", use if (input.equals(".")) { ... }.
(check out this if you want to know why you have to use .equals() instead of == for Strings)
Finally, to convert the input to an integer, see here.
for (entered = 0; entered < 10; entered++) {
System.out.println("Please enter an integer: ");
String str = br.readLine();
if (".".equals(str)) {
break;
}
int input = Integer.valueOf(str);
intArr[entered] = input;
}
Ok Its Really Simple
First let Me Explain You Why Its Happening
Ok the read() function reads first char of the input value and rest of line is stored in buffer
so when you enter any integer
for example: 1
1 is stored in variable and '\n'which java by defaults adds to a input value gets stored in buffer
so in next iteration of loop
it reads the char '\n' from buffer as input value and moves to next iteration
EXAMPLE 2:
If In Your Program We Enter Input As 12
It Skips Two Iterations
Coz Firstly It Stores 1 At The Time Of Input
In Next Iteration It Takes value 2 of previous input as input for this time
In Further Next Iteration It Takes '\n'
and then moves to next iteration at which their is no character left in memory so it asks you to input
Note:::
read() functions return character so even if user enters 5 while calculation ASCII Code Of 10 will be used that is 53 not one creating problems
FIX:::
int[] intArr = new int[10];
int entered;
BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
for (entered = 0; entered < 10; entered++) {
System.out.println("Please enter an integer: ");
String input = br.readLine();
if (input.equals(".")) {
break;
} else {
intArr[entered] = Integer.parseInt(input);
}
}
int total = 0;
for (int i: intArr) {
total += i;
}
System.out.println("Average: " + total / entered);
System.out.println("Entered: " + entered);