Asking the user what size the array should be - java

import java.util.Scanner;
/**
* Created by b00598439 on 30/09/2015.
*/
public class Assessment1 {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number 1 for arrays, 2 to use ArrayLists, or any other number to end the program");
for (int i = 1; i<=2; i=>3; i++){
answer[i] nextInt(); //Get integer entered, if different from 1 or 2, if any other number then quit
}
System.out.println("What size of array would you like?");
int SIZE = in.nextInt(); //What size should the array be?
int [] answer = new int[SIZE]; //Lets user read into the program
System.out.println("The total of the numbers in the program is: " + answer); //Gives total of numbers
System.out.println("The average of the numbers in the program is: " + avg);
int count = 0;
for (int i = 0) ; //Calculating the average
I have been trying to get the code sorted to write to screen and follow on through for the size of the array. I have to get the user to select an option 1, or option 2, if option 1 or 2 isn't chosen then I have to terminate the program. I cannot even get the first part printing or working and this is what I have to do:
1) If the array option is chosen, the program should:
• Ask the user what the size of the array should be
• Let the user read in the numbers into the array
• Output the total of the numbers stored in the array
• Output the average of the numbers stored in the array
I have been sitting here for 4 hours and still getting nowhere
Any help would be appreciated

This can be done in many ways,I have done it in a simple way so you can understand the whole code step by step.By the way,you haven't explained what you want the program to do if option 2 was chosen.You can remove the option 2 by deleting the "case 2:".See the code.
import java.util.Scanner;
public class Assessment1 {
public static void main (String args[]) {
int average,sum=0;
Scanner input = new Scanner(System.in);
Scanner length = new Scanner(System.in);
Scanner option = new Scanner(System.in);
System.out.println("Enter 1 for arrays, 2 to use ArrayLists, or any other number to end the program");
int x=option.nextInt();
switch(x){
case 1:
System.out.println("Input array size: ");
int len=length.nextInt();
int[] numbers = new int[len];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
sum += numbers[i];
}
average=sum/len;
System.out.println("Total sum of all numbers: "+sum);
System.out.println("Average of all numbers: "+average);
case 2:
//insert your "ArrayList code here,you haven't explained what you want here
default:
System.out.println("Program terminated.");
}
}
}

Ok, I developed a little more the code. I put it inside a while loop... it goes back to the beginning and asks to again to enter the options... you enter any number other than 1 or 2 and you get out. I tested it and it works ok in the console. Just a comment.. you are getting the average in integer values... if you would like to get doubles then you have to use doubles and use nextDouble instead of nextInt. Hope that it helps.
import java.util.Scanner;
public class Assessment{
public static void main(String[] args){
// Scanner to get the initial number options
Scanner in = new Scanner(System.in);
// Scanner to get numbers to sum
Scanner numSc = new Scanner(System.in);
// Declaration of variables and array
int answer = 0; //You need int answer, don't need an array by now
int numAnswer;
int sum = 0;
int average;
// Loop the program
while (true){
System.out.println("Enter number 1 for arrays, 2 for arraylists, any other to quit");
// Using in Scanner to test for integer input
if(in.hasNextInt()){
// If there is an integer then give it to numAnswer
numAnswer = in.nextInt();
// What to do if the option is 1, 2 or other number
switch(numAnswer)
{
case 1:
case 2:
answer = numAnswer;
break;
default:
System.exit(0); // Out of the program
}
}
// If answer variable got number 1
if (answer == 1){
// New Scanner to get the size of the array
Scanner sizeSc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
// Getting the size of the array with sizeSc Scanner
int size = sizeSc.nextInt();
// Making a new array with the size of size variable
int[] inputNums = new int[size];
// Looping to get input numbers
for (int i = 0; i < inputNums.length; i++){
System.out.println("Enter a number in the array: ");
//Getting the numbers from console with numSc Scanner
inputNums[i] = numSc.nextInt();
sum += inputNums[i]; //Getting the sum of each number
}
average = (sum/size);
System.out.println("Sum of numbers: " + sum);
System.out.println("Average of numbers: " + average);
System.out.println(" ");
} else {
System.out.println("YOUR CODE TO THE LISTARRAY");
}
}
}
}

Related

Do-While Loop not looping - Java

I am having a problem with my java code below. I want the loop to stop when the number "-100" but it stops as soon as you enter any number. I'm just learning how to use java so there could be plenty of mistakes here.
public static void main(String[] args){
Scanner keyboard = new Scanner (System.in);
String num = "";
do {
System.out.println("Enter a number: ");
int n = keyboard.nextInt();
System.out.println("The number you entered is: " +n);
System.out.println("------------------------");
} while ("-100".equals(num));
}
}
num is always the empty string, because you never change the value of num. You update n. Which is what I would base the loop on. Like,
Scanner keyboard = new Scanner(System.in);
int n;
do {
System.out.println("Enter a number: ");
n = keyboard.nextInt();
System.out.println("The number you entered is: " + n);
System.out.println("------------------------");
} while (n != -100);
That is, do loop while n is not -100.

