JAVA : How do I input a ( < 0 ) to break the code? - java

2 weeks in. I need to break the while loop with a negative integer but I've been unable to implement it successfully. This is my original code before I editted left and right to no avail. The values in Print are outside the loop.
public class AssignmentQuestion2 {
public static void main(String[] args) {
//write your code here
ArrayList<Integer> rainfall = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Please input rainfall(Input negative value to exit)");
while (in.hasNextInt()) {
if (in.hasNextInt()) {
rainfall.add(in.nextInt()); //how to input into array
System.out.println(calculateAverage(rainfall)); //average
System.out.println(findSmallest(rainfall)); //smallest input
System.out.println(findLargest(rainfall)); //largest input
} else {
in.close();
}
}
}

You can break a loop using the (aptly named) break statement:
int r;
while ((rainfall != null)) {
if (in.hasNextInt()) {
r = in.nextInt();
if (r < 0) {
break;
}
rainfall.add(r); //how to input into array
System.out.println(calculateAverage(rainfall)); //average
System.out.println(findSmallest(rainfall)); //smallest input
System.out.println(findLargest(rainfall)); //largest input
}
}

Related

Why do I have to put an integer twice for my Scanner input to work?

I'm trying to make a simple program where you can put integers in, and it will tell you if it increased or decreased from the previous integer input. But when I run the code, I have to put an integer value twice, but I only want it put once.
The input and output should look like (numbers typed by me, words output by the program):
Starting...
5
Increasing
4
Decreasing
6
Increasing
etc. etc.
But instead it looks like:
Starting...
5
5
Increasing
Input Number:
1
2
Not Increasing
etc. etc.
This is my code:
import java.util.Scanner;
public class Prob1 {
public static void main(String[] args) {
System.out.println("Starting...");
int input;
int previousInput = 0;
Scanner scan = new Scanner(System.in);
while (!(scan.nextInt() <= 0)) {
input = scan.nextInt();
if (input > previousInput) {
System.out.println("Increasing");
previousInput = input;
} else {
System.out.println("Not Increasing");
previousInput = input;
}
System.out.println("Input Number:");
}
scan.close();
}
}
Why does this problem occur, and how can I fix it?
The loop behavior you are describing is:
read a numeric input value
do something with it (print a message)
if the loop value meets a condition (input is 0 or less), exit the loop
otherwise, repeat
Here's a "do-while" loop that reads like those steps above:
Scanner scan = new Scanner(System.in);
int input;
do {
input = scan.nextInt();
System.out.println("input: " + input);
} while (input > 0);
System.out.println("done");
And here's input+output, first entering "1", then entering "0":
1
input: 1
0
input: 0
done
while (!(scan.nextInt() <= 0)) { takes an int and then input = scan.nextInt(); takes another one. You need to change the while loop to use input.
modified based on your code
public static void main(String[] args) {
System.out.println("Starting...");
int input;
int previousInput = 0;
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Input Number:");
input = scan.nextInt();
if (input <= 0) {
System.out.println("app shut down");
break;
}
if (input > previousInput) {
System.out.println("Increasing");
} else {
System.out.println("Not Increasing");
}
previousInput = input;
}
scan.close();
}

How to find max number and occurrences

So I'm learn java for the first time and can't seem to figure how to set up a while loop properly .
my assignment is Write a program that reads integers, finds the largest of them, and counts its occurrences.
But I have 2 problems and some handicaps. I'm not allowed to use an array or list because we haven't learned that, So how do you take multiple inputs from the user on the same line . I posted what I can up so far . I am also having a problem with getting the loop to work . I am not sure what to set the the while condition not equal to create a sential Value. I tried if the user input is 0 put I cant use user input because its inside the while statement . Side note I don't think a loop is even needed to create this in the first place couldn't I just use a chain of if else statement to accomplish this .
package myjavaprojects2;
import java.util.*;
public class Max_number_count {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int count = 0;
int max = 1;
System.out.print("Enter a Integer:");
int userInput = input.nextInt();
while ( userInput != 0) {
if (userInput > max) {
int temp = userInput;
userInput = max;
max = temp;
} else if (userInput == max) {
count++ ;
}
System.out.println("The max number is " + max );
System.out.println("The count is " + count );
}
}
}
So how do you take multiple inputs from the user on the same line .
You can use scanner and nextInput method as in your code. However, because nextInt only read 1 value separated by white space at a time, you need to re-assign your userInput varible at the end of while loop to update the current processing value as below.
int userInput = input.nextInt();
while ( userInput != 0) {
//all above logic
userInput = input.nextInt();
}
The code:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0, count = 0, num;
System.out.println("Enter numbers:-");
while ((num = sc.nextInt()) != 0) {
if (num > max) {
max = num;
count = 1;
} else if (num == max) {
count++;
}
}
System.out.println("\nCount of maximum number = "+count);
}
}
And you don't have to use ArrayList or Array. Just keep inputting numbers till you get 0.
You can implement this with a single loop. The traditional concise pattern for doing so involves the fact that assignment resolved to the value assigned. Thus your loop can use (x = input.nextInt()) != 0 to terminate (handling exceptions, and non-integer input left as an exercise for the reader). Remember to display the max and count after the loop and reset the count to 1 when you find a new max. Also, I would default max to Integer.MIN_VALUE (not 1). That leaves the code looking something like
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a Integer:");
int count = 0, max = Integer.MIN_VALUE, userInput;
while ((userInput = input.nextInt()) != 0) {
if (userInput > max) {
max = userInput;
count = 1;
} else if (userInput == max) {
count++;
}
}
System.out.println("The max number is " + max);
System.out.println("The count is " + count);
}

