Output is not showing for second array in Java - java

I'm a beginner in Java programming and I created a program that accepts 10 numbers as input from users and prints them. The first section is using for loop and the second section is using while loop. The first section works properly and the second section isn't displaying output. Could anybody help me?
import java.util.Scanner;
public class ArrayOfTenElements {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numArray1[] = new int [10];
int numArray2[] = new int [10];
int i;
//First Section
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
for(i=0;i<10;i++) {
numArray1[i] = scanner.nextInt();
}
System.out.println("The entered numbers are: ");
for(i=0;i<10;i++) {
System.out.print(numArray1[i] + " ");
}
//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
numArray2[j] = scanner.nextInt();
j++;
}
System.out.println("The entered numbers are: ");
while(j<10) {
System.out.print(numArray2[j] + " ");
j++;
}
scanner.close();
}
}

You are not resetting variable j back to 0 after the 1st loop. so the 2nd loop starts with a value of 10 for j, and hence, while loop is not executed.
//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
numArray2[j] = scanner.nextInt();
j++;
}
// add this
j = 0;
System.out.println("The entered numbers are: ");
while(j<10) {
System.out.print(numArray2[j] + " ");
j++;
}

When you use last for loop j value is 10 in the beginning of that loop
as you declare j out of the scope.So you should declare new variable
and replace while loop from it.The other thing is you should use for
loop to showing array2.Normally we use while loops for only when we
not knowing about end time.So we use for loop for this.
//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
numArray2[j] = scanner.nextInt();
j++;
}
System.out.println("The entered numbers are: ");
for(i=0;i<10;i++) {
System.out.print(numArray2[i] + " ");
}

Related

The task is to write a java program to test if an array contains a specific value in java

I got confused and didn't know what to add or change the loops.
Can someone please help me and tell me what I should do in order to run my code? It would be a big help to me. I'm only a beginner in Java...
**here's my code: **
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
System.out.println("Enter "+ size + " values: \n");
for(i=0; i < num.length; i++){
x = input.nextInt();
num[i]=x;
if ( num [i] == x );
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
if ( num[i] == search){
System.out.println (search + " is found in the array!");
}
else{
System.out.println ("Your number is not in the array.");
}
}
}
The sample output of my task is (using scanner):
Input the size of the array: 4
Enter the values:
14
15
16
17
Enter the search value: 14
14 is found in your input array.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
// System.out.println("Enter "+ size + " values: \n");
for(i=0; i < num.length; i++){
System.out.println("Enter Number to add at index "+i+" : ");
x = input.nextInt();
num[i]=x;
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
boolean condition=false;
for(i=0; i < num.length; i++){
if ( num[i] == search){
condition=true;
break;
}
}
if(condition==true){
System.out.println("Number is Array!");
}
else{
System.out.println("Number is not in array");
}
}
your code is to be like this
there is logical error's in your code
to find an element you must traverse through array which can be achieved using loop so the last if else statement in your code must be in a loop
as due to the post increment in first loop after the completion of loop the value of i is one greater than last index of array so in if else statement at if ( num[i] == search) index is not found in array due to which it generates error.
for example I enter array size 3 and at num[0] I enter 1 at num[1] I enter 2 and at num[2] I enter 3 after the loop finishes the value of i become 3 when it come to conditional statement (if else) so it become if(num[3] == search ) but 3 index is not present in array so it generates error.
You need a loop to compare each element of the array with the search value.
boolean found = false;
for (int x : num)
if (x == search) {
found = true;
break;
}
System.out.println(found ? search + " is found in the array!" : "Your number is not in the array.");
Alternatively, with streams:
System.out.println(Arrays.stream(num).anyMatch(x -> x == search) ?
search + " is found in the array!" : "Your number is not in the array.");
Scanner input = new Scanner (System.in);
int i,x;
System.out.print("Input the size of the array: ");
int size = input.nextInt();
int num [] = new int [size]; /* declaration */
System.out.println("Enter "+ size + " values: \n");
for (i = 0; i < num.length; i++)
{
x = input.nextInt();
num[i] = x;
if (num[i] == x);
}
System.out.print("Enter the search value: ");
int search = input.nextInt();
boolean flag=false;
for( i=0;i<num.length;i++)
{
if (num[i] == search) {
flag = true;
System.out.println(num[i]+" is found in your input array");
break;
}
}
if (flag==false)
{
System.out.println("Your number is not in the array.");
}
}
[Screenshot][1]

i wrote a code using array and methods to display numbers from the smallest o the largest numbers

