Int array pushed through while loop until it reaches -1 - java

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

Related

Finding the mode of an array from user input java

So I'm making a program that gets an array from user-inputed values but I'm having trouble writing the code for finding the mode of the array. I tried writing my own code and then tried using a version of someone else's code but that didn't work out because I didn't fully understand it to be honest.
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int length;
Statistics stats = new Statistics();
System.out.println("Welcome to our statistics program!");
System.out.print("Enter the amount of numbers you want to store: ");
length=Integer.parseInt(keyboard.next());
int[] nums = new int[length];
for(int i=0; i<length; i++) {
System.out.println("Enter a number: ");
nums[i]=keyboard.nextInt();
}
System.out.println("Array elements are: ");
for (int i=0; i<length; i++) {
System.out.println(nums[i]);
}
public int Mode (int[] nums) {
double maxValue = -1.0d;
int maxCount = 0;
for(int i = 0; i < data.length; i++) {
double currentValue = data[i];
int currentCount = 1;
for(int j = i + 1; j < data.length; ++j) {
if(Math.abs(data[j] - currentValue) < epsilon) {
++currentCount;
}
}
}
if (currentCount > maxCount) {
maxCount = currentCount;
maxValue = currentValue;
} else if (currentCount == maxCount) {
maxValue = Double.NaN;
}
}
System.out.println("The minimum number is " + stats.Mode(nums));
You could consider using a HashMap to maintain the frequencies of the values in the array in your loop:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static int getIntegerInput(String prompt, Scanner scanner) {
System.out.print(prompt);
int validInteger = -1;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
validInteger = scanner.nextInt();
break;
} else {
System.out.println("Error: Invalid input, try again...");
System.out.print(prompt);
scanner.next();
}
}
return validInteger;
}
public static int getPositiveIntegerInput(String prompt, Scanner scanner) {
int num = getIntegerInput(prompt, scanner);
while (num <= 0) {
System.out.println("Error: Integer must be positive.");
num = getIntegerInput(prompt, scanner);
}
return num;
}
public static int getMode(int[] nums) {
if (nums.length == 0) {
throw new IllegalArgumentException("nums cannot be empty");
}
Map<Integer, Integer> valueFrequencies = new HashMap<>();
valueFrequencies.put(nums[0], 1);
int maxFreq = 1;
int candidateMode = nums[0];
for (int i = 1; i < nums.length; i++) {
int value = nums[i];
valueFrequencies.merge(value, 1, Integer::sum);
int candidateFreq = valueFrequencies.get(value);
if (candidateFreq > maxFreq) {
candidateMode = value;
maxFreq = candidateFreq;
}
}
return candidateMode;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numsLength = getPositiveIntegerInput("Enter how many numbers you want to store: ", scanner);
int[] nums = new int[numsLength];
for (int i = 0; i < numsLength; i++) {
nums[i] = getIntegerInput(String.format("Enter number %d: ", i + 1), scanner);
}
int mode = getMode(nums);
System.out.printf("Mode: %d%n", mode);
}
}
Example Usage:
Enter how many numbers you want to store: 0
Error: Integer must be positive.
Enter how many numbers you want to store: 6
Enter number 1: 3
Enter number 2: 2
Enter number 3: 5
Enter number 4: 5
Enter number 5: 3
Enter number 6: 3
Mode: 3

How can I find the highest, lowest, and average value of all test scores within my loop?

