Can't find array value - java

Can someone help me with this problem.
I have been given to do some coding exercise
I need to do search Array problem
Below is the output that i want :
I have a problem where when I put the correct value it will not come out the output I want instead it will come out the output "Player not Found" so how to solve this. I feel like I missed something.
Here my code:
import java.util.Scanner;
public class Main{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println(" Welcome to VictoRoar Information System " );
System.out.println( " ********************");
System.out.print(" Enter n , number of player: ");
int n = sc.nextInt();
//declare,initialize array
String [] name = new String[n];
double [] height = new double[n];
sc.nextLine();
//put input in the array
for (int i=0; i<n;i++)
{
System.out.print(" Enter player's name :" );
name[i] = sc.nextLine();
System.out.print(" Enter player's height (cm) :" );
height[i] = sc.nextLine();
}
//search array
System.out.print(" Write the player height that you want to know : ");
double findheight=sc.nextDouble();
boolean noheight = false;
for(int i = 0; i<n; i++)
{
if (n == height[i])
{
noheight = true;
System.out.println("Player name "+ name[i] + " with height " + height[i]+ " present at index " +i);
}
}
if (noheight == false )
System.out.println("Player not found");
System.out.println("**********************");
}
}
I hope you guys can help me to solve this problem.

You have to use the findheight instead of n variable in your if (n == height[i]) condition:
try this it's work :
import java.util.Scanner;
public class Main{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
System.out.println(" Welcome to VictoRoar Information System " );
System.out.println( " ********************");
System.out.print(" Enter n , number of player: ");
int n = sc.nextInt();
//declare,initialize array
String [] name = new String[n];
double [] height = new double[n];
sc.nextLine();
//put input in the array
for (int i=0; i<n;i++)
{
System.out.print(" Enter player's name :" );
name[i] = sc.nextLine();
System.out.print(" Enter player's height (cm) :" );
height[i] = Double.valueOf(sc.nextLine());
}
//search array
System.out.print(" Write the player height that you want to know : ");
double findheight=sc.nextDouble();
boolean noheight = false;
for(int i = 0; i<n; i++)
{
if (findheight == height[i])
{
noheight = true;
System.out.println("Player name "+ name[i] + " with height " + height[i]+ " present at index " +i);
}
}
if (noheight == false )
System.out.println("Player not found");
System.out.println("**********************");
}
}
result:
Welcome to VictoRoar Information System
********************
Enter n , number of player: 2
Enter player's name :Alex
Enter player's height (cm) :120
Enter player's name :David
Enter player's height (cm) :122
Write the player height that you want to know : 120
Player name Alex with height 120.0 present at index 0
**********************

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 do not understand why array[0] and [1] became null

import java.util.Scanner;
public class NoteIt {
public static void main(String[]args) {
Scanner s = new Scanner(System.in);
int Answer;
int i=2;
System.out.print("\nPlease Enter your Name: ");
String Name = s.nextLine();
System.out.println("Welcome to Note-It "+Name+", We hope you'll enjoy our application. ");
String[][] Main = new String[2][2];
Main[0][0]="Create new Note";
Main[1][0]="View My Notes";
while(true) {
System.out.println("\nPlease select what to do: \n");
for (int n = 0; n < 2; n++) {
System.out.println((n + 1) + ") " + Main[n][0]);
}
System.out.print("\nPlease enter your response: ");
Answer = s.nextInt();
if (Answer == 1) {
i++;
Main = new String[i][2];
System.out.print("\nTitle: ");
Main[i - 1][0] = s.next();
System.out.print("Body: ");
Main[i - 1][1] = s.next();
} else if (Answer == 2) {
for (int k = 2; k < i; k++) {
System.out.println(k - 1 + Main[k][0]);
}
}
}
}
}
why did array main become null after one while loop?? When I run the program once everything is perfect, but in the second loop "create new note" and "view your notes", both become null.
Main = new String[i][2];
Here you created a new Array
If you want to Resize the array you have 2 options
Either use java.util.ArrayList or java.util.Vector instead of native array
Or Create a new array and copy old data into new array
Try this code made some minor adjustments
import java.util.Scanner;
public class Main {
public static void main(String[]args) {
Scanner s = new Scanner(System.in);
int Answer;
int i=1;
System.out.print("\nPlease Enter your Name: ");
String Name = s.nextLine();
System.out.println("Welcome to Note-It "+Name+", We hope you'll enjoy our application. ");
String[][] Main = new String[10][2];
//String[] Main1 = new String[2];
Main[0][0]="Create new Note";
Main[0][1]="View My Notes";
/**for( int j=0;j<2;j++ )
Main[j]= new String[2];*/
while(true) {
System.out.println("\nPlease select what to do: \n");
for (int n = 0; n < 2; n++) {
System.out.println((n + 1) + ") " + Main[0][n]);
}
System.out.print("\nPlease enter your response: ");
Answer = s.nextInt();
s.nextLine();
if (Answer == 1) {
i++;
System.out.print("\nTitle: ");
Main[i - 1][0] = s.nextLine();
System.out.print("Body: ");
Main[i - 1][1] = s.nextLine();
} else if (Answer == 2) {
for (int k = 1; k <i; k++) {
System.out.println(1 + Main[k][0]);
}
}
}
}
}
There might be some elements not upto your requirement please change them according to your preferences. Also have fixed the skipping of body.
First, check how the 2D array works. You have declared new String[2][2]. Then it works [0][0], [0][1],[1][0],[1][1].
Then check with you value assigning points.

