Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I tried to print my array using to Arrays.toString(array)); but still it gave me errors... And also ELEMENT IS FOUND is false statement but it mixes with the true statement when i tried to search an element in my array,
for example.....
I searched 4 in my array: 4 , 2, 3 ,5
but ELEMENT IS FOUND is still showing.
import java.util.Scanner;
public class linee {
public static void main(String[] args) {
int String;
int value;
Scanner in = new Scanner(System.in);
System.out.print("Input the Number of Element: ");
String n = in.nextLine();
int num = Integer.parseInt(n);
String array[] = new String[num];
for (int i = 0; i < array.length; i++) {
System.out.print("Input the Number at array index " + i + ": ");
array[i] = in.nextLine();
}
Linear(array);
System.out.print("\nDo you want to continue? YES = 1, NO = 2: ");
value = in.nextInt();
if (value == 1) {
main(args);
} else if (value == 2) {
System.out.println("\nThank you for using the program.");
}
}
public static void Linear(String[] array) {
boolean flag = false;
String key = "";
int index = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number that you want to search: ");
key = in.nextLine();
for (int i = 0; i < array.length; i++) {
if (array[i].equals(key)) {
flag = true;
index = i;
}
}
if (flag == true) {
System.out.println("Elements: " + Arrays.toString(array));
System.out.println("ELEMENT IS FOUND AT INDEX " + index);
} else {
System.out.println("ELEMENT IS NOT FOUND");
}
}
}
From the Object.toString(Object[] a) spec:
Returns a string representation of the contents of the specified
array. If the array contains other arrays as elements, they are
converted to strings by the Object.toString() method inherited from
Object, which describes their identities rather than their contents.
That is, you may want to print your elements in another way. An option is:
System.out.println("Elements: ");
for(String str: array) {
System.out.println(str);
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a List of Array values
String[] names = {"michel","john","mr x","text"};
int[] num ={1,2,3,4};
I asked the User to Enter the names in the array and want to dispaly the num of tht array names also we want to check whether the entered array is in the array if not then we want to send error msg
for that i created a boolean = false and check the condition in loop and i execute
System.out.println("Enter the Name To get Numbers");
Scanner scanner = new Scanner(System.in);
String name=scanner.next();
boolean check =false;
int in = 0;
for (int i=0; i <names.length; i++)
{
if (name.contains(names[i]))
{
check = true;
in = i;
}
if (name.equals(names[i]))
{
System.out.println(num[i]);
}else
{
System.out.println(" Choose the name in the array ");
}
}
But it execute the error in the loop till the no of array list
First search in the array with for loop exists or not in the array if exist then do check = true and print the number.
And after the loop check is not in the array then print the error message.
Scanner scanner = new Scanner(System.in);
String name=scanner.next();
boolean check =false;
for (int i=0; i <names.length; i++)
{
if (name.equals(names[i]))
{
check = true; // if match with any array element
System.out.println(num[i]);
}
}
// if check is false means no element match in array, print err msg
if(!check)
{
System.out.println(" Choose the name in the array ");
}
You set the values for check and in variables, but you never use them. You also print "Choose the name in the array" inside the loop for every non-matching value, but you probably only want to do this once, when the loop is finished, in case you didn't find anything.
This is how you could rewrite your loop to get what you want:
boolean check = false;
for (int i = 0; i < names.length; i++) {
if (name.equals(names[i])) {
check = true;
System.out.println(num[i]);
}
}
if (!check) {
System.out.println(" Choose the name in the array ");
}
Actually, if you want to look up values by names, a HashMap would probably be a better choice than iterating through an array:
Map<String, Integer> map = new HashMap<>();
map.put("michel", 1);
map.put("john", 2);
map.put("mr x", 3);
map.put("text", 4);
Integer in = map.get(name);
if (in == null) {
System.out.println(" Choose the name in the array ");
}
else {
System.out.println(in);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to ask the user to enter up to 10 valid names. In my code I have to have a array with all the full names. Inside that array the full names are a array with the names separated. For each full name - To be valid needs to have at least two names with at least 4 characters. If the user introduces 5 valid full names could digit "fim" to end the program. The max is 10 valid full names, if the user reaches the 10 valid full names the program should end. These code isn't correct because it doesnt end when it reaches 10 valid full names or if the user digits end after 5 or more valid full names.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter up to 10 full names with up to 120 characters and at least two names with at least 4 characters: ");
String[] fullName= new String[10];
String[] separatedName;
String name;
int i = 0;
do {
name = keyboard.nextLine();
fullName[i]=name;
i++;
separatedName = name.split(" ");
//System.out.println(Arrays.toString(separatedName));
int l = 0;
for(int n = 0; n < separatedName .length; n++){
if(separatedName [n].length() >= 4 ) {
l++;
}
}
if(l >= 2 && name.length() <= 120 || name.equalsIgnoreCase("fim") ) {
//System.out.println("Valid name.");
}
else {System.out.println("'" +name+ "'" + " is an invalid name");
}
}
while(i<10);
keyboard.close();
}
Still Not sure what you are trying to do. Try this and this should solve your problem
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter up to 10 full names with up to 120 characters and at least two names with at least 4 characters: ");
String[] fullName= new String[10];
String[] separatedName;
String name;
int i = 0;
int validCount=0;
do {
name = keyboard.nextLine();
fullName[i]=name;
i++;
separatedName = name.split(" ");
//System.out.println(Arrays.toString(separatedName));
int l = 0;
for(int n = 0; n < separatedName .length; n++){
if(separatedName [n].length() >= 4 ) {
l++;
}
}
if(l >= 2 && name.length() <= 120 ) {
validCount++;
//System.out.println("Valid name.");
}
else {System.out.println("'" +name+ "'" + " is an invalid name");
}
if(validCount>=5 || name.equalsIgnoreCase("fim")) {
break;
}
}
while(i<10);
keyboard.close();
}
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need to test for consecutive numbers in any order. My program seems to work ok when I type in numbers in order like 1,2,3 or 8,3,3, but I need this to read the numbers in any order, for example 3,2,4 should return true.
Examples that should return true:
(1,2,3)
(3,2,4)
(-10,-8,-9)
Examples that should return false:
(3,5,7)
(1,2,2)
(7,7,9)
.
import java.util.*;
public class Consecutive {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter three numbers");
String numbers = console.nextLine();
System.out.println("The numbers (" + numbers + ") is '" + consecutive(numbers) + "'");
}
private static boolean consecutive(String str) {
char c = str.charAt(0);
for (int cc = 1; cc < str.length(); cc++)
if ((c + 1) != str.charAt(cc))
return false;
else
c++;
return true;
}
}
Based on a few assumptions (you want them in any order, they will always be comma-delimited), you will need to check for consecutivity on a sorted array with some like the follows:
String[] split = str.split(",");
int[] numbers = new int[split.length];
for (int i = 0; i < split.length; i++)
numbers[i] = Integer.parseInt(split[i]);
Arrays.sort(numbers);
(...now check for consecutivity...)
Try this approach:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Consecutive {
private ArrayList<Integer> numberList;
public Consecutive() {
numberList = new ArrayList<Integer>();
fetchInput();
sortNumberList();
System.out.println(isConsecutive());
}
private void fetchInput() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any amount of numbers"
+ " separated by space.\n" + "Exit by typing any letter and"
+ " pressing Enter key.");
while (scanner.hasNextInt()) {
numberList.add(scanner.nextInt());
}
scanner.close();
}
// Sort the list in ascending order
private void sortNumberList() {
Collections.sort(numberList);
}
private boolean isConsecutive() {
// Loop through the sorted number list
for (int index = 0, length = numberList.size() - 1; index < length; index++) {
// Check if the two adjacent numbers are differing by the value 1 or
// not.
if (numberList.get(index + 1) - numberList.get(index) != 1)
return false;
}
return true;
}
public static void main(String[] args) {
new Consecutive();
}
}
First fetch the input, and store the input in an Array. Sort the array, and then check if the sorted array has any adjacent elements which don't differ by the value of 1.
If there is any such adjacent pair, then that means that the elements that were entered weren't consecutive.
Hope it helps.
Using the sort method suggested by stendika; first convert to an array, removing all the commas, then sort and compare elements.
import java.util.*;
public class Consecutive{
public static void main (String [] args){
Scanner console= new Scanner(System.in);
System.out.println("Enter three numbers");
String numbers = console.nextLine();
System.out.println( "The numbers (" + numbers + ") is '" + consecutive( numbers ) + "'" );
}//end of main
private static boolean consecutive(String str) {
String[] numbers = str.split(",");
Arrays.sort(numbers);
for (int index = 0; index < numbers.length-1; index++){
if (Integer.parseInt(numbers[index]) > Integer.parseInt(numbers[index+1])){
return false;
}
}
return true;
}//end of consecutive method
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hi there I am trying to create an array of records in java in which you have to enter 3 details, the name of a town, the population and the county in which is resides. Before then outputting all the data on a county which you have asked for. I was wondering if anyone could show me why a null.point.exception occurs if I enter the population of a town when does not occur when i enter another one.
import java.util.*;
public class CathedralTowns
{
public static String name;
String population;
String county;
public static int count = 0;
public static int continuation = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int loop1 = 0;
while (loop1 <= 0) {
System.out.println("Please enter the name of the town. ('no' to end)");
String nameEntered = input.nextLine();
System.out.println("Please enter the county in which the town resides. ('no' to end)");
String countyEntered = input.nextLine();
System.out.println("Please enter the population of the town. ('no' to end)");
String populationEntered = input.nextLine();
if (nameEntered.equals("no") || populationEntered.equals("no") || countyEntered.equals("no") ) {
loop1 = 5;
System.out.println("Thank you for entering your county.");
continuation = 1;
}
WorkingDemCathedrals(nameEntered, populationEntered, countyEntered);
}
}
public static void WorkingDemCathedrals(String nameEntered, String populationEntered, String countyEntered) {
Scanner input = new Scanner(System.in);
CathedralTowns[] allTowns = new CathedralTowns[50];
allTowns[count] = new CathedralTowns();
int loop2 = 0;
int loop3 = 0;
while (loop2 == 0){
allTowns[count].name = nameEntered;
allTowns[count].population = populationEntered; //the error relates back to here according to bluej
allTowns[count].county = countyEntered;
if (continuation == 1) {
loop2 = 1;
System.out.println("please enter the name of a county for which you wish to know the details.");
String countyOfChoice = input.nextLine();
while (loop3 > 0){
if ((allTowns[loop3].county).equals(countyOfChoice)){
System.out.println(allTowns[loop3].name);
System.out.println(allTowns[loop3].population);
loop3 = -2;
}
loop3 = loop3 +1;
}
}
count = count + 1;
}
}
}
Elements in an Object array are null by default. Initialialise the elements prior to attempting to access them
for (int i=0; i < allTowns.length; i++) {
allTowns[i] = new CathedralTowns();
}
This lines is very suspicious
allTowns[count] = new CathedralTowns();
You allocate only one object in the array while you have a line before allocated an array of the length 50.
CathedralTowns[] allTowns = new CathedralTowns[50];
Not to mention that it is prone to ArrayIndexOutOfBoundsException if count is equal or more that 50
Then you start to loop and increment count and that's where it happens!
your should loop over the entire array and allocate an object in each slot.
The NullPointerException occurs at "population" and not at "name" is because the "name" field is static, whereas the "population" is non-static.
Also the allocation of the array of CathedralTowns has to be done as per the first answer.
The while (loop2 == 0) could end up in a infinite loop. There is no end condition for this while loop, if the user wants to enter details of more than one county.