How can I define a char variable within a method?

I'm attempting to write a loop, that when the user inputs Y, the loop continues, and when the user inputs N, the loop stops. However, when I try to assign the variable I get the error "Cannot convert from void to char" I'm obviously messing up somewhere along the line but I'm not sure where.
import java.util.Scanner;
public class SimpleList {
public static void main(String[] args) {
System.out.println("Welcome to the Simple List Class");
getData();
}
private static void getData() {
Scanner input = new Scanner(System.in);
float[] numbers = new float[10];
System.out.println("Enter a non-negative floating point value: ");
for(int i = 0; i < 10; i++) {
float x = input.nextFloat();
if (x > 0) {
numbers[i] = x;
char ans = System.out.print("Would you like to input another value? (Y or N)? ");
}
else {
System.out.println("That is not a valid. Try Again.");
}
}
System.out.println(Arrays.toString(numbers));
}
} ```
You're assigning ans to the result of System.out.print() which is a void method.
Instead, create the prompt beforehand and use the Scanner to take the input:
public class SimpleList {
public static void main(String[] args) {
System.out.println("Welcome to the Simple List Class");
getData();
}
private static void getData() {
Scanner input = new Scanner(System.in);
float[] numbers = new float[10];
System.out.println("Enter a non-negative floating point value: ");
for(int i = 0; i < 10; i++) {
float x = input.nextFloat();
if (x > 0) {
numbers[i] = x;
// New Prompt
System.out.print("Would you like to input another value? (Y or N)? ");
// Take input and set ans
char ans = input.next().charAt(0);
}
else {
System.out.println("That is not a valid. Try Again.");
}
}
System.out.println(Arrays.toString(numbers));
}
}

How to sum up user's input in arraylist?

I am trying to make a program that reads integers from the user and adds them to a list. This ends when the user enters 0. The program then prints the sum on the list.
My code works but the problem is the sum value does not add up correctly
public class Main {
private static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
ArrayList<Integer> test1 = new ArrayList<Integer>();
System.out.println("Enter multiple numbers"); //if user enters =0; loop ends
while (input.nextInt() != 0) {
test1.add(input.nextInt());
input.nextLine();
}
int total = 0;
for(int x : test1){
total+=x;
}
System.out.println(total);
}
}
You are only storing every third value in your loop. This
while (input.nextInt() != 0) {
test1.add(input.nextInt());
input.nextLine();
}
should be something like
int value;
while ((value = input.nextInt()) != 0) {
test1.add(value);
}
or
while (input.hasNextInt()) {
int value = input.nextInt();
if (value == 0) {
break;
}
test1.add(value);
}

Java Scanner Continuous User input?

For java practice, i am trying to create a program that reads integers from the keyboard until a negative one is entered.
and it prints the maximum and minimum of the integer ignoring the negative.
Is there a way to have continuous input in the same program once it runs? I have to keep running the program each time to enter a number.
Any help would be appreciated
public class CS {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = keys.nextInt();
while(true)
{
if(n>0)
{
System.out.println("Enter again: ");
n = keys.nextInt();
}
else
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
}
Here is a part of my code - It works, but i think there is an easier way of doing what i want but not sure how!
import java.util.Scanner;
public class ABC {
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Feed me with numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Keep Going!");
}
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
You could do something like:
Scanner input = new Scanner(System.in);
int num;
while((num = input.nextInt()) >= 0) {
//do something
}
This will make num equal to the next integer, and check if it is greater than 0. If it's negative, it will fall out of the loop.
A simple loop can solve your problem.
Scanner s = new Scanner(System.in);
int num = 1;
while(num>0)
{
num = s.nextInt();
//Do whatever you want with the number
}
The above loop will run until a negative number is met.
I hope this helps you

Categories

Resources