Problems with Arrays and Methods [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
How to get the program to read a set of integers from an input file. The goal is to store them in an array and then display greater values than input. Also, Also, create a method called greater_than_n() that accepts an integer array and an integer n. The purpose of this method is to display numbers greater than n
import java.util.Scanner;
import java.io.*;
public class Lab5 // File Name{
public static void main(String[] args) throws IOException
{
Scanner userInput = new Scanner(System.in);
File Integers = new File("Integers.txt");
Scanner inputReader = new Scanner(Integers);
String line = inputReader.nextLine();
System.out.print(line);
inputReader.close();
System.out.print("Enter an Integer: ");
int userAction = userInput.nextInt();
System.out.println("The numbers in the input file that are greater than " + userAction + " are: ");
for (int index = 0; index < Integers.length; index++)
{
if(Integers[index] > userAction)
{
System.out.print(Integers + " ");
}
}
}
}

You are checking in a wrong way. Your loop should iterate up to the length of array. Then if you want to print the greater numbers in the array, check each element if greater than the input number. If yes, print the number in the index.
Scanner userInput = new Scanner(System.in);
int[] numbers = {2, -4, 6, 8, 19};
System.out.print("Enter an Integer: ");
int userAction = userInput.nextInt();
System.out.println("The numbers in the input file that are greater than " + userAction + " are: ");
for (int index = 0; index < numbers.length; index++) {
if(numbers[index] > userAction)
System.out.print(numbers[index] + " ");
}

You are printing out array on every step of loop, to print out a number you should change System.out.print(numbers); for System.out.print(numbers[index]);.
More of than if you want to print just number which greater then input (userAction=3, output should be 6, 8, 19 for your example), you have a error in your algorithm. What your algorithm does is just print out array userAction times. To fix it you can use this snippet:
for (int index = 0; index < numbers.length; index++)
{
if (numbers[index] > userAction) {
System.out.print(numbers[index]);
}
}

You print the Arrayobject, what you want is to print the index of the array, this can be accomplished by using:
System.out.print(numbers[index]).

Related

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

Printing out error messages when user does not input any numbers in array or entering too many numbers into an array

Hello java pros and experts, the first problem I have is implementing a code into my program where it tells a user "No numbers were entered" when they do not enter any numbers and the array is empty.
the second problem I have is implementing a code if the user enters too many numbers, put out an Error message that the size of the array has been exceeded; then print out the numbers entered on the next line.
This is my code so far:
import java.util.Scanner;
public class FunWithArrays
{
public static void main(String[] args)
{
final int ARRAY_SIZE = 10; // Size of the array
// Create an array.
int[] numbers = new int[ARRAY_SIZE];
// Pass the array to the getValues method.
getValues(numbers);
System.out.println("Here are the " + "numbers that you entered:");
// Pass the array to the showArray method.
showArray(numbers);
}
public static void getValues(int[] array)
{
// Create a Scanner objects for keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a series of " + array.length + " numbers.");
// Read the values into the array
for (int index = 0; index < array.length; index++)
{
System.out.print("Enter the number " + (index + 1) + ": ");
array[index] = keyboard.nextInt();
}
}
public static void showArray(int[] array)
{
// Display the array elements.
for (int index = 0; index < array.length; index++)
System.out.print(array[index] + " ");
}
}
I was wondering if you pros or experts have any advice on how to approach this problem without changing any of the codes in my program? my professor instructed me to do a do-while loop for the problem, but do not know how to create the code for it... any suggestions?

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

Asking the user what size the array should be

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

Java - No Duplicate number array

I am in the process of creating of a Lottery Program using Java via BlueJ and I am having trouble with the user inputted numbers and the number being generated by the program (up to and including 1-49), I need the numbers that are entered by the user to not be duplicate i.e. the user cannot enter 1 and 1.
I am not really sure how to get the numbers to not be duplicate i was thinking of using an Array but im not sure what type or where to begin im rather new to the whole programming thing.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class JavaApplication8 {
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
Scanner keyIn = new Scanner(System.in);
int[] LotteryNumbers = new int[6];
int input;
int count = 0;
System.out.print("Welcome to my lottery program which takes\nyour lottery numbers and compares\nthem to this weeks lottery numbers!");
System.out.print("\n\nPress the enter key to continue");
keyIn.nextLine();
for (int i = 0; i < LotteryNumbers.length; i++)
{
count ++;
System.out.println("Enter your five Lottery Numbers now " + count + " (must be between 1 and 49): ");
input = Integer.parseInt(user_input.next());
if (input < 1 || input > 49)
{
while (input < 1 || input > 49)
{
System.out.println("Invalid number entered! \nPlease enter lottery number (between 1 and 49) " + count);
input = Integer.parseInt(user_input.next());
if (input >= 1 || input <= 49)
{
LotteryNumbers[i] = input;
}
}
}
else
{
LotteryNumbers[i] = input;
}
}
System.out.println("Thank you for your numbers.\nThe system will now check if you have any matching numbers");
System.out.print("Press the enter key to continue");
keyIn.nextLine();
Random randNumGenerator = new Random();
StringBuilder output = new StringBuilder();
int[] ActLotteryNumbers = new int[6];
for (int j = 0; j < ActLotteryNumbers.length; j++)
{
int roll = randNumGenerator.nextInt(49);
ActLotteryNumbers[j] = roll;
}
System.out.println(Arrays.toString(ActLotteryNumbers));
int counter = 0;
for (int i = 0; i < LotteryNumbers.length; i++)
{
for (int j = 0; j < ActLotteryNumbers.length; j++)
{
if (LotteryNumbers[i] == ActLotteryNumbers [j])
{
counter ++;
System.out.println("The numbers that match up are: \n" + LotteryNumbers[i]);
}
}
}
if (counter == 0)
{
System.out.println("You had no matching numbers this week ... Try Again next week!");
}
}
}
As "fge" mentioned, use Set to add all the values that you are getting from the user.
Get the user inputs and add it to Set.
Use a Iterator to check the user entered values and generated random numbers.
Set myset = new HashSet();
myset.add(user_input1);
myset.add(user_input1);
To retrive use the iterator'
Iterator iterator = myset.iterator();
while(iterator.hasNext(){
int value= iterator.next();
if(randomValue==value)
//do your logic here
}
I am assuming this is for a school project/lab? (This is due to the JavaApplication8 class name) If that is the case, what the instructor is most likely looking for is a contains method.
For a contains method you write a method that takes an integer and checks to see if it is already in your LotteryNumbers array and returns a boolean. It would return true if it is in the array, false if it is not in it. This method would be called before inserting the number into LotteryNumbers. You could use your count variable that doesn't appear to be used anywhere else as the limit on your loop in the contains method to avoid checking uninitialized entries.
If there is no restriction on type, the set idea suggested by others works and is more efficient, it just depends on what you are supposed to be using for your requirements.
Additionally, the logic you use should most likely be applied to ActLotteryNumbers as well. If you can't have duplicates incoming, you shouldn't have duplicate values in the comparing array. Lottery isn't fair in real life, but not that unfair ;-)
First step should be checking your restrictions on this project.

Categories