It is a simple program to find if input x value is in the array or not.
The user types numbers into the array, after that types a number to count how many times this numbers repeats in the array.
What I have:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] mas = new int[5];
for (int i = 0; i < mas.length; i++) {
System.out.print("Input of mas["+i+"]: ");
int n = sc.nextInt();
}
valueX(mas);
for (int i = 0; i < 10000; i++) {
System.out.println("Would you like to continue (1=yes, 0=no)?");
int n = sc.nextInt();
if (n==1) {
valueX(mas);
}
if (n==0) {
System.out.println("Program terminated");
sc.close();
break;
}
}
}
public static void valueX(int mas1[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Input x: ");
int x =scanner.nextInt();
int count =0;
for (int i = 0; i < mas1.length; i++) {
if (x==mas1[i]) {
count++;
}
}
System.out.println("Value "+x+" appears "+count+" time(s) in the array.");
}
The valueX metod should do this work but it does not.
What I expect to get:
Input of mas[0]: 2
Input of mas[1]: 2
Input of mas[2]: 3
Input of mas[3]: 4
Input of mas[4]: 2
Input x: 2
Value 2 appears 3 time(s) in the array.
But what my code does:
Input of mas[0]: 2
Input of mas[1]: 2
Input of mas[2]: 3
Input of mas[3]: 4
Input of mas[4]: 2
Input x: 2
Value 2 appears **0** time(s) in the array.
Could you please find the mistake ?
You are not storing the input value in array so your array has all 0(default value of int) value, hence the issue
int[] mas = new int[5];
for (int i = 0; i < mas.length; i++) {
System.out.print("Input of mas["+i+"]: ");
int n = sc.nextInt();
mas[i] = n;
//^^^^^^^^
}
Related
I wrote this program in Java : Write a program that reads a list of integers and outputs those integers in reverse. The input begins with an integer indicating the number of integers that follow. For coding simplicity, follow each output integer by a comma, including the last one. Assume that the list will always contain fewer than 20 integers.
Ex: If the input is:
5 2 4 6 8 10
the output is:
10,8,6,4,2
As you can see, this is my expected out^ However, I got 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 8 6 4 2 as my output. What is wrong?
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] userList = new int[20]; // List of numElement integers specified by the user
int numElements; // Number of integers in user's list
int i;
numElements = scnr.nextInt(); // Input begins with number of integers that follow
for (i = 0; i < numElements; ++i) {
userList[i] = scnr.nextInt();
}
for (i = userList.length - 1; i >= 0; --i) {
System.out.print(userList[i] + " ");
}
System.out.println();
}
}
I tried to ask a good question and I expect an answer to my question.
Explanation
You are getting zero maybe due to the array size declaration. You created an array with 20 as the size. But assuming you set the numElements to 10, that means that the input iteration will only loop 10 times thus only loading 10 positions in your array.
As you had defined an array with 20 indexes, the rest are initiated with a zero during array declaration. So assuming the iterations goes 10 times that means only 10 indexes will be updated and the other 10/20 left with their initial zeros.
You have to re-declare your array after getting a value for the numElements and set the numElements as the new array size. The code would look similar to below
Scanner scanner = new Scanner(System.in); // Create Scanner object
int[] userList = new int[0]; // Create int array
int numElements = scanner.nextInt(); // Get number of elements
userList = new int[numElements]; // Re-declare array with new size
Solution
The full code in your approach is as below:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int numElements; // Number of integers in user's list int i;
System.out.println("Input length of the array");
numElements = scnr.nextInt(); // Input begins with number of integers that follow
int[] userList = new int[0];
// Check size value (number of elements)
if (numElements > 0) {
userList = new int[numElements]; // Re-Declare array giving it a new size
} else {
System.out.println("This array size cannot be less than 1");
}
System.out.println();
for(int i = 0; i < numElements; ++i) {
System.out.println("Input number at position " + i);
userList[i] = scnr.nextInt();
}
for (int i = userList.length -1; i >= 0; i--) {
//for (int i = userList.length-1; i >= 0; --i) {
System.out.print(userList[i] + " ");
}
System.out.println();
}
you have to create a list of size numElements,
int[] userList = new int[numElements];
for(i = 0;i < numElements; ++i) {
userList[i] = scnr.nextInt();
}
for (i = userList.length-1; i >= 0; --i) {
System.out.print(userList[i] + " ");
}
System.out.println();
Your code is fine but you just need to read the number of element before creating your userList :
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int numElements; // Number of integers in user's list
numElements = scnr.nextInt(); // Input begins with number of integers that follow
int[] userList = new int[numElements]; // List of numElement integers specified by the user
int i;
for (i = 0; i < numElements; ++i) {
userList[i] = scnr.nextInt();
}
for (i = userList.length - 1; i >= 0; --i) {
System.out.print(userList[i] + " ");
}
System.out.println();
}
}
Your array size is 20 and your are trying to print whole array in reverse order which includes unfilled indexes also. so try to make array size as numElements and print it will work
In order to reduce the lines of code and use streams, the following code would work -
Accept input numbers and store them in the array of size numElements. Use "ArrayUtils" to reverse the array. Details about the reverse() can be referred here.
Scanner scnr = new Scanner(System.in);
int numElements;
numElements = scnr.nextInt();
int[] userList = new int[numElements];
for (int i = 0; i < numElements; ++i)
userList[i] = scnr.nextInt();
ArrayUtils.reverse(userList);
Arrays.stream(userList).forEach(number -> System.out.print(number + " "));
hi guys i've had some help with this program today, basically what i want is for an array of 1 - 200 to be held, then the user inputs a number between 1 and 200.
The ramaning numbers are then added together and the answer outputted.
e.g. user enters 100, numbers from 100-200 are then added together and answer is output.
With the code i have so far it is always outputting 0 as the answer. Any ideas?
thanks.
//Importing scanner
import java.util.Scanner;
//Class name
class programfive{
//Main method
public static void main (String[]args){
//declaring and inizialising scanner
Scanner input = new Scanner (System.in);
//Declaring and inizialising variables
int userInput = 0;
int sum = 0;
//Array initializer
int array[] = new int [201];
//Prompt for user input
System.out.print("Please enter a value between 1 and 200: ");
userInput = input.nextInt();
//For loop - starts at number user inputted, stops when reaches 200, increments by 1.
for (int i = userInput; i<=200; i++)
{
sum += array[i];
}
System.out.println(sum);
}//End of main method
}//End of class
Because you haven't put anything in your array, it contains the default int value at each index, and that is 0 .
You have to fill it with the values you want, so that array[0] contains 0, array[1] contains 1, etc..
int array[] = new int [201];
for(int i=0; i<array.length;i++)
array[i] = i;
Also, you could get rid of the array and get the same result :
for (int i = userInput; i<=200; i++)
{
sum += i;
}
you need to initialize the array first, or changing the sum loop to:
for (int i = userInput; i<=200; i++)
{
sum += i;
}
Untested but should work:
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
int userInput = 0;
int sum = 0;
System.out.print("Please enter a value between 1 and 200: ");
userInput = input.nextInt();
for (int i = userInput; i<=200; i++)
sum += i
userInput.close();
System.out.println(sum);
}
you forgot to populate your array with numbers currently all of your array elements are pointing to the default value of 0.
add this line of code after the array declaration and your good to go:
for(int i=0;i<array.length;i++)
array[i]=i;
System.out.println("Enter five numbers: ");
Scanner scanner = new Scanner(System.in);
int[] array = new int [5] ;
for (int i =0; i < array.length; i++){
array[i] = scanner.nextInt();
}
int sum = 0;
for (int i : array){
sum = sum +i;
}
System.out.println(sum);
So I have to write a program that reads an arbitrary number of integers that are in the range 0 to 50 inclusive and counts how many occurrences of each are entered. Indicate the end of the input by a value outside of the range. After all input has been processed., print all of the values (with the number of occurrences) that were entered one or more time.
public class problem
{
public static void main(String[] args)
{
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int userInput = 0;
ArrayList<Integer> myList = new ArrayList<Integer>();
int index = -1;
for (int num = 0; num <= userInput ; num++)
{
System.out.println("Please enter a random number between 0 and 50, enter a negative number to end input: ");
num--;
if(userInput >= 0 || userInput <= 50)
{
userInput++;
userInput = scan.nextInt();
index++;
myList.add(userInput);
}
if (userInput < 0 || userInput > 50)
{
myList.remove(index);
index--;
break;
}
}
for (int num: myList)
System.out.print(num + " ");
}
}
This is what I have so far, but I am stuck as to how to count each integer occurrence in myList.
If I understand your question correctly, you can do something like this
public static void main(String[] args) {
int max = 200; // this is just for test
HashMap<Integer, Integer> counter = new HashMap<>();
for(int i = 0;i < max; i++){
int value = (int) (Math.random() * 50); // generate random numbers
if(counter.containsKey(value)){ // if map contains value, increment it's count
counter.put(value, counter.get(value)+1);
}else{
counter.put(value, 1); //put it and start from 1
}
}
System.out.println(counter);
}
}
I need help figuring out how to get the user to input a number of integers no more than 10, and then add them to an array and print them out from the array. The code I have below, when run, asks the user for the integers and then runs forever and doesn't work. What am I doing wrong?
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // create a new scanner
System.out.print("Enter integers between 1 and 100\n ");
int[] nextNumber = new int[10];
int i = 0;
int number = input.nextInt();
while (i < nextNumber.length){
i++;
nextNumber[i] = number;
number = input.nextInt();
}
int a = 0;
while (a < nextNumber.length){
a++;
System.out.println(nextNumber[a]);
}
Seems to me like you increment your index too fast. You should increment your index variables at the end of your loops, not the beginning.
I would suggest you use for loops instead since they are designed for that:
Scanner input = new Scanner(System.in); // create a new scanner
System.out.print("Enter integers between 1 and 100\n ");
int[] nextNumber = new int[10];
for (int i = 0; i < nextNumber.length; i++){
nextNumber[i] = input.nextInt();
}
for (int a = 0; a < nextNumber.length; a++){
System.out.println(nextNumber[1]);
}
Also, although I did not change it in the code, it seems like your last line should be:
System.out.println(nextNumber[a]);
Increment the array index after the values have been assigned to the arrays
while (i < nextNumber.length) {
number = input.nextInt();
nextNumber[i] = number;
i++;
}
The same applys to the second loop
while (a < nextNumber.length) {
System.out.println(nextNumber[a]);
a++;
}
Problem 1
Change
int i = 0;
int number = input.nextInt();
while (i < nextNumber.length){
i++; //here is one problem. you not assigning the value to nextNumber[0].
nextNumber[i] = number;
number = input.nextInt();
}
to
int i = 0;
while (i < nextNumber.length){
number = input.nextInt();
nextNumber[i] = number;
i++;
}
Problem 2
change
int a = 0;
while (a < nextNumber.length){
a++; //here is one problem ..You never get nextNumber[0] value
System.out.println(nextNumber[a]);
}
to
int a = 0;
while (a < nextNumber.length){
System.out.println(nextNumber[a]);
a++;
}
You can easily do this as follows. Better use for loop since you know the maximum number of iterations.
Scanner input = new Scanner(System.in); // create a new scanner
System.out.print("Enter integers between 1 and 100\n ");
int[] nextNumber = new int[10];
int i = 0;
while (i < nextNumber.length) nextNumber[i++] = input.nextInt();
int a = 0;
while (a < nextNumber.length) System.out.println(nextNumber[a++]);
I am trying to create a program that sorts user inputted integers from greatest to least. Also I need to find a way to print the maximum and minimum numbers. The code was sorting fine when I had defined values but now that I have switched it to user input it sends back "0"s for some reason. This is my code
import java.util.Scanner;
public class SortInteger {
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i>number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length-1; i++){ //outputs the array to user
System.out.println(number[i]);
}
}
}
you have taken only one number
int num = input.nextInt();
and you are using it for array size :
int number [] = new int [num];
but in rest of the code you haven't taken any input so your array is empty.
Code::
import java.util.*;
class test{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int number [] = {num1,num2,num3}; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i<number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length; i++){ //outputs the array to user
System.out.println(number[i]);
}
}}
Output::
Please input three numbers
1
5
4
1
4
5
you are only initializing your array. you never initialized your array with elements, thus your array elements get default values.
System.out.println("Please enter size");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
for(int i=0; i<number.length; i++){
System.out.println("Please enter element at index " + i);
number[i] = input.nextInt()
}
As others pointed out you need to populate your array with multiple values, currently you are requesting only one int.
Also, are you sure that works? Should't your first for loop read:
for(int i = 0; i<number.length-1; i++ )
Instead of:
for(int i = 0; i>number.length-1; i++ )
On a side note, it looks to me that your sorting algorithm is O(n2) you may want to look into mergesort and quicksort.