Good afternoon, or whenever you are reading this. I am trying to figure out how I can find the minimum, highest, and average of test scores that a user enters.
I have a loop that keeps track of a sentinel value, which in my case is 999. So when the user enters 999 it quits the loop. I also have some level of data validation by checking if the user entered over 100 or under 0 as their input. However, my question is, how can I implement a way to get this code to find the values I need for my user inputs. My code is as follows:
import java.util.Scanner;
public class TestScoreStatistics
{
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int testScore;
double totalScore = 0;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int lowScore;
int highScore;
String scoreString = "";
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT)
{
if (testScore < 0 || testScore > 100 )
{
System.out.println("Incorect input field");
}
else
{
scoreString += testScore + " ";
counter++;
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
System.out.println(scoreString);
System.out.println(counter + " valid test score(s)");
}
}
While keeping your code pretty much the same, you could do it like this:
import java.util.Scanner;
public class TestScoreStatistics
{
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int testScore;
double totalScore = 0;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int lowScore = 100; //setting the low score to the highest score possible
int highScore = 0; //setting the high score to the lowest score possible
String scoreString = "";
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT)
{
if (testScore < 0 || testScore > 100 )
{
System.out.println("Incorect input field");
}
else
{
scoreString += testScore + " ";
counter++;
//getting the new lowest score if the testScore is lower than lowScore
if(testScore < lowScore){
lowScore = testScore;
}
//getting the new highest score if the testScore is higher than highScore
if(testScore > highScore){
highScore = testScore;
}
totalScore += testScore; //adding up all the scores
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
double averageScore = totalScore / counter; //getting the average
}
This will check if the testScore is higher or lower than the highest and lowest scores. This program will also add all the scores together and divide them by the counter (which is how many tests there are) to get the average.
This is how I would do this.
// defines your prompt
private static String PROMPT = "Please enter the next number> ";
// validation in a separate method
private static int asInteger(String s)
{
try{
return Integer.parseInt(s);
}catch(Exception ex){return -1;}
}
// main method
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
System.out.print(PROMPT);
String line = scn.nextLine();
int N = 0;
double max = 0;
double min = Integer.MAX_VALUE;
double avg = 0;
while (line.length() == 0 || asInteger(line) != -1)
{
int i = asInteger(line);
max = java.lang.Math.max(max, i);
min = java.lang.Math.min(min, i);
avg += i;
N++;
// new prompt
System.out.print(PROMPT);
line = scn.nextLine();
}
System.out.println("max : " + max);
System.out.println("min : " + min);
System.out.println("avg : " + avg/N);
}
The validation method will (in its current implementation) allow any integer number to be entered. As soon as anything is entered that can not be converted into a number, it will return -1, which triggers a break from the main loop.
The main loop simply keeps track of the current running total (to calculate the average), and the maximum and minimum it has seen so far.
Once the loop is exited, these values are simply printed to System.out.
With minimal changes of your code:
public class Answer {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int testScore;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int maxScore = Integer.MIN_VALUE;
int minScore = Integer.MAX_VALUE;
double totalScore = 0;
double avgScore = 0.0;
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT) {
if (testScore < 0 || testScore > 100) {
System.out.println("Incorect input field");
} else {
counter++;
System.out.println("The number of scores you entered is " + counter);
//test for minimum
if(testScore < minScore) minScore = testScore;
System.out.println("Current minimum score = " + minScore);
//test for maximum
if(testScore > maxScore) maxScore = testScore;
System.out.println("Current maximum score = " + maxScore);
//calculate average
totalScore += testScore;
avgScore = totalScore / counter;
System.out.println("Current average score = " + avgScore);
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
}
}

ending loop without use of break and convert for loop to while

this is my code
import java.util.*;
public class test3
{
public static void main (String [] args)
{
int sum = 0;
int mark;
Scanner sc = new Scanner(System.in);
for (int student = 1; student <=10; student++)
{
System.out.println("enter mark");
mark = sc.nextInt();
if (mark > 0)
{
sum = sum + mark;
}
else
{
student = 10;
}
}
System.out.println("sum is" + sum);
}
}
i want to change this code so that the loop ends without having to use student = 10 to end loop. i cant think of anything that would end the loop. and also convert it to a while loop so far i have
int student = 1 ;
int sum = 0;
int mark
Scanner sc = new Scanner(System.in);
while (student <= 10)
{
System.out.println("enter mark");
mark = sc.nextInt();
sum = sum + mark;
student++;
}
but i dont know how to end loop if 0 is input we're not allowed to use break; to exit loop could i get some help please?
The ways for ending loops are:
using break
if the condition is not satisfied in the next interation
Including the loop in a method and using return
What about this:
int student = 1 ;
int sum = 0;
int mark
Scanner sc = new Scanner(System.in);
while (student <= 10) {
System.out.println("enter mark: ");
mark = sc.nextInt();
if (mark > 0) {
sum += mark;
} else {
student = 10;
}
student++;
}
System.out.println("sum is = " + sum);
Use while (student <= 10) condition and student = 10 statement to exit the loop:
public static void main(String[] args) {
int sum = 0;
int mark;
Scanner sc = new Scanner(System.in);
int student = 1;
while (student <= 10) {
System.out.println("enter mark");
mark = sc.nextInt();
if (mark > 0) {
sum = sum + mark;
} else {
student = 10;
}
student++;
}
System.out.println("sum is" + sum);
}

How can I achieve this specific output using for loops to simplify storing data in an array?

