for loop condition and if statment - java

I have made a for loop and I want the loop to break when the user enters a negative value and then give a message. I do not want the program to calculate the negative value.
public class test1
{
public static void main(String[] args)
{
PrintStream output = new PrintStream(System.out);
Scanner input = new Scanner(System.in);
List<Integer> yolo = new ArrayList<Integer>();
double sum = 0;
output.println("Enter your integers\n" + "(Negative=sentinel)");
// add the values to your empty Array except the negative entries
for (int entry = input.nextInt(); entry < 0 ; entry = input.nextInt())
{
yolo.add(entry);
if (entry >= 0 )
{
sum += entry;
}
else {
output.println("Your list is empty");
}
}
I tried using Outerloop:, and break outerloop; but it breaks the loop even at positive integers.

change it to
for ( int entry = input.nextInt(); entry >= 0; entry = input.nextInt())
because currently the loop is only running when the entered number is < 0.
So the loop has the semantic(meaning):
run while the entries are >= 0, read every time from the input to entry
So the loop finishes, when a user enters a negative number.

// add the values to your empty Array except the negative entries
It looks like you're also missing out a small thing.
What you want to do is:
if (entry >= 0){
yolo.add(entry);
sum += entry;
}
For your problem, I think your for-loop as declared is wrong, because each time you call input.nextInt() it will ask for a new input, and you can put negative values the second time whatever happens.

Related

How do I read different inputs from scanner in Java?

I need to get various integral inputs and then when -1 is entered, the program should show the largest, smallest, sum of all entered, number of values of all entered, and the mean of all values entered. I have started a loop to take various inputs but cannot find a suitable way to read them and then play with them. I have searched everywhere on the internet.
import java.util.Scanner;
public class Exercise16 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter a Positive integer or -1 to quit.");
while (!s.nextLine().equals("-1")) {
System.out.println("Please enter a Positive integer or -1 to quit.");
}
}
}
s.nextLine() reads your input
You should save it to a variable.
Also using a do-while to prevent the copied print statement
Scanner s = new Scanner(System.in);
String in; // where to save next input value
do {
System.out.println("Please enter a Positive integer or -1 to quit.");
in = s.nextLine();
// TODO: parseInt, check for positive number
} while (!in.equals("-1"));
If you want to track mins and maxes, you need two additional integer values.
If you want to track averages, you need a list.
Best of luck
You first need to read integer from command line. For that you have to use
s.nextInt();
Once you get this you have to get largest and smallest number, you can get these using 2 variables.
For average you can store sum and number of times user asked for input, 2 more variable. No need to store elements in list or some other storage.
If you want to see numbers entered than you have to store else you don't have to.
For storing use :
List<Integer> numbers = new ArrayList<Integer>();
For adding number you can use add method of List.
public static void main2() {
Integer laregst = Integer.MIN_VALUE;
Integer smallest = Integer.MAX_VALUE;
Integer sum = 0;
Integer count =0 ;
Scanner s = new Scanner(System.in);
int temp = s.nextInt();
while (temp != -1) {
if(temp > laregst){
laregst = temp;
}
if(temp < smallest){
smallest = temp;
}
sum += temp;
count += 1;
System.out.println("Please enter a Positive integer or -1 to quit.");
temp = s.nextInt();
}
System.out.println("Largest : "+(count == 0?"NA":laregst)+" Smallest : "+(count == 0?"NA":smallest)+" Mean : "+(count == 0 ? "NA" : ((sum *1.0/count))));
}
if you wont to read Multible Integers Value in Same Line you Can use s.nextInt() to read one Integer Value in each time

Why can't I have a user prompted varaible be the array size?

