i want to print out the four chinese letters over and over again one at a time
package matrixArrayLoop;
public class MatrixArrayLoop {
public static void main(String[] args) {
char[] kai = {'开', '凯', '開', '楷'};
int i=0;
for(i=0;i<kai.length;i++)
System.out.println(kai[i]);
if(i==kai.length)
i=0;
}
}
i used a while loop with an if and bracketed them so they would run
char[] kai = {'开', '凯', '開', '楷'};
int i=0;
while(i<=kai.length) {{{
System.out.println(kai[i]);}
i++;}
if(i==kai.length)
i=0;}
Related
This is the my code and the problem is using array i am taking names and their marks input and want to print then serially but the name accepting part is not working it is taking number inputs but not the names
import java.util.Scanner;
public class ST_test
{
public static void main(String[] args)
{
int i;
Scanner sc= new Scanner(System.in);
String a[]= new String[5];
int num[]= new int[5];
for(i=0;i<5;i++)
{
System.out.println("position mrks"+i);
num[i]=sc.nextInt();
System.out.println("position name "+i);
a[i]=sc.nextLine();
}
for(i=0;i<5;i++)
{
System.out.print(" "+a[i]+" ");
System.out.print(" "+num[i]+" ");
}
}
}
I used to encounter this error early on in my Java journey. The problem is with the Scanner class, probably a bug.
The solution that I used was to create 2 scanner class objects. One for the numeric values and the other for String values. Here is the modified code:-
import java.util.Scanner;
public class ST_test
{
public static void main(String[] args)
{
int i;
Scanner sc= new Scanner(System.in);
Scanner sc1 = new Scanner(System.in); // new scanner object for Strings
String a[]= new String[5];
int num[]= new int[5];
for(i=0;i<5;i++)
{
System.out.println("position mrks"+i);
num[i]=sc.nextInt();
System.out.println("position name "+i);
a[i]=sc1.nextLine();
}
for(i=0;i<5;i++)
{
System.out.print(" "+a[i]+" ");
System.out.print(" "+num[i]+" ");
}
}
}
While this helps, it would be better to switch to BufferedReader and BufferedWriter class :)
public class ShoppingList{
String store;
int noItems;
String[]itemNames;
int [] itemCounts;
ShoppingList(){
store="";
noItems=0;
itemNames=new String [100];
itemCounts= new int [100];
}
ShoppingList(String str, int no){
store=str;
noItems=no;
}
public String [] addItem(String article, int number ){
for(int i=0; i<itemNames.length-1; i++){
itemNames[i]=article;
itemCounts[i]=number;
}
return itemNames;
}
public int noTotalItems(){
int anzahl=0;
noItems=anzahl;
for(int m=0; m<itemCounts.length-1; m++){
anzahl=anzahl+itemCounts[m];
}
return anzahl;
}
public int getNumberOf(String produkt){
int zahl=0;
for(int k=0; k<itemNames.length-1; k++){
if(itemNames[k]==produkt){
zahl=itemCounts[k];
return zahl;
}
}
return zahl;
}
public String [] toString(ShoppingList l){
return itemNames;
}
}
**public class ShoppingListTest{
public static void main (String [] args){
ShoppingList l=new ShoppingList("Supermarkt", 100);
l.addItem("Prosecco", 3);
l.addItem("Milk", 4);
l.addItem("Wine", 5);
l.addItem("Eggs", 4);
Out.println(l);
Out.println("#total items: "+l.noTotalItems());
Out.println("#Milk: "+l.getNumberOf("Milk"));
Out.println("#Wine: "+l.getNumberOf("Wine"));
}
}**
Hi guys! I would be really thankful, if you can help me to solve my problem. This is my code with all classes, but when I compile the ShoppingListTest, I get the following Error: "Exception in thread "main" java.lang.NullPointerException
at ShoppingList.addItem(ShoppingList.java:25)
at ShoppingListTest.main(ShoppingListTest.java:5)"
I am not allowed to create Lists I have to add the items to the String array"itemNames".
This line: ShoppingList(String str, int no){ needs to change to: ShoppingList(String str, int no) { this(); // <-- HERE.
Basically, in your test you are using a construct which does not initialise the required arrays, thus causing them to be null.
Calling this(), in your parametrized constructor will call the parameterless constructor you have, which in turn, initialises the required arrays and other variables.
Write a program that shall calculate the vocabulary richness of a text in a file and the frequency of the most common word. The vocabulary richness is the number of words in the text divided by the number of distinct words. The frequency of a word is the number of times the word is mentioned in the text divided by the total number of words in the text.
Define and implement class WordCounter with two private fields String word and int count, constructor WordCounter(String word), and public methods String getName(), int getCount(), and void addToCounter().
Define and implement class Corpus (as in text corpus) with one private field ArrayList<WordCounter> words, constructor Corpus(BufferedReader infile), and public methods double getVocabularyRichness() and String getMostFrequentWord().
Implement a test program (as the public static void main method in Corpus) that reads all files in a specific folder, creates a Corpus object from each (previously opened) file, and saves the requested statistics into another file stats.csv. You can either create a new Corpus object for each file or define an ArrayList<Corpus> of the corpora.
Each line of the CSV file must consist of three fields separated by commas (but no spaces!): the file name, the vocabulary richness, and the most frequently used word. Run your program on all Shakespeare's plays. Submit the CSV file together with the Java file.
I wrote what I think is the correct implementation of the HW problem because it works properly for some of the text files, however only the words.get(i).getName() (I tested with words.get(i).getCount()) method will print a blank space for some of the files. I have tried everything, and can't seem to figure it out. Can you please give me a hint or some guidance as to how to fix this issue?
public class Corpus {
private ArrayList<WordCounter> words = new ArrayList <WordCounter>() ;
Corpus(BufferedReader infile){
String ln;
try {
while((ln = infile.readLine()) != null) {
for (String word : ln.toLowerCase().split("([,.\\s]+)")) {
int reference = 0;
for(int i = 0; i < words.size(); i++) {
if (word.equals(words.get(i).getName())) {
reference++;
words.get(i).addToCounter();
} }
if (reference==0) { words.add(new WordCounter(word)); }
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public double getVocabularyRichness() {
int word_count=0;
for(int i = 0; i < words.size(); i++) {
word_count=word_count+words.get(i).getCount();
}
return (double)word_count/(double)words.size();
}
public String getMostFrequentWord() {
String winner = "*AN ERROR OCCURRED*";
int max_count = 0;
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getCount() > max_count){
max_count = words.get(i).getCount();
}
}
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getCount() == max_count){
winner = words.get(i).getName();
}
}
//winner="Test " + String.valueOf(words.get(i).getName());;
//return String.valueOf(max_count);
return winner;
}
public static void main(String [] args) throws Exception{
BufferedWriter writer = null;
File folder_location = new File("/Users/joaquindelaguardia/Desktop/Shakespeare");
File[] file_array = folder_location.listFiles();
for(File iteration_file: file_array) {
FileReader current_file = new FileReader(iteration_file);
BufferedReader infile = new BufferedReader(current_file);
Corpus obj1 = new Corpus(infile);
String file_name = iteration_file.getName();
String frequent_word = obj1.getMostFrequentWord();
String vocabulary_richness = String.valueOf(obj1.getVocabularyRichness());
System.out.println(file_name);
System.out.println(frequent_word);
System.out.println(vocabulary_richness);
System.out.println("-----------------------------");
//FileWriter file_writer = new FileWriter("/Users/joaquindelaguardia/Desktop/stats.csv");
//writer = new BufferedWriter(file_writer);
//String output = file_name+", "+frequent_word+", "+vocabulary_richness + "\n";
//writer.append(output);
}
//writer.close();
}
}
public class WordCounter {
private String word;
private int count=1;
WordCounter(String word){
this.word=word;
}
public String getName() {
return word;
}
public int getCount() {
return count;
}
public void addToCounter() {
count++;
}
}
Im testing the information by printing before appending to file, and as you can see with the small fragment of the output included below, for some cases it prints the most common word (and) while in the second case it doesn't print anything.
shakespeare-lovers-62.txt
and
2.2409948542024014
shakespeare-julius-26.txt
6.413205537806177
I'm trying to get the mid, first & last character of a string. Here is what i've done. I'm not sure about what exactly need to be done.
import java.util.*;
class Test11{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String input=sc.nextLine();
int length=input.length();
int even_odd=length%2;
if(even_odd==1){
int mid=length/2;
char mid_letter[]=input.toCharArray();
int first=0; int last=length;
System.out.println(mid_letter[mid]+mid_letter[first]+mid_letter[last]);
}
else System.out.println("Even String has no mid point. Try Again!");
}
Your last variable needs to be
last = length-1
since java is '0 based'.
In this code, how do I call an array globally for other methods to use?
Background info on my code, we are asked to scan a file that contains DNA strands then translating it to an RNA Strand.
I receive the error: " cannot find symbol - variable dna " when i call the dna array on the translation method (it can't find dna.length) for(int i=0; i < dna.length; i++){
public class FileScannerExample
{
public static void main(String[] args) throws IOException
{
//This is how to create a scanner to read a file
Scanner inFile = new Scanner(new File("dnaFile.txt"));
String dnaSequence = inFile.next();
int dnalength = dnaSequence.length();
String[] dna = new String[dnalength];
for(int i=0; i<=dna.length-2 ; i++)
{
dna[i]=dnaSequence.substring(i,i+1); //looking ahead and taking each character and placing it in the array
}
dna[dna.length-1]=dnaSequence.substring(dna.length-1); //reading the last spot in order to put it in the array
//Testing that the array is identical to the string
System.out.println(dnaSequence);
for(int i = 0 ; i<=dna.length-1; i++)
{
System.out.print(dna[i]);
}
}
public void translation()
{
for(int i=0; i < dna.length; i++){
//store temporary
if (dna[i] = "A"){
dna[i] = "U";
}
if(dna[i] = "T"){
dna[i] = "A";
}
if(dna[i] = "G"){
dna[i]= "C";
}
if(dna[i] = "C"){
dna[i] = "G";
}
}
}
}
you need to bring the symbol into scope before you can reference it. you can do this, either by pulling it up into a higher scope (as a field in the class), or by sending it into the local scope by passing it as a method parameter.
As a class member:
public class Test
{
private String myField;
void A() {
myField = "I can see you";
}
void B() {
myField = "I can see you too";
}
}
As a method parameter:
public class Test
{
void A() {
String myVar = "I can see you";
System.out.println(myVar);
B(myVar);
}
void B(String param) {
param += " too";
System.out.println(param);
}
}
Note that in order to see an instance member, you must be referencing it from a non-static context. You can get around this by declaring the field as static too, although you want to be careful with static state in a class, it generally makes the code more messy and harder to work with.