Reading multiple inputs from Scanner

(I'm a beginner at Java)
I am trying to write a program that asks for 6 digits from the user using a scanner, then from those 6 individual digits find the second highest number. So far this works however I'd like to have the input read from a single line rather than 6 separate lines. I've heard of delimiters and tokenisation, but have no idea how to implement it. I'ld like to have it read like "Enter 6 digits: 1 2 3 4 5 6" and parsing each digit as a separate variable so i can then place them in an array as shown. If anyone could give me a run-down of how this would work it would be much appreciated. Cheers for your time.
public static void main(String[] args)
{
//Ask user input
System.out.println("Enter 6 digits: ");
//New Scanner
Scanner input = new Scanner(System.in);
//Assign 6 variables for each digit
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int num4 = input.nextInt();
int num5 = input.nextInt();
int num6 = input.nextInt();
//unsorted array
int num[] = {num1, num2, num3, num4, num5, num6};
//Length
int n = num.length;
//Sort
Arrays.sort(num);
//After sorting
// Second highest number is at n-2 position
System.out.println("Second highest Number: "+num[n-2]);
}
}
Your solution does this allready!
If you go through the documentation of scaner you will find out that your code works with different inputs, as long they are integers separated by whitespace and/or line seperators.
But you can optimice your code, to let it look nicer:
public static void main6(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);
// Assign 6 variables for each digit
int size=6;
int[] num=new int[size];
for (int i=0;i<size;i++) {
num[i]=input.nextInt();
}
Arrays.sort(num);
// After sorting
// Second highest number is at n-2 position
System.out.println("Second highest Number: " + num[size - 2]);
}
As an additional hint, i like to mention this code still produces lot of overhead you can avoid this by using:
public static void main7(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);
// Assign 6 variables for each digit
int size=6;
int highest=Integer.MIN_VALUE;
int secondhighest=Integer.MIN_VALUE;
for (int i=0;i<size-1;i++) {
int value=input.nextInt();
if (value>highest) {
secondhighest=highest;
highest=value;
} else if (value>secondhighest) {
secondhighest=value;
}
}
//give out second highest
System.out.println("Second highest Number: " + secondhighest);
}
if you do not like to point on highest if there are multiple highest, you can replace the else if:
public static void main7(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);
// Assign 6 variables for each digit
int size = 6;
int highest = Integer.MIN_VALUE;
int secondhighest = Integer.MIN_VALUE;
for (int i = 0; i < size - 1; i++) {
int value = input.nextInt();
if (value > highest) {
secondhighest = highest;
highest = value;
} else if (secondhighest==Integer.MIN_VALUE&&value!=highest) {
secondhighest=value;
}
}
// give out second highest
System.out.println("Second highest Number: " + secondhighest);
}
Of course, there are many ways to do that. I will give you two ways:
1. Use lambda functions - this way is more advanced but very practical:
Integer[] s = Arrays.stream(input.nextLine().split(" ")).map(Integer::parseInt).toArray(Integer[]::new);
first create a stream, you can read more about streams here
than read the whole line "1 2 3 ...."
split the line by space " " and after this point the stream will look like ["1", "2", "3" ....]
to convert the strings to int "map" operator is used
and finally collect the stream into Integer[]
You can use an iterator and loop as many times as you need and read from the console.
int num[] = new int[6];
for (int i = 0; i < 6; i++) {
num[i] = input.nextInt();
}
There are several ways to do that:
take a single line string, then parse it.
Scanner input = new Scanner(System.in);
....
String numString = input.nextLine();
String[] split = numString.split("\\s+");
int num[] = new int[split];
// assuming there will be always atleast 6 numbers.
for (int i = 0; i < split.length; i++) {
num[i] = Integer.parseInt(split[i]);
}
...
//Sort
Arrays.sort(num);
//After sorting
// Second highest number is at n-2 position
System.out.println("Second highest Number: "+num[n-2]);

Creating a run time array that takes user input and creates array at run time & accepts 3 variables to calculate sum and average

