So I am pretty sure I am using next and hasNext incorrectly... I am attempting to input a string of ACGT characters and then count the individual resulting letters. Thanks in advance.
import java.util.Scanner;
public class A1Novice {
public static void main(String[] args){
String input = "";
Scanner s = new Scanner(System.in);
Scanner j = new Scanner(input);
System.out.println("Enter nucleobases (enter end when done)");
while(true){
input = s.next() + input;
if(s.next().contains("end")){
break;
}
}
process(j, input);
}
public static void process(Scanner j, String input){
int a = 0, c = 0, g = 0, t = 0;
while(j.hasNext()){
if (j.next()=="A"){
a++;
}
else if(j.next()=="C"){
c++;
}
else if(j.next()=="G"){
g++;
}
else if(j.next()=="T"){
t++;
}
else{
System.out.println("A count: " + a);
System.out.println("C count: " + c);
System.out.println("G count: " + g);
System.out.println("T count: " + t);
break;
}
}
}
}
As already written you have to put your next element in a local variable.
This is not enough however: please never use ==
to compare strings. Use String's method equals
instead or even equalsIgnoreCase
.
You should use something like :
String val = j.next();
if(val.equals("A")){ // you could use val.equalsIgnoreCase("A") to be case insensitive
...
} else if (val.equals("B")){
...
As suggested in aljipa's answer, you you to use a switch. If you want your test to be case insensitive can can also write something like:
String val = j.next();
switch (val.toUpperCase()) {
case "A":
a++;
break;
case "B":
...