I have been asked to make an Create a new integer array with 16 elements - java

Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}

import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.

Related

Using a for loop, display the number of entries and the sum in Java

so I was asked to create a program in which the user enters four integers and then displays the number of entries and the sum of the integers using a for loop. This is what I came up with.
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int sum = 0;
int count = 0;
for (int i = 0; i != 4 ; i++)
{
System.out.println(" Enter an integer: ");
int num = in.nextInt();
sum = sum + num;
count = count + 1;
}
System.out.println("Number of entries: " + count);
System.out.println("Total sum of entries: " + sum);
}
}
I was wondering what a cleaner way was to ask the user for the four numbers using a for loop, and what other people might suggest be best for this situation. Thanks for any input, p.s. (I have just started learning!)
i think you are looking something like this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum=0;
for(int i=0;i<4;i++){
System.out.println("ENter Number"+(i+1));
sum += sc.nextInt();
}
System.out.println("the Sum is "+sum);
sc.close();
}
You can check with enter. If user presses enter, you can break.
enterkey = readinput.nextLine();
System.out.print(enterkey);
if(enterkey.equals("")){
break;
}
Have a look at this solution. I cleaned it up a bit. Maybe you will find some design decisions I made which will help you in the future:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int sum = 0;
for (int count = 1; count <= 4; count++) {
System.out.print(String.format("Please enter %d. integer: ", count));
sum = sum + readNumber(scanner);
}
System.out.println("The sum of numbers entered is: " + sum);
}
}
private static int readNumber(Scanner scanner) {
do {
String input = scanner.nextLine();
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.print(String.format("Input %s is not a valid integer. Try again: ", input));
}
} while (true);
}
As you're a beginner it's the best way for getting input from the user in console. But you are for the condition should be like:
for ( int i =0;i < 4 ; i ++){}

program that reads integers between 1 and 100 and counts the occurrence of each

Write a program that reads integers between
1 and 100 and counts the occurrence of each (you should store the numbers in an array). Output should be in ascending order. Assume the input ends when the user enters a 0.
Hi guys, I know that this question has been posted before, perhaps a lot of times, but as I am a complete beginner at java, I don't completely understand the complexity of the codes that are posted. I just started taking Java classes, and would appreciate if you could help me figure out how to get my program to output the correct occurrences at the end. I'm so close to getting the answer but I can't figure it out for the life of me!! Thanks in advance!
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
//declarations
int [] myArray = new int [100];
int input = 5;
Scanner keyboard = new Scanner(System.in);
//input and processing
System.out.println("Please enter integers between 1 and 100 (enter 0 to stop): ");
while (input != 0)
{
input = keyboard.nextInt();
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] = input;
}
}
}
//output (This is where I need help!!!!)
for (int k = 0; k < myArray.length; k++)
{
if (myArray[k] != 0)
{
System.out.print(k + " occurs " + myArray[k] + " time");
if (myArray[k] > 1)
{
System.out.println("s");
}
else
System.out.println("");
}
}
keyboard.close();
}
}
You are storing the number entered by the user in the array. Instead, you should store a counter in each position of the array for the corresponding integer. When the user inputs a number, you should increase the corresponding counter.
The second part of your code (output results) seems ok. It is the first one that needs fixing.
I think the first for loop should be something like this:
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] += 1;
}
}
}
This should store add 1 to the array everytime the numbers occurs.
hey this my source code that worked out or me.
package test2;
import java.util.Arrays;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// ask for user to input numbers
System.out.println("Enter some integers between 1 and 100 (and 0 when done): ");
int[] myArray = new int[1000];//create a new array for user inputs
int number;//variable for user inputs
int count = 0;
do
{
number = input.nextInt();
myArray[count] = number;
count++;
}
while (number != 0);
int[] mySort = new int [count - 1]; //create a new array with only the numbers
for(int i = 0; i< (count-1); i++) { //get the array until 0th number into new
mySort[i] = myArray[i];
}
java.util.Arrays.sort(mySort);// sort the array in ascending order
int n = 0;
for(int i = 0; i < mySort.length; i++) {//check if the number have checked before
int occurance = 0;
if(n >= mySort[i]) {
continue;
}
else {
n = mySort[i];//if a new number found do the calculation+
for (int j=0; j<mySort.length; j++)
if (n == mySort[j])
occurance++;
System.out.print(n + " occurs " + occurance );
{
if (occurance == 1) {
System.out.println(" time.");
}
else {
System.out.println(" times.");
}
}
}
}
}
}

Java scanner count numbers that are in an interval

I'm new with java and i have to write a code that asks the user two numbers an interval. Then the user must introduce n numbers and the program must return how many numbers belong to that interval.
I've tried to do this and this is what i have:
import java.util.*;
public class NumsInter {
public static void main(String[] args) {
Scanner sc;
int a,b,nums,count;
sc = new Scanner (System.in);
System.out.print ("Write two numbers a and b(a<=b)(interval): ");
a=sc.nextInt();
b=sc.nextInt();
count=0;
System.out.println("write a number: ");
while(sc.hasNextInt()){
nums=sc.nextInt();
if (a<=nums && nums>=b){
count= count + 1;
} else {
count= count;
}
}
System.out.println(count +" numbers are included in ("+a+","+b+")");
}
}
Example: If the user writes 2 and 6, and then 4,4,3,1 the output should be 3.
As I am a newbie i don't know how can i do this the good way, can someoen help?
PD: How can i break the loop so i can get the output?
Thank You!
Try something like this
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter the numbers you want to test, enter 'stop' to stop");
boolean userInput = true;
while(input.hasNextInt() && userInput){
if(input.hasNext("stop")){userInput = false;}
numbers.add(input.nextInt());
}
Where you have a loop that checks if there is a next int while at the same time checking to see if the user is done or not.
And them something like this to print your answer
for(int i =0; i < numbers.size(); i++){
testNum = numbers.get(i);
if(testNum > lowerLimit && testNum < upperLimit){
count++;
}
}
System.out.println(count + " valid numbers have been entered!");
take an int [] no_between_max&min after take the input from user and store in this array. after that take a for loop and compare the value of array with max and min ant increase the count variable.
int noOfItem=sc.nextInt();
int [] no_between_max_min = new int[noOfItem];
for(int i=0;i<noOfItem;i++){
no_between_max_min[i]=sc.nextInt();
}
for(int i=0;i<no_between_max_min.length;i++){
if(no_between_max_min[i]>=a&&no_between_max_min[i]<=b){
count++;
}
}

