Enter Integers into an Array and terminating input before reaching limit - java

I'm doing a practice question in my textbook to add integers (negative and positive) into an array. I want the user to be able to terminate entering numbers into the array before it reaches the end [50].
This is what I've come up with:
The user enters the numbers which is stored in a string. If keepLooping is true and index < size of the array; it will parse token by token the string and place the number into the int array.
There must be an easier way to do this and I can't get my code working, any help would be much appreciated:
// Create Objects to use in program
Scanner keyboard = new Scanner(System.in);
int[] arrayOfNumbers = new int[50];
// Prompt for input
System.out.println("Enter upto 50 integers separated by a space.");
System.out.println("Type x to signal no more integers to enter.");
int index = 0;
boolean keepLooping = true;
while (index < arrayOfNumbers.length && keepLooping) {
String numToAdd = keyboard.nextLine();
if ( numToAdd.equals("x") || numToAdd.equals("X") ) {
keepLooping = false;
}
if ( !numToAdd.equals("x") || !numToAdd.equals("X") ) {
arrayOfNumbers[index] = Integer.parseInt(numToAdd);
}
}
// DEBUG, Print Array
for (int k=0; k < arrayOfNumbers.length; k++) {
System.out.println(arrayOfNumbers[k]);
}

You can simplify a little bit with a for loop, and break out of the loop to exit:
for (int index = 0; index < arrayOfNumbers.length; ++index) {
String numToAdd = keyboard.nextLine();
if (numToAdd.equals("x") || numToAdd.equals("X")) {
break;
}
arrayOfNumbers[index] = Integer.parseInt(numToAdd);
}

If you debugged your program step-by-step (e.g. Stepping with F6 in Eclipse), you would have noticed that index's value does not change. Quickest fix would be:
while (index < arrayOfNumbers.length && keepLooping) {
String numToAdd = keyboard.nextLine();
if ( numToAdd.equals("x") || numToAdd.equals("X") ) {
keepLooping = false;
}
if ( !numToAdd.equals("x") || !numToAdd.equals("X") ) {
arrayOfNumbers[index] = Integer.parseInt(numToAdd);
}
index++;
}
But of course, this solves just the filling-of-array issue. Then come the good practice in programming concerns, which are thoroughly covered by the rest of the answers.

int index = 0;
boolean keepLooping = true;
while (index < arrayOfNumbers.length && keepLooping) {
String numToAdd = keyboard.nextLine();
if (numToAdd.equalsIgnoreCase("x")) { // Use EqualsIgnoreCase to shorten it
keepLooping = false;
} else { // Use an else statement instead of evaluating the inverse
arrayOfNumbers[index] = Integer.parseInt(numToAdd);
}
index++; // Increment the index to avoid eternal loop and actually fill the array
}

Related

Increasing number sequence in a string java