I keep getting the error "cannot find symbol 'arr' " How do I accept both the array as a user input (being a float not a double) and 3 float variables as elements in the array?
import java.util.Scanner;
public class runtime_array
{
public static void main(String[] args){
System.out.println("Program creates array size at run-time");
System.out.println("Program rounds sum and average of numbers to two decimal places");
System.out.println("Note: numbers *must* be float data type");
System.out.println(); //blank line
// taking String array input from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter length of String array");
int length = input.nextInt();
arr[i] = input.nextInt();
// create an array to save user input
float[] input = new float[length];
float[] input = new float[arr];
// loop over array to save user input
System.out.println("Please enter array elements");
for (int i = 0; i < length; i++) {
}
float sum = 0;
System.out.println("The array input from user is : ");
for(int i = 0; i < arr.length; i++){
System.out.println(String.format("%.2f", Float.valueOf(arr[i])));
sum += Float.valueOf(arr[i]);
}
System.out.println("The sum is: " + String.format("%.2f",sum));
System.out.println("The average is: " + String.format("%.2f",(sum/length)));
}
}
You've got a couple issues here
First, you cannot declare float[] input because you've already given Scanner to the reference for input. You need to name your float[] something different. Let's go with userInput.
Scanner input = new Scanner(System.in);
System.out.println("Please enter length of String array");
int length = input.nextInt();
float[] userInput = new float[length];
Next, you are trying to do things with arr before you have declared it. However, I don't even think you need a reference to arr. You should remove this line.
arr[i] = input.nextInt();
Furthermore, you need to prompt your user during each loop iteration, as well as append the Scanner input to float[] userInput.
for (int i = 0; i < length; i++) {
System.out.println("Please enter array elements");
userInput[i] = input.nextInt();
}

Creating if statement for the small program [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am currently struggling with my first java program.
The question's task was to create a program that prompts the user to enter 5 numbers and store them in an array. Then the array should be printed, after that's done the program prompts the user to enter a number to search. Depending on the number the program should print "(display number) is on the list" or "(display number) is not on the list"
I have been struggling with this for quite a while now not fully understanding the conditional task.
Here is what my code looks like:
public class NewClass {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// Enter three numbers
System.out.print("Enter five numbers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
int number4 = input.nextInt();
int number5 = input.nextInt();
System.out.println("The sorted numbers are "
+ number1 + ", " + number2 + ", " + number3 + ", " + number4 + ", " + number5);
System.out.println("Enter a number to search: ");
}
I added comments to document what the code was doing. This should hopefully help you grasp the concept.
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
//Create an array of integers to store user input
int[] userNumbers = new int[5];
System.out.print("Enter " userNumbers.length + " numbers: ");
//Goes into a loop, and sets each array index to the user inputted integer
for (int i = 0; i < userNumbers.length; i++) {
userNumbers[i] = input.nextInt();
}
System.out.println("Enter a number you would like to search for");
boolean exists = false;
int numToSearch = input.nextInt();
//for each number in the user numbers array, check to see if that number matches the number to search. If so, set exists = true and break out of the loop to check no further.
for (int num: userNumbers) {
if (numToSearch == num) {
exists = true;
break;
}
}
//if else to decide which output to show the user.
if (exists) {
System.out.println(numToSearch + " is in the list");
} else {
System.out.println(numToSearch + " is not in the list");
}
}
}
At first instead of storing your numbers in single variables, you store them in an array.
The next thing you'll do is use
boolean tmp = false;
int search = input.nextInt();
This will give you the number the user is searching for.
When you have it (the program will wait at the instruction until there's input), you loop over your array and in each iteration you compare it to the given number. You do this by using
if (array[i] == search) {
tmp = true}
With i being your iteration variable.
After the end of the for loop, you'll do another if where you, depending on the state of the tmp variable either print that the number exists or it doesn't.
Sorry for short explanation.
Try following....
public class NewClass {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
List<Integer> integers = new ArrayList<Integer>();
// Enter three numbers
System.out.print("Enter five numbers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
int number4 = input.nextInt();
int number5 = input.nextInt();
integers.add(number1);
integers.add(number2);
integers.add(number3);
integers.add(number4);
integers.add(number5);
System.out.println("The sorted numbers are "
+integers);
System.out.println("Enter a number to search: ");
int searchNum = input.nextInt();
if(integers.contains(seacrchNum)){
System.out.println(searchNum+" is on the list");
}else{
System.out.println(searchNum+" is not on the list");
}
}
Explainations :
Placed all the entered numbers into an arrayLists and then prompt for the search Number to be entered. and Check wheather the search number is der in the ArrayLists or not. Based on the condition display the Message

"exception in thread main java.lang.arrayindexoutofboundsexception" when using an array + for loop

when I wrote this code to prompt the user for how many numbers are going to be entered, I got an error saying: "exception in thread main java.lang.arrayindexoutofboundsexception"
PS: note that I used an array of int + for loop to write it.
import java.util.*;
public class Pr8{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
//Prompt the user for how many numbers are going to be entered.
System.out.print("*Please write how many numbers are going to be entered: ");
int a = scan.nextInt();
int[] n = new int[a];
for (int i = 0; i < a; i++){
System.out.print("*Please enter an enteger: ");
n[a] = scan.nextInt();
}//for
}//main
}//Pr8
Change
n[a] = scan.nextInt();
to
n[i] = scan.nextInt();
a is not a valid index in an array that only has a elements. The valid indices are 0 to a-1.

Categories