For the code, it wakes a user input and splits it by witespaces then takes the individual words from the user input and checks to see if the singular word is in the text file( containing parallel arrays with one being a string array and the other an int array). For every time it finds the user inputted word it needs to add one but the problem is that I don't know how to implement either match, or compare or equalsTo to check to see if the word is in the String array.
public class MovieReviewSentimentAnalysis {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// TODO: complete me
//make own arrays to pass by value
//movieReviewComments = the text
String[] movieReviewComments = new String[10000];
//movieReviewScores = numeric values, avoid lit. values
int[] movieReviewScores = new int[10000];
String userComment = "";
// String reviewFile = "";
// reviewFile = args[0];
String whiteComment = "";
MovieReviewReader.readMovieReviews("movie_reviews.txt", movieReviewComments, movieReviewScores); //string, string array, and int array
System.out.println("Please type one line of review and when you are done press either Ctr D or Ctr Z");
userComment = userInput.nextLine();
System.out.println(userComment);
String[] words2 = userComment.split("[\\W]");
double itemCount = 0;
double wordTotal = 0;
double totalSumOfUserCommentWords = 0;
String test = "";
// int itemCount = words.length;
for (int i = 0; i < words2.length; i++)
{
test = words2[i];
itemCount = wordCount(test, movieReviewComments, movieReviewScores);
wordTotal += itemCount;
totalSumOfUserCommentWords = wordTotal / userComment.length();
// System.out.println(totalSumOfUserCommentWords);
}
// System.out.println(reviewFile);
System.out.println("Incomplete assignment");
userInput.close();
}
public static double wordCount(String test, String[] movieReviewComments, int[] movieReviewScores)
{
double storeScore = 0;
double totalSumofReviewScores = 0;
double numOfTimesWordAppears = 0;
for (int i=0; i < (movieReviewComments.length); i++)
{
if (test.equals(movieReviewComments[i])) //////////////////////////////////////////////////////////SOMETHING'S OFF
{
storeScore = movieReviewScores[i];
totalSumofReviewScores += storeScore;
numOfTimesWordAppears++;
System.out.println("Found"); //QUQ when will you appear!?!?
}
else
System.out.println("You dun goofed"); //delete after fixing problem
}
double wordScoreAverage = totalSumofReviewScores / numOfTimesWordAppears;
return wordScoreAverage;
}
It is very simple. You can do it the following way:
if (movieReviewComments[i].toLowerCase().contains(test.toLowerCase())
And if you want to test an equal comparison and not containment, use following instead:
if (test.equalsIgnoreCase(movieReviewComments[i])
Related
I'm trying to get a printout of all variations of a certain String. For example, we have this input: AB0C0. The 0 in the 3rd and 5th spots should be treated as variables. The variable characters are 1, 2, and 3 to be placed in the spot of 0. This means there would be all possible variations of this input:
AB1C1
AB2C1
AB3C1
AB1C2
AB1C3
AB2C2
AB2C3
AB3C2
AB3C3
This is just an example. A 5-character long string is a place for 1 to 5 variables. The issue I'm facing is, that it should generate all variations no matter how many variables are in the input in no matter in which place they are.
Scanner scanner = new Scanner (System.in);
System.out.println("Enter the key consisting of 5 characters:");
String input = scanner.next();
String strOutput1 = input.replaceFirst("0","1");
String strOutput1A = input.replace("0","1");
String strOutput2 = input.replaceFirst("0","2");
String strOutput3 = input.replaceFirst("0","3");
String strOutput4 = input.replaceFirst("0","4");
String strOutput5 = input.replaceFirst("0","5");
System.out.println(strOutput1.toUpperCase());
System.out.println(strOutput1A.toUpperCase());
System.out.println(strOutput2.toUpperCase());
System.out.println(strOutput3.toUpperCase());
System.out.println(strOutput4.toUpperCase());
System.out.println(strOutput5.toUpperCase());
What about this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the key consisting of 5 characters:");
String input = scanner.next();
//find positions of '0' in input
List<Integer> varPositions = findVarPositions(input);
//create permutations
List<String> permutations = new ArrayList<>();
permutations.add(input);//AB0C0
for (int position : varPositions) {
permutations = permutateAtPosition(permutations, position);
}
//print permutations
for (String permutation : permutations) {
System.out.println(permutation.toUpperCase());
}
}
private static List<Integer> findVarPositions(String input) {
List<Integer> varPositions = new ArrayList<>();
int lastVarPosition = -1;
while ((lastVarPosition = input.indexOf('0', lastVarPosition + 1)) != -1) {
varPositions.add(lastVarPosition);
}
return varPositions;
}
private static List<String> permutateAtPosition(List<String> partialyPermutated, int position) {
List<String> result = new ArrayList<>();
char[] replacements = {'1', '2', '3', '4', '5'};
for (String item : partialyPermutated) {
for (int i = 0; i < replacements.length; i++) {
String output = replaceCharAt(item, position, replacements[i]);
result.add(output);
}
}
return result;
}
private static String replaceCharAt(String input, int position, char replacement) {
//converting to char array, because there's no method like
//String.replaceAtPosition(position, char)
char[] charArray = input.toCharArray();
charArray[position] = replacement;
return new String(charArray);
}
}
It's not fixed to a number of variables.
The idea is to extract positions of '0' and subsequently call the method permutateAtPosition, which takes a partially permutated list and permutates it by one more level.
For "a0b0c0" and values 1-2 it would be ['a0b0c0'], then ['a1b0c0','a2b0c0'], then ['a1b1c0','a1b2c0','a2b1c0','a2b2c0'], and finally ['a1b1c1','a1b1c2','a1b2c1','a1b2c2','a2b1c1','a2b1c2','a2b2c1''a2b2c2'].
This solution keeps everything in memory, so in the general case (unlimited input string) it would be wiser to go with depth-first instead.
I've got another solution for you.
First step, getting the amount of variables:
int variableCount = 0;
for (int i = 0; i < 5; i++) {
if (input.charAt(i) == '0') {
variableCount++;
}
}
Then calculating the amount of results we are expecting:
int countMax = (int)Math.pow(4,variableCount);
Lastly, count up in base 4. Pad the number with 0's and replace the original input 0's:
for (int i = 0; i < countMax; i++) {
String paddedNumbers = format("%" + variableCount + "s",Integer.toString(i, 4)).replace(" ", "0");
int replacedCount = 0;
char[] outputChars = input.toCharArray();
for (int j = 0; j < 5; j++) {
if (input.charAt(j) == '0') {
outputChars[j] = paddedNumbers.charAt(replacedCount);
replacedCount++;
}
}
System.out.println(outputChars);
}
I'm doing a hackerrank medium challenge for a password cracker. I want to be able to check if a given string, attempt, contains all the words in pass. pass is an array of passwords and attempt is a concatenation of random entries in pass. If attempt contains ONLY words that are found as entries in pass, then it is deemed a good password and the words from the input of attempt, limited with spaces, is printed.
Sample Input
3 //3 attempts
6 //6 words for attempt 1
because can do must we what //pass[]
wedowhatwemustbecausewecan //attempt
2 //...
hello planet
helloworld
3
ab abcd cd
abcd
Expected Output
we do what we must because we can
WRONG PASSWORD //Because planet is not in pass[]
ab cd
Code
public class Solution {
static String passwordCracker(String[] pass, String attempt) {
int arrayLength=pass.length;
int accuracy=0;
String trips_array[] = new String[pass.length];
String [] newWord = new String[20];
for (int i=0; i<pass.length;i++)
{
// int j=0;
String[] arr = pass[i].split(" ");
//-------------------------------
if (attempt.contains(pass[i]))
{
accuracy++;
newWord[i] = pass[i];
trips_array[i] = attempt.split(" ");
}
//------------------------------
}
StringBuilder sb = new StringBuilder();
for (String words : trips_array) {
sb.append(words);
}
for (int i=0; i<pass.length;i++)
{
if (accuracy==pass.length)
return sb.toString() + " ";
else
return "WRONG PASSWORD";
}
return "test";
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int n = in.nextInt();
String[] pass = new String[n];
for(int pass_i = 0; pass_i < n; pass_i++){
pass[pass_i] = in.next();
}
String attempt = in.next();
String result = passwordCracker(pass, attempt);
System.out.println(result);
}
in.close();
}
}
The part in focus is the part in the //----------------- comment section. Basically, my goal is to see if the attempt contains the correct entries in pass, and if so, save that substring of the attempt (or similarly, the entry in pass) to a new array which can be printed in the correct order. If you check the expected output above, you'll see that the output is the same as attempt except with spaces.
Essentially, I would need to find the breaks in the words of attempt and print that if it fulfills the above requirements (first paragraph).
See this for more details
https://www.hackerrank.com/challenges/password-cracker/problem
If it helps you
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int testNumb = Integer.parseInt(reader.readLine());
List<String> passList = new ArrayList<>();
List<String> attList = new ArrayList<>();
for (int i = 0; i < testNumb; i++) {
reader.readLine();
passList.add(reader.readLine());
attList.add(reader.readLine());
}
reader.close();
for (int i = 0; i < testNumb; i++) {
String s1 = passList.get(i);
String s2 = attList.get(i);
StringBuilder sb = new StringBuilder();
String[] s1Arr = s1.split(" ");
while (s2.length() > 0) {
int s2Lenght = s2.length();
for (String s : s1Arr) {
if (s2.startsWith(s)) {
sb.append(s + " ");
s2 = s2.substring(s.length());
}
}
if (s2.length() == s2Lenght) {
sb = new StringBuilder("wrong pass");
break;
}
}
System.out.println(sb.toString());
}
Your for loop looks too complicated, here is how I would approach that part.
boolean isAllWords = true;
int checksum = 0;
for (int j = 0; j < pass.length; j++) {
if (!attempt.contains(pass[j]) {
isAllWords = true;
break;
}
checksum += pass[j].length;
}
if (isAllWords && checksum == attempt.length) {
//This means attempt contains all words in pass array and nothing more
//... handle successful attempt
} else {
//... handle bad attempt
}
EDIT: right, I forgot to state the problem -- which is the fact that I get 0 as an output.
CONTEXT
My program aims to take a user-inputted number-word (1- 99) and output it as an integer (i.e. thirty-four = 34). I can't figure out where the error in my code is and need help:
Scanner scInput = new Scanner(System.in);
String word = scInput.nextLine(); //number in word-form (i.e. twenty six)
char[] charArray = word.toCharArray();//string to char array for word^
int divider = 0; //position of hyphen/space in charArray
All 2-word numbers are comprised of a tens value & a ones value. Assuming proper syntax [english], the word before the hyphen/space divider is the tens and the word following divider is the ones.
ARRAYS
//word values - components & syntax (1-99)
//ONES
public static final String[] wONES = {"one","two","three","four","five","six","seven","eight","nine"};
//TENS
public static final String[] wTENS = {null,"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
//TEENS
public static final String[] wTEENS = {"ten", "eleven", "twelve", "thirteen","fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
I've organized all the word-components into 3 different arrays: ones, tens, and teens.
//equivalent integer-array of above String arrays
//ONES
public static final int[] nONES = {1,2,3,4,5,6,7,8,9};
//TENS
public static final int[] nTENS = {0,20,30,40,50,60,70,80,90};
//TEENS
public static final int[] nTEENS = {10,11,12,13,14,15,16,17,18,19};
I created 3 other arrays that are the same as the above three arrays, except they store the integer values.
CODE
Here I separate the user-inputted String into two sections: the tens and the ones. So if the number was 72: 70 = tens and 2 = ones.
int tensValue = 0; //number's tens value (i.e. 30)
int onesValue = 0; //ones value (i.e. 3)
char[] tensArray = null; //array storing tens section of word (before divider)
for (int u = 0; u < divider; u++){
tensArray[u] = charArray[u];
}
String tens = new String(tensArray); //convert char array to String
char[] onesArray = null; //array storing ones section of word (after divider)
for (int u = divider + 1; u > divider && u < charArray.length; u++){
onesArray[u] = charArray[u];
}
String ones = new String(onesArray);
//searches for matches in String array for tens
for(int u = 0; u < wTENS.length; u++){
if(tens.equals(wTENS[u])){
tensValue = nTENS[u];
total += tensValue;
}
}
//searches for matches in String array for ones
for(int u = 0; u < wONES.length; u++){
if(ones.equals(wONES[u])){
onesValue = nONES[u];
total += onesValue;
In your current code you are doing char[] tensArray = null; which should be something like char[] tensArray = new char[10]; or else you end up with NPE.
It might not be most efficient but here is a simple and better approach to your problem.
Read the line and split it on white space (assuming you are separating your words by a space).
Search each of the tokens you get after split in the above lists and add the corresponding number (same index) to your answer.
Print the answer.
Here is the code snippet:
class Main
{
public static final String[] wONES = {"one","two","three","four","five","six",
"seven","eight","nine"};
public static final String[] wTENS = {"ten","twenty","thirty","forty","fifty","sixty",
"seventy","eighty","ninety"};
public static final String[] wTEENS = {"eleven", "twelve", "thirteen","fourteen",
"fifteen", "sixteen", "seventeen", "eighteen",
"nineteen"};
public static final int[] nONES = {1,2,3,4,5,6,7,8,9};
public static final int[] nTENS = {10,20,30,40,50,60,70,80,90};
public static final int[] nTEENS = {11,12,13,14,15,16,17,18,19};
public static void main (String[] args) throws Exception
{
Scanner scInput = new Scanner(System.in);
String word = scInput.nextLine();
int answer = 0;
/* Assuming you are giving space between words */
for(String s : word.split(" ")) {
/* Scan wONES */
for(int i = 0; i < wONES.length; i++) {
if(wONES[i].equalsIgnoreCase(s)) {
answer += nONES[i];
continue;
}
}
/* Scan wTENS */
for(int i = 0; i < wTENS.length; i++) {
if(wTENS[i].equalsIgnoreCase(s)) {
answer += nTENS[i];
continue;
}
}
/* Scan wTEENS */
for(int i = 0; i < wTEENS.length; i++) {
if(wTEENS[i].equalsIgnoreCase(s)) {
answer += nTEENS[i];
continue;
}
}
}
System.out.println("Result: " + answer);
}
}
Input:
thirty four
Output:
34
You have an interesting approach to this problem. A couple of things to change:
I don't see where you set your divider index.
You seem to be doing a lot of work with character arrays, so I'm guessing you're coming from a different language. Sticking with Strings will work fine.
You don't address the "teens". This looks like a simple oversight.
I've added those fixes while attempting maintain the original approach:
public static void main(String [] args) {
Scanner scInput = new Scanner(System.in);
String word = scInput.nextLine();
int total = 0;
int tensValue = 0; //number's tens value (i.e. 30)
int onesValue = 0; //ones value (i.e. 3)
int divider = word.indexOf('-');
String tens = null;
String ones = null;
if (divider != -1) {
tens = word.substring(0, divider);
ones = word.substring(divider + 1);
} else {
ones = word;
}
//searches for matches in String array for tens
if (tens != null) {
for (int u = 0; u < wTENS.length; u++) {
if (tens.equals(wTENS[u])) {
tensValue = nTENS[u];
total += tensValue;
}
}
}
//searches for matches in String array for ones
for(int u = 0; u < wONES.length; u++) {
if (ones.equals(wONES[u])) {
onesValue = nONES[u];
total += onesValue;
}
}
// if a "teen" override what's in total
for(int u = 0; u < wTEENS.length; u++) {
if (ones.equals(wTEENS[u])) {
total = nTEENS[u];
}
}
System.out.println(total);
}
Currently I have a method that asks user for an input string but only outputs the first 16 characters! The method is supposed to take in any length of string then output the characters in 4x4 blocks after it does the following: first row remains the same. Shift the second row one position to the left, then shifts the third row two positions to the left. Finally, shift the fourth row three positions to the left. As of now it will only output the first 4x4 block
Also I am not sure how I can change the method so it doesnt ask for user input
I would like it to use a given string like:
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
"WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO" is the given encrypted string I would like to use. but without asking for user input..I keep getting errors and incorrect outputs..please show how I might fix this
code I am using:
public class shiftRows {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] input= new String[4];
String[] output= new String[4];
System.out.println("Enter a String");
String inputStr = sc.next();
for (int i = 0, n = 0; i < 4; i++, n+=4) {
input[i] = inputStr.substring(0+n, 4+n);
}
// -
output[0] = input[0];
for(int i=1; i<4; i++)
{
output[i] = Shift(input[i],i);
}
for(int i=0; i<4; i++)
{
System.out.println(output[i]);
}
}
public static String Shift(String str, int shiftNum)
{
char[] out = new char[4];
if(shiftNum==1)
{
out[0]=str.charAt(1);
out[1]=str.charAt(2);
out[2]=str.charAt(3);
out[3]=str.charAt(0);
}
if(shiftNum==2)
{
out[0]=str.charAt(2);
out[1]=str.charAt(3);
out[2]=str.charAt(0);
out[3]=str.charAt(1);
}
if(shiftNum==3)
{
out[0]=str.charAt(3);
out[1]=str.charAt(0);
out[2]=str.charAt(1);
out[3]=str.charAt(2);
}
return new String(out);
}
}
Here's a good way to do it :
import java.util.Scanner;
public class shiftRows {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inputStr = "WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO";
for (int i = 0 ; i < inputStr.length() ; i++){
System.out.print(inputStr.charAt(i));
if ((i + 1)%4 == 0) System.out.println();
}
}
}
If you want to stock it into a String, just concatenate at each loop and add a "\n" each time the if test is valid.
I'm trying to use i++ to store certain parts of an array in a loop. But instead of incrementing by 1, I really need it to increment by 2.
For example:
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JOptionPane;
public class PeerTutoring
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
int a = 0;
int b = 1;
String name, degree;
String line;
line = JOptionPane.showInputDialog("Inputs");
String[] userinput = line.split("\\s+");
for(int i = 0; i < userinput.length; i++)
{
name = userinput[a];
degree = userinput[b];
a+=2;
b+=2;
}
}
public static String sort(String name)
{
String tutors = "Tutor List";
ArrayList<String> names = new ArrayList<String> ();
names.add(userinput[0]);
names.add(userinput[2]);
names.add(userinput[4]);
names.add(userinput[6]);
names.add(userinput[8]);
names.add(userinput[10]);
names.add(userinput[12]);
names.add(userinput[14]);
names.add(userinput[16]);
names.add(userinput[18]);
}
}
I want a to start as 0 and b as 1, and then each time I would like it to increase by two. (Since the names are each one is seperated by a space) I think I'm going to have to incorporate something along the lines of userinput[a + 1]. But I just wanted to know if there was a simpler way.
for(i=0, i < linesize; i += 2)
As a side note, make sure to initialize your variables outside the loop if you are planning to use them after, or they will be lost.
int a = 0;
int b = 1;
String name, degree;
for(i=0, i < linesize; i += 2)
{
int linesize = line.size();
String line;
line = JOptionPane.showInputDialog("Please enter tutor name and
their highest earned degree.");
String[] userinput = line.split("\\s+");
name = userinput[a];
degree = userinput[b];
a++;
b++;
}
Your options are:
i++; i++; (Which you can't use in the for loop construct since you need a single statement.)
i += 2;
i = i + 2;
String line;
line = JOptionPane.showInputDialog("Please enter tutor name and
their highest earned degree.");
String[] userinput = line.split("\\s+");
for(int i=0, i < userinput.length; ){
String name = userinput[i++];
String degree = userinput[i++];
...
}