I want to build a program that takes inputs a set number of strings (int T) via scanner and stores them inside an arraylist. Then I want to check the input to see if it matches or contains characters from another Array.
Example Input:
1
ABCD
Example Output:
Good
Problem: When I run the code I do not get a "Good" or "Bad" output, instead I get an error and the debug console launches.
Exact Error:
Scanner.throwFor() line: not available. Source not found
import java.io.*;
import java.util.*;
public class RNA {
public static void main(String[] args) {
String X [] = {"A", "B", "C", "D"}; // Array to be checked against
List<String>A = new ArrayList(); // ArrayList to be imported
Scanner q = new Scanner(System.in);
System.out.println("How Many Sets of Strings do you want?");
int T = q.nextInt(); // number of Strings to be imported
q.nextInt(); // allows to reset Scanner
for(int i = 0 ; i < T; i ++){
A.add(q.nextLine()); //imports stuff to add to array A
}
Iterator<String> ListChecker = A.iterator();
while((ListChecker.hasNext())) { //continues as long as DNA Check has an index to go to
if (A.contains(X)) { //Checks A for X
System.out.println("Good"); //Prints out good if the check is good
}
else {
System.out.println("Bad"); //Prints out bad if the check is bad
}
}
}
}
Couple of issues:
You should use q.next(); to consume the new line character instead of q.nextInt(); which is basically you are getting input mismatch exception.
You are doing list.contains(Array) which is not supported. If you wish to check for each input from user whether its there in Array X then you should probably do something like:
List<String> list = Arrays.asList(X);
while((ListChecker.hasNext())) { //continues as long as DNA Check has an index to go to
if (list.contains(ListChecker.next())) { //Checks A for X
System.out.println("Good"); //Prints out good if the check is good
} else {
System.out.println("Bad"); //Prints out bad if the check is bad
}
}
You check if A contains an Array of String (directly the String[] object), not if it contains a String inside this array (What is inside this String[]).
Replace it with
List<String> result = Arrays.asList(X);
So you have a List from your Array, and then use contains
result.contains(A)
Your code could look like this
List<String> xAsList = Arrays.asList(X);
// [....]
while((ListChecker.hasNext())) { //continues as long as DNA Check has an index to go to
if (xAsList.contains(ListChecker.next())) { //Checks A for X
System.out.println("Good"); //Prints out good if the check is good
} else {
System.out.println("Bad");//Prints out bad if the check is bad
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class RNA {
public static void main(String[] args) {
String X [] = {"A", "B", "C", "D"}; // Array to be checked against
List<String>A = new ArrayList<String>(); // ArrayList to be imported
Scanner scanner = new Scanner(System.in);
System.out.println("How Many Sets of Strings do you want?");
int T = scanner.nextInt(); // number of Strings to be imported
scanner.nextLine();
for(int i = 0 ; i < T; i ++) {
String nextLine = scanner.nextLine();
A.add(nextLine); //imports stuff to add to array A
}
scanner.close();
Iterator<String> ListChecker = A.iterator();
while((ListChecker.hasNext())) { //continues as long as DNA Check has an index to go to
if (A.contains(X)) { //Checks A for X
System.out.println("Good"); //Prints out good if the check is good
}
else {
System.out.println("Bad"); //Prints out bad if the check is bad
}
ListChecker.next();
}
}
}
Try this.
instead of q.nextInt() to use q.nextLine() to reset.
Never use the same scanner for both nextInt() and nextLine(). They bug out. Use two scanners, one for ints, and one for strings. This will fix your program.
Related
So I have been doing competitive programming using java, my code is ACCEPTED in codeforces. But I still think this code doesn't look so good, cause it needs 2 "for loops" to identify the duplication. if it is only one "for loops", it still has duplication in the strings.
This is the problem: https://codeforces.com/problemset/problem/236/A.
So basically, the code will try to find the distinct characters in the strings, then if the length of the string is odd, it will print "IGNORE HIM", else "CHAT WITH HER!".
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String a;
int counter=0;
Scanner sc= new Scanner(System.in);
a=sc.next();
StringBuilder b= new StringBuilder(a);
int count = 0;
for(int i=0;i<b.length();i++)
{
for(int j=i+1;j<b.length();j++) {
if(b.charAt(i)==b.charAt(j)) {
b=b.deleteCharAt(j);
}
}
}
for(int i=0;i<b.length();i++)
{
for(int j=i+1;j<b.length();j++) {
if(b.charAt(i)==b.charAt(j)) {
b=b.deleteCharAt(j);
}
}
}
counter=b.length();
if(counter%2==0)
{
System.out.println("CHAT WITH HER!");
}
else
{
System.out.println("IGNORE HIM!");
}
}
}
You can replace most of this code by this one line:
int count = a.chars().distinct().count();
This transforms you string input into a stream of characters, gets the distinct values and returns the count.
Using streams is a good option. If you want to go plain old route, then you can use a hashset. Basically if character is in hashset, then move to next char, else add to hashset and increase counter by 1.
Building upon and completing #Guillaume's answer
String a = "xiaodao";
String out = a.chars().distinct().count() % 2 == 0 ? "CHAT WITH HER!" : "IGNORE HIM!";
System.out.println(out);
I would use a Hashset because it will contain a distinct set of all characters you add. You can just go through the list once and use size() to get the unique character count.
...
Set<Character> characters = new HashSet<>()
for(int i=0;i<b.length();i++)
{
characters.add(b.charAt(i));
}
if(characters.size()%2==0) {
...
I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}
gets a single letter from the user. This method validates that it’s either a valid letter or the quit character, ‘!’. It'll eventually keep asking for characters, then once the user is done, they'll type ‘!’ to make the loop end and move on to printing their list of chars
public static String isValidLetter(){
char[] charArray;
charArray = new char[11];
charArray[0] ='C';
charArray[1] ='E';
charArray[2] ='F';
charArray[3] ='H';
charArray[4] ='I';
charArray[5] ='J';
charArray[6] ='L';
charArray[7] ='O';
charArray[8] ='P';
charArray[9] ='S';
charArray[10] ='T';
charArray[11] ='U';
String input;
char letter;
Scanner kb = new Scanner(System.in);
System.out.println("Enter a single character: ");
input=kb.nextLine();
letter = input.charAt(0);
Reading the strings from console.. type "a", enter, "b", enter, "!", enter
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scann = new Scanner(System.in);
List<String> letterWords = new LinkedList<String>();
String str = null;
while (!"!".equals(str)) {
str = scann.next();
letterWords.add(str);
}
for (String word : letterWords) {
System.out.println(word);
}
scann.close();
}
}
If you just want to have a "collection" of valid characters, then you also could use a String instead of an array. It would be much easier to search in it and it avoids errors like in your example (you've initialized your array with size of 11, but you're inserting 12 elements):
public static boolean isValidLetter(final char character) {
final String validCharacters = "CEFHIJLOPSTU";
return validCharacters.contains(String.valueOf(character));
}
This method expects a single char and returns true if it is valid, false otherwise. Please mind, that this check is case sensitive.
You could use that method like this:
final Scanner scan = new Scanner(System.in);
String input;
while (!(input = scan.nextLine()).equals("!")) {
if (!input.isEmpty() && isValidLetter(input.charAt(0))) {
// ... store valid input
System.out.println("valid");
}
}
This loop requests user input until he enters !. I've omitted the storing part. It is up to you to do this last part.
Modify your isValidLetter method to return boolean.
Modify your isValidLetter method to get a char as a parameter.
In isValidLetter, try to find a letter by using a helper function, something like:
static boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
Somewhere in your code where you need the input (or in main for testing), ask for user input (as you already did in isValidLetter). Perform a loop, asking for input, until it is right, or until it is your ending character.
I am not posting the complete solution code on purpose, as it is better for you to play with the code and learn. I only gave directions on how to try; of course it is not the only way, but it fits with what you've already started.
I have 100 text files. 50 of them are called text_H and the other are called text_T. What I would like to do is the following open two text files text_T_1 and text_H_1 and find the number of common words and write it to a text file then open text_H_2 and text_T_2 and find the number of common words....then open text_H_50 and text_T_50 and find the number of common words.
I have written the following code that open two text files and find common words and return the the number of common words between the the two files. The results are written in text file
For whatever reason instead of giving me the number of common word for just the open text files, it gave me the number of of common words for all files. For the example if the number of common words between fileA_1 and fileB_1 is 10 and the number of common words between fileA_2 and fileB_2 is 5, then result I get for number of common word for the second two files is 10+5=15.
I'm hoping someone here can catch whatever it is that I'm missing, because I've been through this code many times now without success. Thanks ahead of time for any help!
The code:
package xml_test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class app {
private static ArrayList<String> load(String f1) throws FileNotFoundException
{
Scanner reader = new Scanner(new File(f1));
ArrayList<String> out = new ArrayList<String>();
while (reader.hasNext())
{
String temp = reader.nextLine();
String[] sts = temp.split(" ");
for (int i = 0;i<sts.length;i++)
{
if(sts[i] != "" && sts[i] != " " && sts[i] != "\n")
out.add(sts[i]);
}
}
return out;
}
private static void write(ArrayList<String> out, String fname) throws IOException
{
FileWriter writer = new FileWriter(new File(fname));
//int count=0;
int temp1=0;
for (int ss= 1;ss<=3;ss++)
{
int count=0;
for (int i = 0;i<out.size();i++)
{
//writer.write(out.get(i) + "\n");
//writer.write(new Integer(count).toString());
count++;
}
writer.write("count ="+new Integer(temp1).toString()+"\n");
}
writer.close();
}
public static void main(String[] args) throws IOException
{
ArrayList<String> file1;
ArrayList<String> file2;
ArrayList<String> out = new ArrayList<String>();
//add for loop to loop through all T's and H's
for(int kk = 1;kk<=3;kk++)
{
int count=0;
file1 = load("Training_H_"+kk+".txt");
file2 = load("Training_T_"+kk+".txt");
//int count=1;
for(int i = 0;i<file1.size();i++)
{
String word1 = file1.get(i);
count=0;
//System.out.println(word1);
for (int z = 0; z <file2.size(); z++)
{
//if (file1.get(i).equalsIgnoreCase(file2.get(i)))
if (word1.equalsIgnoreCase(file2.get(z)))
{
boolean already = false;
for (int q = 0;q<out.size();q++)
{
if (out.get(q).equalsIgnoreCase(file1.get(i)))
{
count++;
//System.out.println("count is "+count);
already = true;
}
}
if (already==false)
{
out.add(file1.get(i));
}
}
}
//write(out,"output_"+kk+".txt");
}
//count=new Integer(count).toString();
//write(out,"output_"+kk+".txt");
//write(new Integer(count).toString(),"output_2.txt");
//System.out.println("count is "+count);
}//
}
}
Let me show you what your code is doing and see if you can spot the problem.
List wordsInFile1 = getWordsFromFile();
List wordsInFile2 = getWordsFromFile();
List foundWords = empty;
//Does below for each compared file
for each word in file 1
set count to 0
compare to each word in file 2
if the word matches see if it's also in foundWords
if it is in foundWords, add 1 to count
otherwise, add the word to foundWords
//Write the number of words
prints out the number of words in foundWords
Hint: The issue is with foundWords and where you are adding to count. arunmoezhi's comment is on the right track, as well as board_reader's point #3 in his answer.
As it stands now, your code is doing nothing meaningful with any of the count variables
use more meaningful variable names in loops, makes code readable.
use HashMap-s instead of ArrayList-s, will make code smaller, faster and a lot easier. will use less memory too in case words are repeated several times in files.
should not you increase count in already==false case?
could not figure out point of calculating count 3 times in write method, is not count equal to out.size()?
probably there are more too...
Hi I'm in a programming class over the summer and am required to create a program that reads input from a file. The input file includes DNA sequences ATCGAGG etc and the first line in the file states how many pairs of sequences need to be compared. The rest are pairs of sequences. In class we use the Scanner method to input lines from a file, (I read about bufferedReader but we have not covered it in class so not to familiar with it) but am lost on how to write the code on how to compare two lines from the Scanner method simultaneously.
My attempt:
public static void main (String [] args) throws IOException
{
File inFile = new File ("dna.txt");
Scanner sc = new Scanner (inFile);
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
comparison(DNA1,DNA2);
}
sc.close();
}
Where the comparison method would take a pair of sequences and output if they had common any common characters. Also how would I proceed to input the next pair, any insight would be helpful.. Just stumped and google confused me even further. Thanks!
EDIT:
Here's the sample input
7
atgcatgcatgc
AtgcgAtgc
GGcaAtt
ggcaatt
GcT
gatt
aaaaaGTCAcccctccccc
GTCAaaaaccccgccccc
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
gctagtacACCT
gctattacGcct
First why you are doing:
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
While you have pairs only in one line not pairs and two lines of input, but number of lines once? Move reading pairs from that while looop and parse it to int, then it does not matter but you could use it to stop reading lines if you know how many lines are there.
Second:
throws IOException
Might be irrelevant but, really you don't know how to do try catch and let's say skip if you do not care about exceptions?
Comparision, if you read strings then string has method "equals" with which you can compare two strings.
Google will not help you with those problems, you just don't know it all, but if you want to know then search for basic stuff like type in google "string comparision java" and do not think that you can find solution typing "Reading two lines from an input file using Scanner" into google, you have to go step by step and cut problem into smaller pieces, that is the way software devs are doing it.
Ok I have progz that somehow wokrked for me, just finds the lines that have something and then prints them out even if I have part, so it is brute force which is ok for such thing:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class program
{
public static void main (String [] args) throws IOException
{
File inFile = new File ("c:\\dna.txt");
Scanner sc = new Scanner (inFile);
int pairs = Integer.parseInt(sc.nextLine());
for (int i = 0; i< pairs-1; i++)
{
//ok we have 7 pairs so we do not compare everything that is one under another
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
Boolean compareResult = comparison(DNA1,DNA2);
if (compareResult){
System.out.println("found the match in:" + DNA1 + " and " + DNA2) ;
}
}
sc.close();
}
public static Boolean comparison(String dna1, String dna2){
Boolean contains = false;
for (int i = 0; i< dna1.length(); i++)
{
if (dna2.contains(dna1.subSequence(0, i)))
{
contains = true;
break;
}
if (dna2.contains(dna1.subSequence(dna1.length()-i,dna1.length()-1 )))
{
contains = true;
break;
}
}
return contains;
}
}