Have to design a lottery program that using Arrays and Arraylists that print results for the whole year

So I have to write a program that mimics Megabucks lottery game.
It should either let the user enter 6 numbers OR automatically pick 6 numbers and 1 bonus number. The troubling part is that I have to design it in a way that it will produce 104 drawings(2 drawings a week for 52 weeks). I can't seem to write the code in a way that the 104 drawings are all randomized.
Here's the code I have for drawing the 6 winning numbers and 1 bonus number:
import java.util.*;
public class oops
{
public static void main(String[] args)
{
Random randomGenerator = new Random();
int bonus = randomGenerator.nextInt(42)+1;
List <Integer> winningNumbers = new ArrayList<Integer>(6);
for(int i=0; i < 6; i++)
{
winningNumbers.add(randomGenerator.nextInt(42)+1);
}
System.out.println();
System.out.println("------------------------------------------------------------");
System.out.println(" Winning numbers: "+ Arrays.toString(winningNumbers.toArray()) +" Bonus Number:" + "[" + bonus + "]");
System.out.println("------------------------------------------------------------");
}
}
And the output for that part is:
As for my code for the rest of the program:
public void getPlayNum()
{
Scanner scan = new Scanner(System.in);
System.out.println(" Enter 1 for manual picking or 2 for automatic: ");
int input = scan.nextInt();
List <Integer> playNumbers = new ArrayList<Integer>();
if(input == 1) //let user pick out their own play numbers
{
for(int i =0; i< 6; i++)
{
System.out.println("Enter number 1 and 42 (no duplicates): ");
int userNum = scan.nextInt();
if(playNumbers.contains(userNum))
{
System.out.println();
System.out.println("*** DUPLICATE FOUND! Please enter a non-repeating digit between 1 and 42 ***");
i--;
System.out.println();
}else if (userNum > 42 || userNum < 1)
{
System.out.println();
System.out.println("*** OUT OF RANGE! Please enter a non-repeating digit between 1 and 42 ***");
i--;
System.out.println();
}else{
playNumbers.add(userNum);
System.out.println("Here are your numbers: ");
System.out.println(Arrays.toString(playNumbers.toArray()));
}
}
}else{
Random randomGenerator = new Random();
for (int index = 0; index < 6; index++)
{
playNumbers.add(randomGenerator.nextInt(42));
}
System.out.println();
System.out.println("Here are the numbers randomly generated for you: ");
System.out.println("------------------------");
System.out.println(Arrays.toString(playNumbers.toArray()));
System.out.println("------------------------");
System.out.println();
}
}
Nothing is properly formatted but I need to fix the important parts first. Thanks for any tips at all!
It is as easy as #Gendarme mentioned:
for(int draw = 0; draw < 104; draw++) {
int bonus = randomGenerator.nextInt(42)+1;
List <Integer> winningNumbers = new ArrayList<Integer>(6);
for(int i=0; i < 6; i++)
{
winningNumbers.add(randomGenerator.nextInt(42)+1);
}
System.out.println();
System.out.println("------------------------------------------------------------");
System.out.println(" Winning numbers: "+ Arrays.toString(winningNumbers.toArray()) +" Bonus Number:" + "[" + bonus + "]");
System.out.println("------------------------------------------------------------");
}

I don't understand how to take my input string and print it out with right-alignment

I'm taking a string input and prompt the user for score values, which the user can input up to 5 scores and no less than 1. I don't understand how to take that string and print it out so there are no more commas and they are right aligned.
This is what I have so far:
//user inputs for number of students
numStudents = UtilsKS.readInt("Enter number of students: ", false);
//while loop for correct input of students
while (numStudents <= 0 || numStudents > 12) {
System.out.print("ERROR: must be 1-12, ");
numStudents = UtilsKS.readInt("Enter number of students: ", false);
}
// user input for student score using a for loop
for (int i = 0; i < numStudents; i++) {
stuScores = UtilsKS.readString("Enter comma-separated test score for student " + (i+1) + ": ", false);
}
//initializing testscore to = what scores are inputed per student
for (int t=0; t<numStudents; t++) {
testScores[t] = stuScores;
}
// setting up turning string into separate arrays and trimming them
array1 = stuScores.split(",");
for (int i=0; i<array1.length; i++) {
score[i] = Integer.parseInt(array1[i].trim());
}
//outputs
System.out.println( String.format("%10s", header));
System.out.println( String.format("%10.2f", score));
My main question is how do I take the inputs and properly format them to print?

Printing Two Dimensional Array