public class Sort {
public static void main(String[] args) {
int i = 1;
Scanner input = new Scanner(System.in);
// prompts the user to get how many numbers need to be sorted
System.out.print("Please enter the number of data points: ");
int data = input.nextInt();
// this creates the new array and data sets how large it is
int [] userArray = new int[data];
// this clarifies that the value is above 0 or else it will not run
if (data < 0) {
System.out.println("The number should be positive. Exiting.");
}
// once a value over 0 is in, the loop will start to get in all user data
else {
System.out.println("Enter the data:");
}
while (i <= data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
// this calls the sortArray method to sort the values entered
sortArray(userArray);
// this will print the sorted array
System.out.println(Arrays.toString(userArray));
}
}
I have set the array size equal to what the user inputs for how many variables they will be entering to be sorted. For some reason, Java only wants a set number instead of the number that is entered by the user. Is there a way to make this work?
First of all, there are a few mistakes in your code. You are checking if(data < 0) after you create your array with int[] userArray = new int[data];. You should check it before.
Furthermore, you will get ArrayIndexOutOfBoundsException because userArray[data] does not exist. Array indices start at 0, so the last index is data-1. You need to change your while-loop to while(i < data) instead of while(i <= data).
The problem is not that you have data instead of 10 as the length of the array. The problem is as I stated above: your while-loop.
Your issue is the while loop. Because arrays are 0 based and you need to only check if i < data. By setting it to <=, you are exceeding the array length and generating and ArrayIndexOutOfBoundsException
while (i < data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
You are over-indexing the array. A more standard way for inputting the data would be
for ( int i=0; i < data; i++ ) {
userArray[i] = input.nextInt();
}

How to use for loop to input 10 numbers and print only the positives?

I'm trying to make a "for" loop in which it asks the user to input 10 numbers and then only print the positives.
Having trouble controlling the amount of inputs. I keep getting infinite inputs until I add a negative number.
import java.util.Scanner;
public class ej1 {
public static void main(String args[]) {
int x;
for (x = 1; x >= 0; ) {
Scanner input = new Scanner(System.in);
System.out.print("Type a number: ");
x = input.nextInt();
}
}
}
From a syntax point of view, you've got several problems with this code.
The statement for (x = 1; x >= 0; ) will always loop, since x will always be larger than 0, specifically because you're not introducing any kind of condition in which you decrement x.
You're redeclaring the scanner over and over again. You should only declare it once, outside of the loop. You can reuse it as many times as you need.
You're going to want to use nextLine() after nextInt() to avoid some weird issues with the scanner.
Alternatively, you could use nextLine() and parse the line with Integer.parseInt.
That said, there are several ways to control this. Using a for loop is one approach, but things get finicky if you want to be sure that you only ever print out ten positive numbers, regardless of how many negative numbers are entered. With that, I propose using a while loop instead:
int i = 0;
Scanner scanner = new Scanner(System.in);
while(i < 10) {
System.out.print("Enter a value: ");
int value = scanner.nextInt();
scanner.nextLine();
if (value > 0) {
System.out.println("\nPositive value: " + value);
i++;
}
}
If you need to only enter in ten values, then move the increment statement outside of the if statement.
i++;
if (value > 0) {
System.out.println("\nPositive value: " + value);
}
As a hint: if you wanted to store the positive values for later reference, then you would have to use some sort of data structure to hold them in - like an array.
int[] positiveValues = new int[10];
You'd only ever add values to this particular array if the value read in was positive, and you could print them at the end all at once:
// at the top, import java.util.Arrays
System.out.println(Arrays.toString(positiveValues));
...or with a loop:
for(int i = 0; i < positiveValues.length; i++) {
System.out.println(positiveValues[i]);
}
Scanner scan = new Scanner(System.in);
int input=-1;
for(int i=0;i<10;i++)
{
input = sc.nextInt();
if(input>0)
System.out.println(input);
}

Java ArrayList: Utilising ArrayList for print message

In my Java program I have an ArrayList. What I want to do is print a number at the bottom that will say 'x amount of people have passed'
System.out.println = ("The amount of people that have more than 40 marks is " + x);
Is it possible to calculate how many numbers of marks will be more than 40 if there are an undetermined amount of marks put in, utilising an ArrayList?
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
// Create a new scanner to use in java
int[] range = { 0,29,39,69,100 };
// A new array is created with the grade boundaries
int[] inRange = new int[boundary.length - 1];
// Indexed from 0 to n-1
int markIn;
// New integer markIn
do {
// This do-while loop calculates the expression after the statements below are exectued at least once
System.out.println("Enter Mark(s):");
// Wait for user input
markIn = input.nextInt();
// markInp value is set as the value entered by user
marks.add(markIn);
for (int a=1 ; a<boundary.length ; a++)
// for loop will take the variable 'a' and compare it with varibale 'boundary', when the condition is satisfied that value of 'a' increments by 1
if (range[a-1] <= markInp && markInp <= range[a]) {
// The boundaries will define the upper and lower limits of the markInp
inRange[a-1]++;
//inRange is incremented by 1
break;
//Exit if
}
} while (markIn <= 100);
// When the mark exceeds 100, the loop is stopped
System.out.println(marks);
input.close();
} // Close the Scanner input
}
You can do something like :
int result = 0;
if(marks != null)
{
Collections.sort(marks);
for(int i=0;i<marks.size();i++)
{
if(marks.get(i) > 40)
{
result = marks.size() - i;
break;
}
}
}
marks is the arraylist and result is desired output.
If the array is already sorted, like you show in your example, then you just have to do a simple search from where you start seeing a particular score, then taking the length of the array and subtracting the position of the element that came from your search.
If the array isn't sorted, sort it and then do the search.

Error checking duplicate user-input array values

I am self-learning Java and am stuck on a simple project. I'd like to receive 6 unique 'lottery' numbers from a user.
User will be asked to input an integer.
Each user input will be placed into an array.
If the user inputs a previously input number, I want to prompt to reenter the number again.
Recheck the new input. If unique, continue the for loop. If non-unique, run step 3 again.
So far, all I have is:
public static int[] userLottoInput()
{
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < userNums.length; i++ ) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
for (int k=i; k<userNums.length; k++) {
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}
}
}
Any help is appreciated!!
Try and keep you logic simple.
While the user hasn't enter 6 numbers, loop
Ask the user for a value
Check to see if it's a duplicate
If it is, ask the user to re-enter the value
If it's not (a duplicate) increment the counter to the next element...
For example...
public static int[] userLottoInput() {
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
int i = 0;
// Keep looping until we fill the array, but
// allow the control to fall somewhere else
while (i < userNums.length) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
// Check for duplicates
boolean duplicate = false;
// We only need to check up to i - 1, as all the
// other values are defaulted to 0
// We also don't need to check for the last number entered ;)
for (int k = 0; k < i; k++) {
// Check for duplicated
if (userNums[k] == userNums[i]) {
System.out.println("No duplicates allowed, please try again");
duplicate = true;
// Break out of the loop as we don't need to check any more..
break;
}
}
// If no duplicates where found, update i to the next position
if (!duplicate) {
i++;
}
}
return userNums;
}
With this, there is only one point at which you prompt the user. Everything else is used to control the element position (i) to meet your requirements.
Now, I'm sure that there are other ways to do this and this is just a simple example ;)
Move the asking of number outside loop, when received the number loop over the numbers array to find a match. If match found re-ask for number (outside the for loop used for finding the match), else if match not found, then add the number to array.
Don't you think your for loop is little complicated. Anyways, you can try this :
for (int k=0; k<i-1; k++) { //Start k=0 means from the first stored value
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}

Categories