i wrote a code using array and method that allow the user to enter any number of numbers and
display the numbers sorted from the smallest number to the largest number however the program works but it doesn't show the numbers here is the code that i wrote
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers you want to enter? ");
int size = s.nextInt();
int i;
double[] numbers1 = new double[size];
System.out.println("Enter " + numbers1.length + " numbers: ");
getNumbers(numbers1);
double[] numbers2 = new double[numbers1.length];
for (i = 0; i < numbers1.length; i++) {
numbers2[i] = numbers1[i];
}
displayNumbers(numbers1);
System.out.println("The numbers after sorting are: ");
sortNumbers(numbers2);
displayNumbers(numbers2);
}
public static void getNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
}
}
public static void sortNumbers(double[] numbers) {
double temp;
double pass;
for (pass = 0; pass < numbers.length; pass++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
}
}
}
}
public static void displayNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
System.out.print(numbers + " ");
}
System.out.println();
}
}
Your displayNumbers() method is wrong. In the loop you wrote:
numbers[i] = s.nextDouble();
System.out.print(numbers + " " );
You're trying to read again 4 doubles (everytime you call that method) and you're printing the whole array (which doesn't do what you'd expect). What you probably want is this:
System.out.print(numbers[i] + " " );
Your code is inefficient and unclear.
You don't need to create a new Scanner everytime and also why instead of println the array with Arrays.toString(double[]).
You should also make more cleaner instructions and variable names.
Here is an example of how the code should be
public static void main(String[] args)
{
//create a new Scanner with a name that defines it
Scanner scanner = new Scanner(System.in);
//print your instructions
System.out.println("How many numbers would you like to sort?");
//print "> " to let the user to know he should be entering values
System.out.print("> ");
//read the number the user has entered which we will define as how many numbers he would enter next
int totalNumbers = scanner.nextInt();
//create a new array the size of the total numbers
double[] unsortedNumbers = new double[totalNumbers];
//tell the user to enter his unsorted numbers
System.out.println("Enter your unsorted numbers: ");
//loop totalNumbers times until the whole unsortedNumbers is full
for(int index = 0; index < totalNumbers; index++)
{
System.out.print("> ");
unsortedNumbers[index] = scanner.nextDouble();
}
//Print the numbers he entered
System.out.println("You entered: ");
//Arrays.toString prints the array in format [number, number, ...]
System.out.println(Arrays.toString(unsortedNumbers));
//sort the arrays with Arrays.sort which sorts in ascending numerical order
Arrays.sort(unsortedNumbers);
//Print the final result - sorted numbers
System.out.println("Sorted: " + Arrays.toString(unsortedNumbers));
}

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

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.

How can I print out the int values from the array?

The code below shows my progress, but I cannot print the numbers that were entered. I don't know where to put println("you entered the following numbers") in the loop so that it'll show up when the loop stops.
import java.util.Scanner;
public class aufgabe5 {
public static void main(String[] args) {
int x;
Scanner input = new Scanner(System.in);
System.out.println("How much numbers do you want to enter?");
x = input.nextInt();
int j = 1;
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[x];
for (int i = 0; i < numbers.length; i++) {
System.out.println("Enter the " + j++ + ". number:");
numbers[i] = scanner.nextInt();
}
System.out.println("You entered following numbers");
System.out.println(x);
}
}
Change x like
System.out.println(x);
to Arrays.toString(int[]) like
System.out.println(Arrays.toString(numbers));
Edit
To print the array reversed,
String str = Arrays.toString(numbers).replace(", ", " ,");
str = str.substring(1, str.length() - 1);
System.out.println(new StringBuilder(str).reverse().insert(0, "[")
.append("]"));
Intialize the String before the loop, then keep adding the values to it.
After the loop finishes you can print the whole thing.
String someVar="You entered following numbers: ";
for(int 1=0;i<array.length;i++)
{
someVar=someVar+numbers[i]+",";
}
System.out.println(someVar);

How can I limit the amount of strings printed on a single line

I want to be able to enter a string s and an integer n, then print the string s n times. I have done this, but I want there to be only 2 strings per line.
Here is my code so far:
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n; j++){
System.out.println(s);
}
if(n<0){
System.out.println("error: number must be positive");
}
}
Let's say the string was java and the number was 6. I need it to output:
java java
java java
java java
Use the modulo operator (%) to check if your loop index is evenly divisible by 2.
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=1; j<n+1; j++){
System.out.print(s);
if (j%2==0)
System.out.println("\n");
else
System.out.print(" ");
}
if(n<0){
System.out.println("error: number must be positive");
}
}
EDIT I changed the output to use print() instead of println() and added an empty space so the output is formatted as the example in your question. Also changed the for loop index to be one based so the mod works correctly.
Create a simple counter that counts to two inside your for loop. After it reaches two. Add a return character.
int count = 0;
for(int j=0; j<n; j++){
System.out.print(s);
count++;
if (count == 2) {
System.out.print("\n");
count = 0;
}
}
for(int j=0; j<n/2; j++){
System.out.println(s+" "+s);
}
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n; j++){
// modified
if(j%2==0 && j!=0){
System.out.println("\n");
}
System.out.print(s); // Should this not be print and not println
System.out.print(" ");
// end of modification
}
if(n<0){
System.out.println("error: number must be positive");
}
}
Try this code
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n/2; j++){
System.out.print(s + " " + s + "\n");
}
if(n%2 == 1){
System.out.print(s);
}
if(n<0){
System.out.println("error: number must be positive");
}
}

Categories

Resources