Problem: Check if the numbers in the string are in increasing order.
Return:
True -> If numbers are in increasing order.
False -> If numbers are not in increasing order.
The String sequence are :
CASE 1 :1234 (Easy) 1 <2<3<4 TRUE
CASE 2 :9101112 (Medium) 9<10<11<12 TRUE
CASE 3 :9991000 (Hard) 999<1000 TRUE
CASE 4 :10203 (Easy) 1<02<03 FALSE
(numbers cannot have 0 separated).
*IMPORTANT : THERE IS NO SPACES IN STRING THAT HAVE NUMBERS"
My Sample Code:
// converting string into array of numbers
String[] str = s.split("");
int[] numbers = new int[str.length];
int i = 0;
for (String a : str) {
numbers[i] = Integer.parseInt(a.trim());
i++;
}
for(int j=0;j<str.length;j++)
System.out.print(numbers[j]+" ");
//to verify whether they differ by 1 or not
int flag=0;
for(int j=0;j<numbers.length-1;j++){
int result=Integer.parseInt(numbers[j]+""+numbers[j+1]) ;
if(numbers[j]>=0 && numbers[j]<=8 && numbers[j+1]==numbers[j]+1){
flag=1;
}
else if(numbers[j]==9){
int res=Integer.parseInt(numbers[j+1]+""+numbers[j+2]) ;
if(res==numbers[j]+1)
flag=1;
}
else if(result>9){
//do something
}
}
This is the code I wrote ,but I cant understand how to perform for anything except one-digit-numbers ( Example one-digit number is 1234 but two-digit numbers are 121314). Can anyone have a solution to this problem?. Please share with me in comments with a sample code.
I'm gonna describe the solution for you, but you have to write the code.
You know that the input string is a sequence of increasing numbers, but you don't know how many digits is in the first number.
This means that you start by assuming it's 1 digit. If that fails, you try 2 digits, then 3, and so forth, until you've tried half the entire input length. You stop at half, because anything longer than half cannot have next number following it.
That if your outer loop, trying with length of first number from 1 and up.
In the loop, you extract the first number using substring(begin, end), and parse that into a number using Integer.parseInt(s). That is the first number of the sequence.
You then start another (inner) loop, incrementing that number by one at a time, formatting the number to text using Integer.toString(i), and check if the next N characters of the input (extracted using substring(begin, end)) matches. If it doesn't match, you exit inner loop, to make outer loop try with next larger initial number.
If all increasing numbers match exactly to the length of the input string, you found a good sequence.
This is code for the pseudo-code suggested by Andreas .Thanks for the help.
for (int a0 = 0; a0 < q; a0++) {
String s = in.next();
boolean flag = true;
for (int i = 1; i < s.length() / 2; i++) {
int first = Integer.parseInt(s.substring(0, i));
int k=1;
for (int j = i; j < s.length(); j++) {
if (Integer.toString(first + (k++)).equals(s.substring(j, j + i)))
flag = true;
else{
flag=false;
break;
}
}
if (flag)
System.out.println("YES");
else
System.out.println("NO");
}
I would suggest the following solution. This code generates all substrings of the input sequence, orders them based on their start index, and then checks whether there exists a path that leads from the start index to the end index on which all numbers that appear are ordered. However, I've noticed a mistake (I guess ?) in your example: 10203 should also evaluate to true because 10<203.
import java.util.*;
import java.util.stream.Collectors;
public class PlayGround {
private static class Entry {
public Entry(int sidx, int eidx, int val) {
this.sidx = sidx;
this.eidx = eidx;
this.val = val;
}
public int sidx = 0;
public int eidx = 0;
public int val = 0;
#Override
public String toString(){
return String.valueOf(this.val);
}
}
public static void main(String[] args) {
assert(check("1234"));
assert(check("9101112"));
assert(check("9991000"));
assert(check("10203"));
}
private static boolean check(String seq) {
TreeMap<Integer,Set<Entry>> em = new TreeMap();
// compute all substrings of seq and put them into tree map
for(int i = 0; i < seq.length(); i++) {
for(int k = 1 ; k <= seq.length()-i; k++) {
String s = seq.substring(i,i+k);
if(s.startsWith("0")){
continue;
}
if(!em.containsKey(i))
em.put(i, new HashSet<>());
Entry e = new Entry(i, i+k, Integer.parseInt(s));
em.get(i).add(e);
}
}
if(em.size() <= 1)
return false;
Map.Entry<Integer,Set<Entry>> first = em.entrySet().iterator().next();
LinkedList<Entry> wlist = new LinkedList<>();
wlist.addAll(first.getValue().stream().filter(e -> e.eidx < seq
.length()).collect(Collectors.toSet()));
while(!wlist.isEmpty()) {
Entry e = wlist.pop();
if(e.eidx == seq.length()) {
return true;
}
int nidx = e.eidx + 1;
if(!em.containsKey(nidx))
continue;
wlist.addAll(em.get(nidx).stream().filter(n -> n.val > e.val).collect
(Collectors.toSet()));
}
return false;
}
}
Supposed the entered string is separated by spaces, then the code below as follows, because there is no way we can tell the difference if the number is entered as a whole number.
boolean increasing = true;
String string = "1 7 3 4"; // CHANGE NUMBERS
String strNumbers[] = string.split(" "); // separate by spaces.
for(int i = 0; i < strNumbers.length - 1; i++) {
// if current number is greater than the next number.
if(Integer.parseInt(strNumbers[i]) > Integer.parseInt(strNumbers[i + 1])) {
increasing = false;
break; // exit loop
}
}
if(increasing) System.out.println("TRUE");
else System.out.println("FALSE");

JAVA - Hangman game that keeps the correct letter entered in the unknown letters

if(letterGuessBoolean == true) {
System.out.println("Nice job! That was correct!");
for (position = 0; position < pickRandomWord.length(); position++) {
if (pickRandomWord.charAt(position) == letterGuess) {
System.out.print(letterGuess);
}
else {
System.out.print(unknownLetters);
}
}
}
loop does save the word properly, the unknown character never save the correct way.
You are printing out the latestly guessed letter only, because this is the only thing you are checking:
pickRandomWord.charAt(position) == letterGuess
You need to remember somehow and somewhere, which letters have been guessed previously. One variant could be the following:
String pickRandomWord = ""; // select your random word
char[] displayOutput = new char[pickRandomWord.length()];
for(int n = 0; n < displayOutput.length; ++n)
displayOutput[n] = '-';
/* ... */
if(letterGuessBoolean) // do not compare against true, if it is already boolean!
{
for(int position = 0; position < pickRandomWord.length(); ++position)
{
if (pickRandomWord.charAt(position) == letterGuess)
{
displayOutput[position] = letterGuess;
}
System.out.print(displayOutput[position]);
}
}

Java OOP-Accessing the last element in an array of objects

I am practicing object orientation here entering in basketball player names and how many points scored and rebounds grabbed.
How would I go through each element in an array of objects to find the last player with an even amount of points?
This is the code I have so far to enter the information. What do I need to do in my second forloop to examine each element and then display the last element that fits my criteria?
class basketballObj
{
public static void main (String[]args)
{
Basketball bbArray[];
String theName;
int thePoints;
int theRebounds;
int index;
int noOfElements = 0;
bbArray = new Basketball[3];
for(index = 0; index < bbArray.length; index++)
{
System.out.println("Enter a name ");
theName = EasyIn.getString();
System.out.println("Enter points scored ");
thePoints = EasyIn.getInt();
System.out.println("Enter rebounds grabbed ");
theRebounds = EasyIn.getInt();
bbArray[index] = new Basketball(theName, thePoints, theRebounds);
noOfElements++;
}
for(index = 0; index < bbArray.length; index++)
{
if(bbArray[index].getPoints() % 2 == 0)
{
}
}
}
}
Well if you want to find the last player with an even amount of points, you don't actually want to go through each element ;-). Try:
for(index = bbArray.length-1; index >= 0; index--)
{
if(bbArray[index].getPoints() % 2 == 0)
{
//add whatever relevant code here.
break; //this line breaks the for loop (because you've found a player with an even amount of score
}
}
we start at bbArray.length-1 because while you array contains 3 elements, arrays are zero-indexed. Meaning that to get the first element, you will have to call bbArray[0]. Similarly call bbArray[2] for the last element.
Simple. Iterated your array backwards.
boolean found = false;
for(int index=array.length-1; index>-1 && !found; index--) {
if(array[index].getPoints()%2 == 0) {
// found element. Break out of for loop
found=true;
}
}
You've pretty much got it.
Create a temporary, uninitialized variable Basketball temp; before the for loop that iterates through the bbArray and then set it equal to the bbArray[index] if the if condition is met.
If you want to save the index it was found at then create an int indexFound; as well.
Looping through it backwards as user2651804 suggested yields this:
public class basketballObj
{
public static void main(String[] args)
{
...
Basketball temp;
int indexFound = -1;
...
for(index = bbArray.length - 1; index >= 0; index++)
{
if(bbArray[index].getPoints() % 2 == 0)
{
temp = bbArray[index];
indexFound = index;
break;
}
}
//note temp will be null if no scores were even
//if (temp != null)
//you can use the above if statement if you don't want to use indexFound
//you can also just check if indexFound == -1
if (indexFound != -1)
{
System.out.println("Found at index: " + indexFound);
//
}
}
}

What am I doing Wrong here [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I made a program to search for a certain string in another string and print Word found if the condition is true or print word not found if condition is false
The logic is as follows
enter word
length of word
for searching for letter [1]
if true
then for till length of word match with string to be searched
else continue loop
But I always get word not found no matter what the input, please help me over here!!!
The code is as follows :-
import java.util.Scanner;
class Search_i_String
{
public static void main(String args[])
{
int flag=0;
Scanner Prakhar=new Scanner(System.in);
System.out.println("Enter a String");
String ori=Prakhar.nextLine();
System.out.println("Enter the String to be Searched");
String x=Prakhar.nextLine();
char a[]=new char[ori.length()];
char b[]=new char[x.length()];
for(int i=0;i<ori.length();i++)
{
a[i]=ori.charAt(i);
}
for(int i=0;i<x.length();i++)
{
b[i]=x.charAt(i);
}
for(int i=0;i<a.length;i++)
{
if (a[i]==b[0])
{
for(int j=0;j<b.length;j++)
{
while(flag==0)
{
if(b[j]==a[i])
{
flag=0;
}
else if(b[j] != a[i])
{
flag=1;
}
i++;
}
}
}
}
if (flag==0)
{
System.out.println("Word Found !!!");
}
else
System.out.println("Word not Found");
}
}
P.S. : I know I can use the contains() function but I can as my professor suggests against it and could someone please correct the program I have written, because I could have scavenged off a program from the internet too if I had to, I just wanted to use my own logic
Thank You(again)
while(flag==0)
{
if(b[j]==a[i])
{
flag=0;
}
else if(b[j] != a[i])
{
flag=1;
}
i++;
j++; //add this and try once
}
If you are comparing strings in Java, you have to use equals();
So, stringA.equals(stringB);
Cheers!
Let me get this straight. You're looking for b array inside of a array? "Enter the string to be searched" means that you are searching the other way around, but I'll go with the logic your code seems to follow... Here's a naive way to do it:
if (a[i]==b[0])
{
flag = 0;
for(int j=0;j<b.length;j++)
{
if(b[j] != a[i+j]) // will array index out of bounds when its not foud
{
flag++; // you should probably break out of a named loop here
}
}
if(flag == 0){/*win*/}
}
You're modifying your first search loop with variable i when you don't have to. You can just add i to j. Also, you don't need the while loop inside if i'm understanding your problem. Like others have said, functions exist to do this already. This algorithm isn't even as efficient as it could be.
I know of an algorithm where you check starting in the last character in b instead of the first character in b to begin with. Then you can use that information to move your search along faster. Without resorting to full pseudo code, anyone know what that's called?
The simple way(but not the fastest way) is use double loop to check the chars in strings one by one, pls ref to my code and comments:
public class SearchString {
public static void main(String[] args) {
String a = "1234567890";
String b = "456";
// Use toCharArray() instead of loop to get chars.
search(a.toCharArray(), b.toCharArray());
}
public static void search(char[] a, char[] b) {
if (a == null || b == null || a.length == 0 || b.length == 0) {
System.out.println("Error: Empty Input!");
return;
}
int lenA = a.length, lenB = b.length;
if (lenA < lenB) {
System.out
.println("Error: search key word is larger than source string!");
return;
}
// Begin to use double loop to search key word in source string
for (int i = 0; i < lenA; i++) {
if (lenA - i < lenB) { // If the remaining source string is shorter than key word.
// Means the key word is impossible to be found.
System.out.println("Not found!");
return;
}
// Check the char one by one.
for (int j = 0; j < lenB; j++) {
if (a[i + j] == b[j]) {
if (j == lenB - 1) { // If this char is the last one of key word, means it's found!
System.out.println("Found!");
return;
}
} else {
// If any char mismatch, then right shift 1 char in the source string and restart the search
break;
}
}
}
}
}
You can just use String.contains();
If you really want to implement a method, try this one:
public static void main(String[] args) {
// Initialize values searchedWord and original by user
String original = [get original word from user] ;
String searchedWord = [get searched for word from user];
boolean containsWord = false;
int comparePosition = 0;
for(int i = 0; i < original.length() - searchedWord.length(); i++) {
if(original.charAt(i) == searchedWord.charAt(comparePosition)) {
comparePosition += 1;
} else {
comparePosition = 0;
}
if(comparePosition == searchedWord.length()) {
containsWord = true;
break;
}
}
return containsWord? "Word found!!" : "Word not found.";
}

How to iterate a string in order to validate values are in range using charAt()?

I am trying to iterate a string that contains the users inputed values. I want to validate that the user only enters 4 characters and that all of them are between 1 and 4. For example, prompts the user to enter 4 values using commas, therefore they can only enter 1,2,3,4. If they enter anything else, then they will be asked again. I have included the section of my code where I am trying to perform the validation. I am also experiencing an unreachable code error which does not make sense to me. This takes place after I close the while (true) loop.
//Entering by ROWS
//This is for a 4x4 board size using rows
if (dataSelection == 1) {
if (boardSize == 1) {
int row = 1;
while (row < 5)
{
String row1Values4x4 = "-1";
while (true)
{
Scanner firstRow4x4 = new Scanner(System.in);
System.out.println("Please enter four values using commas for row " + row); //this needs to loop
row1Values4x4 = firstRow4x4.next();
row1Values4x4 = row1Values4x4.replaceAll(" ",""); //this is in case user enters numbers with spaces
for (int i = 0; i < row1Values4x4.length(); i++) {
char c = row1Values4x4.charAt(i);
if (row1Values4x4.length() == 7 && c == 48) //I entered 48 in order to test if it is using ascii value (48 = 0) {
break;
}
}
} //I think I need to include another break in order to escape the second loop?
String strArray[] = row1Values4x4.split(","); //This is where I get an unreachable code error
int arraySidesInteger[] = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
arraySidesInteger[i] = Integer.parseInt(strArray[i]);
}
fourArray[row-1] = arraySidesInteger;
for (int i = 0; i < fourArray.length; i++) {
for (int j = 0; j < fourArray.length; j++)
System.out.print(fourArray[i][j] + " ");
System.out.println();
}
row++;
}
Please let me know if there
Your comment is right; you need a second break in there. The break that exists only breaks out of the for loop, but not the while loop.
Perhaps instead of
while (true)
{
// do some stuff
for (/* some other stuff */)
{
// even more stuff
if (/* should we break */)
{
break;
}
}
}
you could try something like
boolean done = false;
while (!done)
{
// do some stuff
for (/* some other stuff */)
{
// even more stuff
if (/* should we break */)
{
done = true;
break;
}
}
}
Why not use the split method in strings
String s = userInput;
String[] inputArray = s.split(",");
for(int i = 0; i < inputArray.length; i++){
// check if the character is correct here
}

Categories

Resources