Arrays with user input

I am trying to write a program that repeatedly asks the user to supply scores (out of 10) on a test.It needs to continue until a negative value is supplied. Values higher than 10 should be ignored. I also calculated the average of the inputs. After the scores have been inputted, i need to use a single array to produce a table that automatically fills the test scores and the number of occurrences of the certain test score.
I wanted it to look something like this:
Score | # of Occurrences
0 3
1 2
2 4
3 5
4 6
and so on.. P
I am a beginner and this is my first question, so i am sorry if i made a mistake in posting the question or something.
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main()
{
Scanner kbReader= new Scanner (System.in);
int score[] = new int [10];//idk what im doing with these two arrays
int numofOcc []= new int [10];
int counter=0;
int sum=0;
for (int i=0;i<10;i++)// Instead of i<10... how would i make it so that it continues until a negative value is entered.
{
System.out.println("Enter score out of 10");
int input=kbReader.nextInt();
if (input>10)
{
System.out.println("Score must be out of 10");
}
else if (input<0)
{
System.out.println("Score must be out of 10");
break;
}
else
{
counter++;
sum+=input;
}
}
System.out.println("The mean score is " +(sum/counter));
}
}
You could use a do...while loop like this:
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main(String args[]) {
Scanner kbReader= new Scanner (System.in);
int scores[] = new int [10];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 10 or negative to break.");
input=kbReader.nextInt();
if (input<0) {
break;
} else if (input>10) {
System.out.println("Score must be out of 10");
} else {
scores[input]++;
counter++;
sum+=input;
}
} while (input>0);
System.out.println("Score\t# of occur...");
for(int i =0; i<10; i++) {
System.out.println(i + "\t" + scores[i]);
};
System.out.println("The mean score is " +(sum/counter));
}
}
The formatting can certainly be done better (without c-style tabs) but I don't remember the syntax at the moment.
I think what you need is a List Array! Create ArrayList from array
Think of it as a dynamic array, you don't need to specify the size of the array and it is expanded/made smaller automatically.
What you're missing is a while loop. Here is a nice way to loop through a Scanner for input. It also catches numbers greater than 10 and provides an error message:
public static void main() {
Scanner s = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int response = 0;
while (response >= 0) {
System.out.print("Enter score out of 10: ");
response = s.nextInt();
if (response > 10) {
System.out.println("Score must be out of 10.");
} else if (response >= 0) {
list.add(response);
}
}
// Do something with list
}

How to sum elements of a stack

import java.util.*;
public class multiple {
public static int userNumber;
public static int userChoice;
static Stack<Object> stack = new Stack<Object>();
static int[] list = new int[100];
public static void main(String[] args) {
introduction();
multiple();
printStack(stack);
}
public static void introduction() {
Scanner input = new Scanner(System.in);
System.out.print("Welcome to the program, please enter the number less than 100 that you would like "
+ "to find whoes number \nbelow have muliples of 3 and 5: ");
userNumber = input.nextInt();
System.out.println();
// System.out.println("Ok, now that youve entered," + userNumber +
// " we will find out which numbers of you number are three and five. "
// +
// "would you like the result published as a:\n 1.alist \n 2.A sum of the result \n 3.Or both?");
// userChoice = input.nextInt();
// if (userChoice >=1 && userChoice <=3)
// System.out.println( "The Computer will now program for" +
// userChoice);
// else
// System.out.println("incorrect entry for menu. Please try again");
}
public static void multiple() {
for (int i = 1; i < userNumber; i++) {
if (i % 3 == 0 || i % 5 == 0) {
stack.push(i);
}
}
}
// public static addElementsofstac
private static void printStack(Stack<Object> s) {
if (s.isEmpty())
System.out.println("You have nothing in your stack");
else
System.out.println(s);
}
}
I am trying to make a simple program that will take input for a user, find out the multiples of 3 & 5, then return the sum of the multiple. I have all the multiples discovered. I have a hunch that i need to convert the stack to an array. if so, would i just use stack.toArray()? then i would add them in a for loop?
Alternative without the need for intermediary counter variable:
int sum = 0;
while (stack.size() > 0) sum += stack.pop();
Why would you need an array?
You just need to do something along the lines of:
int sum = 0;
for(i=0;i<stack.size();i++){
sum = sum + stack.pop();
}
Though I agree with the others in that there's really no purpose of the stack itself.
EDIT: your clarification is only more confusing. How are 3, 6 and 9 multiples of 10? Are you talking about integers less than an inputted number that are multiples of 3 and 5?
I usually do this way:
ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
int ans = 0;
<...>
for (Integer n : stack) {
ans += n;
}

Categories

Resources