public class IndividualProject2 {
public static void main(String[] args) {
int i;
for( i = 0; i < 7; i++){
Scanner gradeInput = new Scanner(System.in);
System.out.println("Enter midterm 1 score: ");
int num1 = gradeInput.nextInt();
System.out.println("Enter midterm 2 score: ");
int num2 = gradeInput.nextInt();
System.out.println("Enter final score: ");
int num3 = gradeInput.nextInt();
}
}
public static char function (int grade){
String[] name = new String[7];
char[] finalGrade = new char[7];
char letter;
if (grade >= 90){
letter = 'A';
System.out.println(letter);
}
else if (grade >= 80 && grade < 90){
letter = 'B';
System.out.println(letter);
}
else if(grade >= 70 && grade < 80){
letter = 'C';
System.out.println(letter);
}
else{
letter = 'F';
System.out.println(letter);
}
for(int counter=0; counter < finalGrade.length; counter++ ){
finalGrade[counter] = letter;
}
return letter;
}
public static int function (int midtermOne, int midtermTwo) {
int result;
int[] midterm = new int[7];
if ( midtermOne > midtermTwo)
{
result = midtermOne;
}
else{
result = midtermTwo;
}
for(int counter=0; counter < midterm.length; counter++ ){
midterm[counter] = result;
}
return result;
}
public static double function (int num1, int num2, int num3){
double result;
double[] average = new double[7];
result = (num1 + num2 + num3)/3.0;
for(int counter=0; counter < average.length; counter++ ){
average[counter] = result;
}
return result;
}
}
The output should look like this http://i.imgur.com/GHo2YS6.png
I am having difficulty creating a loop that match this specific output.How do I take the inputs in the the loop while using the three function methods to store the values in the arrays. I feel very overwhelmed on how to do this.
Move Scanner gradeInput = new Scanner(System.in); before the for loop in your main. In this way you can avoid doing the same thing 7 times which is not useful in anyway.
Declare four arrays - name, midTerm1, midTerm2 and avg for holding 4 values for each student. You can define them at the class level or inside main.
Fill these four arrays for each student something like
for(int i = 0; i < 7; i++){
System.out.println("Student number " + (i + 1) );
System.out.print("Enter student's name: ");
name[i] = gradeInput.next();
System.out.print("Enter midterm 1 score: ");
midTerm1[i] = gradeInput.nextInt();
System.out.print("Enter midterm 2 score: ");
midTerm2[i] = gradeInput.nextInt();
System.out.print("Enter final score: ");
avg[i] = gradeInput.nextInt();
}
Once, this is done do as below
System.out.printf("%-8s %6s %8s %8s\n", "name", "final", "midterm", "average");
for(int i = 0; i < 7; i++) {
System.out.printf("%-8s %6c %8d %2.6f\n", name[i] , function(avg[i]), function(md1[i], md2[i]), function(md1[i], md2[i], avg[i]));
}
Remove all the print statements from function (int grade).
One side note It is also possible not to hard code the value for number of students - in your case 7 and pass it from command line. In this case, you can use that number to initialize all the four arrays sizes and modify the for loops appropriately.
For example - inside main, you can do something like
public static void main(String[] args) {
int noOfStudents;
if (args.length == 1) {
noOfStudents = Integer.parseInt(args[0]);
name = new String[noOfStudents];
midTerm1 = new int[noOfStudents];
midTerm2 = new int[noOfStudents];
avg = new int[noOfStudents];
} else {
System.out.println("please provide a value for no of students data that need to be processed");
return;
}
}

how to find StickNumbers

So I have to read a sequence of numbers from the console ( 1 to 50 numbers), none of which are equal and print out the numbers for which is true that a|b == c|d (example: 5|32 == 53|2), but I get an NubmferFormatException each time. Why?
import java.util.Scanner;
public class StuckNumbers {
public static void main(String[] args) {
// create Scanner
Scanner input = new Scanner(System.in);
// input count and declare array
System.out.println("input number of numbers");
int count = input.nextInt();
int[] numbers = new int[count];
// check if count is between 1 and 50
if (count < 1 && count > 50) {
System.out.println("Wrong input. Input a number between 1 and 50");
count = input.nextInt();
}
// input n numbers
for (int i : numbers) {
i = input.nextInt();
// check if i = j
for (int j : numbers) {
if (i == j) {
System.out
.println("All numbers must be dist75inct. Try again.");
i = input.nextInt();
}
}
}
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
if (stuckNumbers(numbers[i], numbers[j]) == stuckNumbers(
numbers[j], numbers[i])) {
System.out.println(i + "|" + j + " == " + j + "|" + i);
}
}
}
input.close();
}
public static int stuckNumbers(int a, int b) {
String firstNum = "a";
String secondNum = "b";
String res = "ab";
int result = Integer.parseInt(res);
return result;
}
}
Look at these lines:
String res = "ab";
int result = Integer.parseInt(res);
"ab" is not a number, so you're going to get a NumberFormatException when you try to parse it as an integer.
Change the firstNum and SecondNum variables from "a" and "b" to Integer.toString(a); OR String.valueOf(a); and similar for b.
public static int stuckNumbers(int a, int b) {
String firstNum = String.valueOf(a);
String secondNum = String.valueOf(b);
String res = "";
res.concat(firstNum);
res.concat(secondNum);
int result = Integer.parseInt(res);
return result;
}
I hope this will remove any Exception being thrown.

Categories