I'm new to Java and am working through some problems. I'm stuck on a question that asks me to "Write a program to input ten words and then display the words that are first and last in alphabetical order". The question is ambiguous. It could mean put all the input words into alphabetical order and display the first and last of these (harder) or display the first and last inputted word in alphabetical order (easier). I wrote the following code:
import java.util.Scanner;
public class Alphabetical {
public static void main(String[] args) {
String[] s = new String[10];
for (int i = 0; i < 10; i++) {
System.out.println("Enter word");
Scanner ins = new Scanner(System.in);
s[i] = ins.nextLine().toLowerCase();
}
int result = s[0].compareTo(s[10]);
if (result < 0) {
System.out.println(s[0]);
System.out.println(s[10]);
}
else if(result>0){
System.out.println(s[10]);
System.out.println(s[0]);
}
else{
System.out.println("Words are identical so cannot be placed in alphabetical order");
}
}
}
But I'm getting an out of bounds exception where the compareTo method is placed and I'm not sure why. If anybody could help that would be great. If anyone could help with the harder version of the question too, that would be even better.
new String[10] creates an array of 10 elements.
s[10] is the 11th element of the array since elements begin with 0. So you have to treat s[9] as your last element. compareTo is not your problem
Because your "s" array have 10 elements. You cahange your code
import java.util.Scanner;
public class Alphabetical {
public static void main(String[] args) {
String[] s = new String[10];
for (int i = 0; i < 10; i++) {
System.out.println("Enter word");
Scanner ins = new Scanner(System.in);
s[i] = ins.nextLine().toLowerCase();
}
int result = s[0].compareTo(s[9]);
if (result < 0) {
System.out.println(s[0]);
System.out.println(s[9]);
}
else if(result>0){
System.out.println(s[9]);
System.out.println(s[0]);
}
else{
System.out.println("Words are identical so cannot be placed in alphabetical order");
}
}
}
The reason you're getting the error about the array is because arrays start with index 0 and go up to one less than the size of the array. So on an array with a size of 10, the highest index is 9. Did you try searching the exception online before posting this question?
What the question means, you'll have to clarify with the person who gave you the assignment/problem.
Related
import java.util.Scanner;
import java.util.ArrayList;
public class kek2 {
public static void main(String[] args) {
Scanner imeskanera = new Scanner(System.in);
ArrayList<String> wordlist = new ArrayList <String>();
while(true) {
System.out.println("Type a word: ");
String word = imeskanera.nextLine();
int lenght =wordlist.size();
if(word.equals("")) {
for(int i = 0;i<lenght; i++) {
System.out.println(wordlist.get(lenght-i));}
break;
}
wordlist.add(word);
}
}
}
Im trying to print out the array in reversed order but i get error in (lenght-i) part, everything looks fine to me, am'I doing something wrong that Java doesnt allow?
It may be better to limit while loop to reading the inputs and when user is done, print the list contents in any desired order.
Scanner imeskanera = new Scanner(System.in);
List<String> wordlist = new ArrayList<>();
String word;
System.out.println("Type a word: ");
while(!(word = imeskanera.nextLine()).isEmpty()) {
wordlist.add(word);
System.out.println("Type a word: ");
}
for (int i = wordlist.size(); i-- > 0;) { // index decremented in condition
System.out.println(wordlist.get(i));
}
Or ListIterator may be retrieved using List::listIterator and its methods hasPrevious() / previous() can be used to iterate in reverse direction -- however, the size of list is needed anyway:
for (ListIterator i = wordlist.listIterator(wordlist.size()); i.hasPrevious();) {
System.out.println(i.previous());
}
In this question we need to find the number of "codechef" that we can form using the characters taken from input strings.
First line is number of test cases and next line is the number of
input string. The output is a single integer value representing the
number of "codechef" string that can be formed from the given
characters.
It throws NZEC error on submitting and when I use try catch block to avoid it, it shows wrong answer. This is a question from codechef beginners section.
Problem Link
My approach:
Store every character from the input string into a Hashmap with the frequency.
Create one character array containing the characters used in the word "codechef". And another integer array contains the frequency of these corresponding characters, here my arrays are
char[ ] c ={c,o,d,e,h,f}
int[ ] arr={2,1,1,2,1,1}
I run a loop traversing each character in hashmap and delete the character count needed for a word formation. Every complete traversal will give one increment in count.
Implementation:
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-->0){
int n = sc.nextInt();
sc.nextLine();
String s;
HashMap<Character,Integer> hmap = new HashMap<Character,Integer>();
for(int i = 0;i < n;i++){
s = sc.nextLine();
for(int j = 0;j < s.length();j++){
if(hmap.containsKey(s.charAt(j)))
hmap.put(s.charAt(j),hmap.get(s.charAt(j))+1);
else
hmap.put(s.charAt(j),1);
}
}
/* for(Map.Entry entry:hmap.entrySet()){
System.out.println(entry.getKey()+": "+entry.getValue());
}*/
int arr[] = {2,1,1,2,1,1};
char crr[] = {'c','o','d','e','h','f'};
int count = 0;
int i = 0;
boolean flag = true;
while(flag){
if(hmap.get(crr[i])>=arr[i])
hmap.put(crr[i],hmap.get(crr[i])-arr[i]);
else flag = false;
if(i==5 && flag)
{
count++;
i = 0;
}
else
i++;
}
System.out.println(count);
}
sc.close();
}
}
if(hmap.get(crr[i])>=arr[i])
This line contains an Exception what if hmap does not contain crr[i].
Try catch will always give wrong answer in these sites because these sites only checks what answer your code is producing.
I have an assignment for school in which I have to have a user enter names which are then put into title case and then alphabetical order. My problem is that if a user enters 11 names or more they no longer become alphabetized. If someone could explain why this is happening and maybe give me some tips to fix this I would really appreciate it. Thanks!
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main (String [] args)
{
ArrayList <String> names = new ArrayList <String>();
Scanner scan = new Scanner(System.in);
System.out.println ("Please Enter a Name. (Enter 'stop' to end)");
String g = scan.nextLine();
g = titleCase(g);
names.add(g);
while (!g.equals("Stop"))
{
System.out.println ("Please Enter a Name. (Enter 'stop' to end)");
g = scan.nextLine();
g = titleCase(g);
if (!g.equals("Stop"))
abcSort(g, names);
}
toString(names);
}
This method is what returns the string into title case.
public static String titleCase(String s)
{
String firstLetter;
s = s.toLowerCase();
firstLetter = s.substring(0, 1);
s = firstLetter.toUpperCase() + s.substring(1, s.length());
return s;
}
This is my method for putting the names into alphabetical order.
public static void abcSort(String inputName, ArrayList <String> sorted)
{
String g;
for (int i = 0; i < sorted.size(); i++)
{
g = sorted.get(i);
if (inputName.compareTo(g) < 0)
{
sorted.add (i, inputName);
return;
}
else {
sorted.add(inputName);
return;
}
}
}
The assignment requires me to also have a method to print the ArrayList which is what this one does
public static void toString(ArrayList s)
{
System.out.println(s);
}
}
The problem is with your abcSort method. Since you return in both the if and the else part, it's impossible for the for loop to get beyond the first string. You want to add the string to the end of this list if it can't go before any of the other strings. At the moment it goes to the end if it can't go before the first string. You need to get rid of the else and move the line sorted.add(inputName); to be after the for loop.
A corrected version is:
public static void abcSort(String inputName, ArrayList <String> sorted)
{
String g;
for (int i = 0; i < sorted.size(); i++)
{
g = sorted.get(i);
if (inputName.compareTo(g) < 0)
{
sorted.add (i, inputName);
return;
}
}
sorted.add(inputName);
}
A good IDE can find problems like this. When I paste your version into IntelliJ IDEA, the for loop goes a horrible shade of brown and it tells me the problem: 'for' statement does not loop.
I don't know where you are getting the number 11 from. The original version fails if you enter Anne, Chris, Bob, Stop.
I have two different arrays and they both contain the same type of element. The elements are obtained from user input. And the arrays can store fixed size of element.
*Let's say that fisrt one is basically an arrayList and it adds the user input into the list.
The second one is simply an array which also gets value from user input. All the elements of second array are also contained in the first array and the length of this array is less than the first array*
Now I want to print an array which is the result of first array-second array.
This is the program I am working on right now. You may avoid this coding just to give me a theoritical concept for doing that.
package issuetracking;
import java.util.*;
public class IssueTrackingObject {
ArrayList<String> crIss = new ArrayList<String>();
Scanner input = new Scanner(System.in);
boolean crIss_bool;
int numOfSolvedIss;
private String[] solvedIss;
//lets user create some issues and add them into an arrayList
public void createIssue() {
System.out.println("Enter 5 issues: ");
for (int i = 0; i < 5; i++) {
System.out.println("Issue " + (i + 1 + ": "));
crIss_bool = crIss.add(input.nextLine());
}
}
//Let user mark some issues as solved (which are already in the list that the user has just created)
public void solvedIssue() {
System.out.println("How many solved issue you have(Must be less than 5): ");
numOfSolvedIss = input.nextInt();
solvedIss = new String[numOfSolvedIss];
for (int k = 0; k < numOfSolvedIss; k++) {
System.out.print("Enter solved issue(REMEMBER THAT THE SOLVED ISSUE MUST BE FROM ONE OF THEM YOU ALREADY HAVE CREATED)no. " + (k + 1) + ": ");
solvedIss[k] = input.next();
}
}
public void printUnsolvedIssue() {
//print out the elements of createIssue() that doesn't belong to the solvedIssue()
}
You can use a simple solution like this:
for (String solved : solvediss) {
if (solved != null) crIss.remove(solved);
}
This will remove all the Strings from the list that are in the array.
Of course, you could also do this.
crIss.removeAll(Arrays.asList(solvediss));
Go over your second array and use the remove method in arraylist to remove every element of second array from the first.
for (int i = 0; i < solvedIss.length; i++) {
crIss_bool = crIss.remove(solvedIss[i]);
}
Removing the elements might be the simplest method in this case, but it causes original list to change.
If you do not wish to have any destructive modification to the original list, you could perform a simple search like following.
for (String issue : crIss) {
bool isUnSolved = true;
for (String solvedIssue : solvedIss) {
if (issue.equals(solvedIssue)) {
isUnSolved = false;
break;
}
}
if (isUnSolved) {
// Print the 'issue' or do whatever you want to do with it.
}
}
Hope this helps.
Good luck.
I am having trouble starting out this program. I am supposed to write a program that will populate an ArrayList by asking the user for 10 numbers.
After the list is made I'm to navigate it and if a number is even number, remove it from the ArrayList and put the number to a Stack of integers. So far I have this but I am confused on how to get the stack started so that I can put the even numbers into it:
import java.io.* ;
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
ArrayList<Integer> test = new ArrayList<Integer>();
Stack<Integer> myStack = new Stack<Integer>();
System.out.print ("Enter Number: \n");
for (int i = 0; i < 10; i++) { //Put Into ArrayList
test.add(input.nextInt());
}
System.out.print("Contents of Array: " + test );
System.out.print("\n");
for (int i= 0; i < 10 ; i++) {
int item = myIterator.getNext();
if (item % 2 == 0) {
myListIterator.remove(); //removes it from the ArrayList
myStack.push(item); //puts it into the stack
}
}
System.out.print("Contents of Array afer numbers removed: " + test );
System.out.print("\n");
}
}
It seems that you just need to initialize the stack. Do the initialization of the stack where you initialize the test array.
Put this:
Stack<Integer> item = new Stack <Integer> ();
After:
ArrayList<Integer> test = new ArrayList<Integer>();
EDIT -- I was feeling generous, so I finished it for ya ;) You were actually almost all the way there, so I don't feel I really deprived you of a learning opportunity. The only other real thing you were missing was initializing the iterator and using it correctly.
Note the following:
-- you will see that if you use the iterator, you can just get rid of the for loop.
-- I changed the names of the variables so they are a bit easier to follow-naming is important.
-- Finally, since an ArrayList ISA List, you will notice I changed the declaration for the input values to use the interface for the declaration.
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> inputValues = new ArrayList<Integer>();
Stack<Integer> evens = new Stack <Integer> ();
System.out.print("Enter Number: \n");
for (int i = 0; i < 10; i++) { //Put Into ArrayList
inputValues.add(input.nextInt());
}
System.out.println("Contents of Array: " + inputValues);
Iterator<Integer> iter = inputValues.iterator();
while(iter.hasNext()) {
Integer currentVal = iter.next();
if (currentVal % 2 == 0) {
iter.remove(); //removes it from the ArrayList
evens.push(currentVal); //puts it into the stack
} else {
System.out.println("No");
}
}
System.out.println("List values " + inputValues);
System.out.println("Stack values " + evens);
}
}
Hint: The commented out code has a declaration and initialization of a stack that is suitable for your purposes. It needs to be before the code that pushes stuff onto the stack.
I really doubt your code compiles without modification. For example myListIterator and myStack aren't even declared and I don't remember java Iterators to have a getNext() method.
Before using a variable, you must first declare it and the initialize it, these operations can be both done in one line, for example : Stack<Integer> myStack = new Stack<Integer>();
Looking at the tags of your question, this seems to be some kind of homework, I'm sure the documentation explains all of theses steps.
And since your using a ListIterator to remove the Integer from the ArrayList, there's no need to use a for loop, you can do something like
while(myListIterator.hasNext()) {
Integer item = myListIterator.next();
if(item % 2 == 0) {
item.remove();
myStack.add(item);
}
}