Okay so I have to write a program that loops and continues to ask for a pair of numbers until the user enters -1 in which case the program terminates. The combination numbers will be written like this : " 10 2" Without the quotes. When I type it in I get an error any idea what is wrong with my code?
Here is my code:
import java.util.*;
public class Combinations
{
public static int combinations( int n, int p )
{
if ( p == 0 )
return 1;
else if ( n == p )
return 1;
else
return ( combinations( n - 1, p - 1 ) + combinations( n - 1, p ) );
}
public static void main(String [] args)
{
int a=0;
int b=0;
boolean end = false;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the combination numbers");
while (end==false)
{
String line = scan.next();
StringTokenizer str=new StringTokenizer(line, " ");
String st = str.nextToken();
a = Integer.parseInt(st);
String st1 = str.nextToken();
b = Integer.parseInt(st1);
if(a==-1||b==-1)
{
end=true;
}
System.out.println(combinations(a,b));
}
}
}
Rather than using a StringTokenizer try
String line = scan.nextLine(); // not next
String str[] = line.split (" ");
// check that str.length is 2
String st = str[0];
a = Integer.parseInt(st);
String st1 = str[1];
b = Integer.parseInt(st1);
if(a==-1||b==-1)
{
break;
}
To get the full line use 'nextLine()' then tokenize it.
String line = scan.nextLine();
use this ...
String line = scan.nextLine();
instead of
String line = scan.next();
because its not take value after space.......
Related
I am writing a program that searches a file imported for a string of characters and length user enters. For example,
"Enter the possible letters in your word: "
Keyboard scans "aeppr"
"Enter the number of letters in your target words:"
"5"
and then proceeds to search my dictionary file and ultimately prints:
1 paper
I was wondering if you can use indexOf or any other methods or classes to display this result. As of now my code only displays words that match the searched letters and length exactly. Any help or advice would be greatly appreciated.
String input;
String altInput;
Scanner inFile = new Scanner(new File("words.txt"));
Scanner scanner = new Scanner(System.in);
String lettersBeingTested;
int numberOfLetters;
System.out.println("Enter the possible letters in your word: ");
lettersBeingTested = scanner.next();
System.out.println("Enter the number of letters in your target words: ");
numberOfLetters = scanner.nextInt();
int count = 0;
while (inFile.hasNext()) {
input = inFile.next();
altInput = "";
for (int i = 0; i < input.length(); i++) {
altInput = altInput + input.charAt(i);
if (input.contains(lettersBeingTested) && altInput.length() == numberOfLetters) {
count++;
System.out.println(count + " " + altInput);
}
}
}
System.out.println("End of list: " + count + " words found");
inFile.close();
}
public static void main(String[] args) throws FileNotFoundException {
findWords(new File("words.txt"));
}
public static void findWords(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter the possible letters in your word: ");
String lettersBeingTested = scan.next();
System.out.println("Enter the number of letters in your target words: ");
int numberOfLetters = scan.nextInt();
int[] requiredHistogram = histogram(lettersBeingTested, new int[26]);
Predicate<int[]> predicate = wordHistogram -> {
for (int i = 0; i < requiredHistogram.length; i++)
if (requiredHistogram[i] > 0 && wordHistogram[i] < requiredHistogram[i])
return false;
return true;
};
Set<String> words = findWords(file, predicate, numberOfLetters);
int i = 1;
for (String word : words)
System.out.println(i + " " + word);
System.out.println("End of list: " + words.size() + " words found");
}
}
private static int[] histogram(String str, int[] histogram) {
Arrays.fill(histogram, 0);
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++)
histogram[str.charAt(i) - 'a']++;
return histogram;
}
private static Set<String> findWords(File file, Predicate<int[]> predicate, int numberOfLetters) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
Set<String> words = new LinkedHashSet<>();
int[] histogram = new int[26];
while (scan.hasNext()) {
String word = scan.next().toLowerCase();
if (word.length() == numberOfLetters && predicate.test(histogram(word, histogram)))
words.add(word);
}
return words;
}
}
This look a bit complicated using histogramm. I think that if lettersBeingTested = "aa", then you're looking for words with at lest 2 'a' in it. Threfore, you have to build a histogram and compare symbol appearance number in the current words and in example one.
P.S.
altInput = altInput + input.charAt(i);
String concatenation within loop flows bad performance. Do look at StringBuilder isntead.
This program gets user input for 2 teams and 2 results, separates them with the " : " delimiter, then stores them in the array, when the user enters the word "stop" it stops asking for user input and is meant to display the results and stats of the match (which is not yet added into the code). the problem I'm having is if I type more than one line of match results then type 'stop', it only displays the first line of user input back to the console and not any of the others? input example: "Chelsea : Arsenal : 2 : 1".
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
System.out.println("please enter match results:");
// loop, wil ask for match results ( b < () )
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
// stop command
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between
// the
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
// convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
if ("stop".equals(line)) {
System.out.println(Arrays.toString(results));
return; // exit
}
The reason that it outputs the first results you entered is because results is assigned to s.split(" : "). s never changes in the first iteration of the outer for loop, so s.split(" : ") never changes. Your results always holds the first match results!
You have written your code very wrongly.
First, why do you have a while loop inside a for loop? The for loop is redundant.
Second, you can't use arrays for this. Try an ArrayList. Arrays don't have the ability to change its size dynamically.
Third, I recommend you to create a class for this, to represent a MatchResult.
class MatchResult {
private String homeTeam;
private String awayTeam;
private int homeScore;
private int awayScore;
public String getHomeTeam() {
return homeTeam;
}
public String getAwayTeam() {
return awayTeam;
}
public int getHomeScore() {
return homeScore;
}
public int getAwayScore() {
return awayScore;
}
public MatchResult(String homeTeam, String awayTeam, int homeScore, int awayScore) {
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
this.homeScore = homeScore;
this.awayScore = awayScore;
}
#Override
public String toString() {
return "MatchResult{" +
"homeTeam='" + homeTeam + '\'' +
", awayTeam='" + awayTeam + '\'' +
", homeScore=" + homeScore +
", awayScore=" + awayScore +
'}';
}
}
Then, you can create an ArrayList<MatchResult> that stores the user input.
Scanner sc = new Scanner(System.in);
String hometeam;
String awayteam;
int homescore;
int awayscore;
ArrayList<MatchResult> list = new ArrayList<>();
System.out.println("please enter match results:");
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
if ("stop".equals(line)) {
System.out.println(Arrays.toString(list.toArray()));
return; // exit
}
String results[] = line.split(" : "); // parse strings in between
hometeam = results[0];
awayteam = results[1];
homescore = Integer.valueOf(results[2]);
awayscore = Integer.valueOf(results[3]);
list.add(new MatchResult(hometeam, awayteam, homescore, awayscore));
}
try just adding another array
string[] matches = new string[]{};
then input your values into the array. I am using b since that is the int variable in your loop. I also put in + " : "
matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
then change the print to
System.out.println(Arrays.toString(matches));
i think this should work, but I wasn't able to test it.
public static final String SENTINEL = "stop";
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
string[] matches = new string[]{};
String hometeam = new String();
String awayteam = new String();
String homescore = new String();
String awayscore = new String();
int result0;
int result1;
System.out.println("please enter match results:");
// loop, wil ask for match results ( b < () )
for (int b = 0; b < 100; b++) {
String s = sc.nextLine();
// stop command
while (sc.hasNextLine()) { // better than the for loop
String line = sc.nextLine();
String results[] = s.split(" : "); // parse strings in between
// the
for (String temp : results) {
hometeam = results[0];
awayteam = results[1];
homescore = results[2];
awayscore = results[3];
}
// convert 'score' strings to int value.
result0 = Integer.valueOf(results[2]);
result1 = Integer.valueOf(results[3]);
matches [b] = hometeam.tostring() + " : " + awayteam.tostring() + homescore.tostring() + " : " + awayscore.tostring();
if ("stop".equals(line)) {
System.out.println(Arrays.toString(matches));
return; // exit
}
Here is a simple loop to grab all data from user until "stop" is entered and display the output of the input
Scanner sc = new Scanner(System.in);
ArrayList<String[]> stats = new ArrayList<>(); //initialize a container to hold all the stats
System.out.println("please enter match results:");
while(sc.hasNextLine())
{
String input = sc.nextLine();
String[] results = input.split(" : ");
if(results.length == 4)
{
stats.add(results);
}
else if(input.equals("stop"))
break;
else
System.out.println("Error reading input");
}//end of while
for(int i = 0; i < stats.size(); i++)
{
try{
System.out.println(stats.get(i)[0] + " vs " + stats.get(i)[1] + " : " +
Integer.valueOf(stats.get(i)[2]) + " - " + Integer.valueOf(stats.get(i)[3]));
}catch (Exception e) {
//do nothing with any invalid input
}
}
Output
please enter match results:
r : b : 5 : 4
r : c : 7 : 10
j : g : 3 : 9
stop
r vs b : 5 - 4
r vs c : 7 - 10
j vs g : 3 - 9
I'm working on a code in java that will swap a random letter inside of a word with another random letter within that word.
I need to apply this code to an entire string. The issue I'm having is my code can't identify white space and therefore runs the method for once per string instead of once per word. How can I split the input string and apply the method to each word individually. Here's what I have so far.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args {
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
System.out.print(scramble(word));
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
Check the inline comments:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
//Split your input phrase
String[] wordsArray = word.split(" ");
//For each word in the phrase call your scramble function
// and print the output plus a space
for (String s : wordsArray){
System.out.print(scramble(s) + " ");
}
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
As destriped in teh String.split(); you can define a regrex for instance " " and then a return array of String[] for all substrings split on the input is returned
see String split
example
String in = "hello world";
String[] splitIn = in.split(" ");
The same way you can test for other things such as "," "." ";" ":" etc
Please run the code if possible
input: "wooooow"
output:
w:2
o:5
o:5
o:5
o:5
o:5
w:2
I want the results to be : w:2 o:5
I have tried several ifs and loops to make it happen but I can't is there a syntax for it? or anything
import java.util.Scanner;
public class test {
public static void main( String[] args ){
String sWord= new String();
int nCtr,nCtr2,nTemp=0,n,n1=0,n2=0,n3=0;
char cTemp=' ',cTemp2=' ';
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
n = sWord.length();
char[] cArray = new char[n];
cArray = sWord.toCharArray();
for(int ctr=cArray.length;ctr>0;ctr--){
for(nCtr=0;nCtr<cArray.length;nCtr++){
if(cArray[nCtr]==sWord.charAt(n1)){
nTemp++;
}
}//for
cTemp = cArray[n2];
for(nCtr2=0;nCtr2<n;nCtr2++){
if(sWord.charAt(nCtr2)=='$'){
n3++;
}
}//for
System.out.println("# of occurence of " + cTemp + " is " + nTemp);
n1++;
n2++;
nTemp=0;
}//for minus
}//
}//class
You could try something like this:
import java.util.HashMap;
import java.util.Scanner;
public class test {
public static void main( String[] args ){
String sWord= new String();
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
HashMap<Character, Integer> charCount = new HashMap<Character, Integer>();
for(Character c : sWord.toCharArray()) {
if(charCount.containsKey(c)) {
charCount.put(c, charCount.get(c)+1);
} else {
charCount.put(c, 1);
}
}
for(Character key : charCount.keySet()) {
System.out.print(key + ":" + charCount.get(key) + " ");
}
}
}
This will print the following lines:
Enter a Word
wooooow
w:2 o:5
Should work for Uppercase, Lowercase, Numbers, ... everything you can save in a String.
edit:
Without using a HashMap:
public static void main( String[] args ){
String sWord= new String();
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
int[] cArr = new int[1024];
for(char c : sWord.toCharArray()) {
if((int) c <= cArr.length) {
cArr[(int) c]++;
}
}
for(int x = 0; x < cArr.length; x++) {
if(cArr[x] > 0) {
System.out.print((char) x + ":" + cArr[x]);
}
}
}
This works because you can cast a char to an integer and use it as an index for the array. Also you can do this reverse integer -> char.
This will work for the first 1024 Chars in your Charset. Normaly theese are all uppercase, lowercase, numbers and special characters.
This answer works only for lowercase input. For uppercase as well, use an array of size 46.
You will have to keep track of the occurrences yourself by creating a new array or some other data structure. Also, I dont think that your loops are very efficient.
import java.util.Scanner;
public class Temp {
public static void main( String[] args ){
String sWord= new String();
int nCtr,nCtr2,nTemp=0,n,n1=0,n2=0,n3=0;
char cTemp=' ',cTemp2=' ';
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word");
sWord = input.nextLine();
n = sWord.length();
char[] cArray = new char[n];
cArray = sWord.toCharArray();
int[] countsOfChars = new int[26];
for(int ctr=cArray.length;ctr>0;ctr--){
for(nCtr=0;nCtr<cArray.length;nCtr++){
if(cArray[nCtr]==sWord.charAt(n1)){
nTemp++;
}
}//for
cTemp = cArray[n2];
for(nCtr2=0;nCtr2<n;nCtr2++){
if(sWord.charAt(nCtr2)=='$'){
n3++;
}
}//for
// System.out.println("# of occurence of " + cTemp + " is " + nTemp);
countsOfChars[cTemp - 'a'] = nTemp;
n1++;
n2++;
nTemp=0;
}//for minus
for(int i=0; i<26; i++){
if(countsOfChars[i] != 0) {
System.out.println("# of occurence of " + (char)('a'+i) + " is " + countsOfChars[i]);
}
}
}//
}//class
You can try something like this
string str = "wooooow";
Dictionary<char, int> table = new Dictionary<char, int>();
foreach (char ch in str.ToCharArray())
{
int count = 0;
if (table.TryGetValue(ch, out count))
{
table[ch] = count + 1;
}
else
{
table.Add(ch, 1);
}
}
foreach (var item in table)
{
Console.Write(item.Key + ":" + item.Value+" ");
}
I need to input a two strings, with the first one being any word and the second string being a part of the previous string and i need to output the number of times string number two occurs. So for instance:String 1 = CATSATONTHEMAT String 2 = AT. Output would be 3 because AT occurs three times in CATSATONTHEMAT. Here is my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.indexOf(word9);
System.out.println(occurences);
}
It outputs 1 when I use this code.
Interesting solution:
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
Basically what we're doing here is subtracting the length of main from the length of the string resulting from deleting all instances of sub in main - we then divide this number by the length of sub to determine how many occurrences of sub were removed, giving us our answer.
So in the end you would have something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurrences = countOccurrences(word8, word9);
System.out.println(occurrences);
sc.close();
}
You could also try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.nextLine();
String word9 = sc.nextLine();
int index = word8.indexOf(word9);
sc.close();
int occurrences = 0;
while (index != -1) {
occurrences++;
word8 = word8.substring(index + 1);
index = word8.indexOf(word9);
}
System.out.println("No of " + word9 + " in the input is : " + occurrences);
}
Why no one posts the most obvious and fast solution?
int occurrences(String str, String substr) {
int occurrences = 0;
int index = str.indexOf(substr);
while (index != -1) {
occurrences++;
index = str.indexOf(substr, index + 1);
}
return occurrences;
}
Another option:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.split(word9).length;
if (word8.startsWith(word9)) occurences++;
if (word8.endsWith(word9)) occurences++;
System.out.println(occurences);
sc.close();
}
The startsWith and endsWith are required because split() omits trailing empty strings.