string accept error name accept part getting skipped - arrays

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 :)

Related

Scanner automatically assigned first input to an empty string, why is that?

I am very much a beginner so forgive me if I made an obvious mistake. I tried to create a HashMap of a student list by getting input from user via scanner but somehow the scanner skipped the first key and automatically assigned it to an empty string?
Here's my code in details:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inputvalue = new Scanner(System.in);
HashMap<Integer, String> studentName = new HashMap<Integer, String>();
String student;
int counter = 1;
int classSize;
System.out.println("Enter class size: ");
classSize = inputvalue.nextInt();
do {
System.out.println("Enter " + counter + " student name: ");
student = inputvalue.nextLine();
studentName.put(counter, student);
counter++;
} while(counter <= classSize);
System.out.println(studentName);
}
I tried using a for loop instead but it didn't work either. Please elaborate to me what made the scanner skip first key and how to fix this bug. Thank you so much in advanced

How to fix method printing null for some iterations?

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

make a for loop update twice

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;}

Java loops using a Scanner class and I can use breaks

I am trying to figure out how to use the scanner class with a loop. I cannot use break as part of my code. I am unsure how close I am, but any help would be much appreciated.
import java.util.Scanner;
public static void main(String[] args) {
Scanner i = new Scanner(System.in);
System.out.print("Please enter a number between 1 and 10: ");
int number = i.nextInt();
boolean value = number>=1 && number <=10;
while (number >=1 && number <=10){
System.out.println ("Good Job!");
}
if (number <=1 && number >=10 )
continue;
{System.out.print ("You have entered an incorrect number. Please try again");
System.out.println("Please try again:");
Scanner r = new Scanner(System.in);
return;
}
The Scanner class can be used like this:
import java.util.Scanner;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// now loop while the scanner is available
while(scanner.hasNext()) {
// print out every single number input from standard input
System.out.println("Scanner inputed from stdin is " + Integer.toString(scanner.nextInt());
}
}
You can do like this:
import java.util.Scanner;
import java.util.Stack;
public class ScannerDemo {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String next = scan.next();
if("quit".equals(next)) break;
System.out.println("Element: " + next);
}
scan.close();
}
}
Press quit to exit.

How to return a value of a variable so that another class can use that value to access a value in an array

I am trying to return a variable 'i' which stores the position of a value in an array.I want to return the value of 'i' so that the other classes can use the value to access another value in an array(this might sound a little dumb).How do I do that ?
import java .io.*;
public class Login{
public int i;
public void Menu1()throws IOException
{
int flag=0;
int goal=0;
String p;
String Username[]={"Mohit","Rahul","Mehul","Kevin","Tony"};
String MNumber[]={"8720765181","8659133560","9869206216","9767445692","9967129878"};
String Password[]={"1234","5678","9012","3456","7890"};
int Balance[]={20,124,256,67,512};
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
do
{
System.out.println("Enter your Username");
String username=br.readLine();
for(i=0;i<5;i++)
{
if(username.equals(Username[i])){
flag=1;
break;
}}
if(flag==1)
{
System.out.println("Enter your password");
p=br.readLine();
if(p.equals(Password[i]))
{
goal=1;
}
if(goal==1)
{
System.out.println("Password matched");
System.out.println("Welcome Mr."+Username[i]+".Your Registired Mobile number is "+MNumber[i]);
System.out.println("It has a balance of Rs."+Balance[i]+" which will expire on 20th August 2025");
goal=1;
Second_Menu sm=new Second_Menu();
sm.main();
}
else
System.out.println("Incorrect password,please retry");
}
else
System.out.println("incorrect username,please retry");
}while(goal!=1);
}
}
This is the class in which I want to call the value.
import java.io.*;
public class Recharge
{
public void recharge()throws IOException {
int Balance[]={20,124,256,67,512};
int chcea;
double recAmt=0;
double u;
int i=0;
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Choose an option");
System.out.println("1.Recharge your account");
System.out.println("2.Return to Main Menu");
chcea=Integer.parseInt(br.readLine());
System.out.println("You choose option number "+chcea+".Proceed(y or n)");
String answ=br.readLine();
switch(answ)
{
case "y":
switch(chcea)
{
case 1:System.out.println("For the first time India a Mobile Service Provider gives you the freedom to recharge with a coustom amount");
System.out.println("Please enter a recharge amount");
recAmt=Double.parseDouble(br.readLine());
System.out.println("Your entered amount is Rs."+recAmt+".Proceed(y or n)");
String optyn=br.readLine();
switch(optyn)
{
case "y":System.out.print("Please wait");
for(int wait=0;wait<=5;wait++);
{for(int tmp=0;tmp<=999999999;tmp++){}
System.out.print(".");
}
System.out.println("Your account has been successfully recharged.");
System.out.println("Your new Balance is Rs."+(Balance[i]+recAmt));
break;
case "n":break;
default:System.out.println("Please enter a valid choice");
break;
}
case 2 :Second_Menu sm= new Second_Menu();
sm.main();
break;
}
case"n":break;
}
}
}
I want to return the value of 'i' from the first class so that the second class can use it to access the value in the array 'Balance[]' for the right user.I also want that after recharge the value of balance of that user(i) changes to the new recharged amount.
if you make the int i public other classes can use it and if you make it static, if a constructor or something changes it, it changes the value for the whole program
try to make the int i a
public static int i

Resources