I am working in a small task that allow the user to enter the regions of any country and store them in one array. Also, each time he enters a region, the system will ask him to enter the neighbours of that entered region and store these neighbours.
I did the whole task but I have small two problems:
when I run the code, the program does not ask me to enter the name of the first region
(This is happened only to the first region)
I could not be able to print each region and its neighbours like the following format:
Region A: neighbour1 neighbour2
Region B: neighbour1 neighbour2
and so on.
My code is the following:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Test6{
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the number of regions: ");
int REGION_COUNT = kb.nextInt();
String[][] regions = new String[REGION_COUNT][2];
for (int r = 0; r < regions.length; r++) {
System.out.print("Please enter the name of region #" + (r+1) + ": ");
String region = kb.nextLine();
System.out.print("How many neighbors for region #" + (r+1) + ": ");
if (kb.hasNextInt()) {
int size = kb.nextInt();
regions[r] = new String[size];
kb.nextLine();
for (int n = 0; n < size; n++) {
System.out.print("Please enter the neighbour #"
+ (n) + ": ");
regions[r][n] = kb.nextLine();
}
} else System.exit(0);
}
for(int i=0; i<REGION_COUNT; i++){
for(int k=0; k<2; k++){
System.out.println(regions[i][k]);
}
}
}
}
Thanks everybody for your immediate helps. But let me explain to you what I want in more details.
First of all, I need to use the two dimensional array.
Secondly, my problem now is just with the printing of the result. I want to print the results like the following format:
> RegionA : its neighbours
For example, let us take USA
> Washington D.C: Texas, Florida, Oregon
--------------------------------------------------------------------------
Dear ykartal,
I used your program and it gave me the following:
when I run the code, the program
does not ask me to enter the name of
the first region (This is happened
only to the first region)
Because you are using nextLine, program take your first edit for nextLine use next insteadof nextline
could not be able to print each region and
its neighbours like the following
format: Region A: neighbour1
neighbour2 Region B: neighbour1
neighbour2 and so on.
A and B is the name or Alphabetic order of regions? If alphabetics 65 is the aSCII equalence of 'A' and 66 is 'B' ... So using (char)65 write A. Otherwise put region names instead of (char)65+i
Try this;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Test6{
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the number of regions: ");
int REGION_COUNT = kb.nextInt();
String[] regionNames = new String[REGION_COUNT];
String[][] regions = new String[REGION_COUNT][2];
for (int r = 0; r < regions.length; r++) {
System.out.print("Please enter the name of region #" + (r + 1)
+ ": ");
regionNames[r] = kb.next();
System.out
.print("How many neighbors for region #" + (r + 1) + ": ");
if (kb.hasNextInt()) {
int size = kb.nextInt();
regions[r] = new String[size];
for (int n = 0; n < size; n++) {
System.out.print("Please enter the neighbour #" + (n)
+ ": ");
regions[r][n] = kb.next();
}
} else
System.exit(0);
}
for (int i = 0; i < REGION_COUNT; i++) {
System.out.print(regionNames[i] +": ");
for (int k = 0; k < 2; k++) {
System.out.print(regions[i][k]+", ");
}
System.out.println();
}
}
}
Output;
Please enter the number of regions: 2
Please enter the name of region #1: aaa
How many neighbors for region #1: 1
Please enter the neighbour #0: a1
Please enter the name of region #2: bbb
How many neighbors for region #2: 2
Please enter the neighbour #0: b1
Please enter the neighbour #1: b2
aaa: a1
bbb: b1 b2
Note: This is not a good code, you must handle if user enter alfanumeric characters instead of numbers where you expected user will enter numeric values.
UPDATE:
This is what you want:
for (int i = 0; i < region.length; i++){
StringBuilder sb = new StringBuilder();
sb.append(region[i] + ": ");
for (int i2 = 0; i2 < neighbor.length; i2++){
if (i2 != 0 && i2 != neighbor.length-1){
sb.append(", " + neighbor[i2]);
}else{
sb.append(neighbor);
}
}
System.out.println(sb.toString());
}
I think it's going to be easier for you if you manipulate your information in a Map.
Try this
Map<String, List<String>> mapRegionNeighbor = new HashMap<String, List<String>>();
System.out.println("What region would you like to see?");
String regionName = scanner.nextLine();
List<String> neighborList = mapRegionNeighbor.get(regionName);
for(String neighbor : neighborList){
System.out.println(regionName + ": " + neighbor);
}
So, basically, if you want to add information to regions:
if it's a new region do this
mapRegionNeighbor.put(regionName, new ArrayList<String>);
if region has got a list of neighbor already, you'll do this to add a new neighbor:
List<String> neighborList = mapRegionNeighbor.get(regionName);
neighborList.add(neighborName);
mapRegionNeighbor.put(regionName, neighborList);
This 3 lines above will just update your region.
To run thru all values printing there neighbors, do something like this:
Iterator it = countedWords.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
for (String neighbor : pairs.getValue()){
System.out.println(pairs.getKey() + ": " + neighbor);
}
}

Categories

Resources