made a program that counts and outputs users based on user input. I want the program to display the names one below the other with the line break but stuck on how to. the code is below:
package uk.ac.reading.cs2ja16.Glen.Stringtest;
import java.util.Arrays;
import java.util.Scanner;
public class stringnames {
public static String[] countNames (String names) {
// Create Scanner object
#SuppressWarnings("resource")
Scanner names1 =new Scanner(System.in);
// Read a string
String read= names1.nextLine();
// Split string with space
String numPeople[]=read.trim().split(" ");
System.out.println("The Number of names inputted is: "+ numPeople.length);
return numPeople;
}
public static void main(String[ ] args){
System.out.println("Enter the amount of names you want(make sure you make space for each name):\n");
String[] namesout = countNames(null);
System.out.println(Arrays.toString(namesout));
}
}
First of all, the countNames method does not need a parameter, so delete that String names thingy in the method declaration. And delete the word null in your method call.
Now, you can either use a for loop or use one of the methods in the new Stream API if you're using Java 8.
I'll show you both ways.
For loop:
for (String name: namesout) {
System.out.println(name);
}
the println method automatically adds a new line character at the end of the string that you want to print.
Stream API:
Arrays.stream(namesout).forEach(System.out::println);
Related
I'm setting a java application that has 3 separately saved classes WordApp, WordProcessor, and WordType. WordApp reads the file and is suppose to pass the data to the other classes. I can read the file but I can't the data to pass to the other classes. How to pass the information via a string?
I've searched this and every example I find has all the classes saved to the same file. I'm using textpad and I tried passing the string to the WordProcessor class which has constructs an ArrayList of WordType objects. This method is not working for me.
This is the first part of the WordApp class for reading the file.
import java.io.*; // Import IO package
import java.util.Scanner; // Import Scanner utility
import java.util.ArrayList; // Import ArrayList utility
public class WordApp // Declared WordApp Class
{
public static void main (String[] args) // Main
{
// Declared Variables
String again;
String initial = "";
String inputFileName;
String outputFileName;
// Declared Objects
Scanner input = new Scanner(System.in);
do
{
try
{
System.out.println(" Welcome to the Word Processor App! ");
System.out.println("**********************************************************************\n");
System.out.println("Enter file names with .txt extension.");
System.out.print("Please Enter File Name to Read: ");
inputFileName = input.nextLine().trim();
File mcFile = new File(inputFileName);
Scanner scan = new Scanner(mcFile);
System.out.println("Enter file names with .txt extension.");
System.out.print("Please Enter File Name to Save: ");
outputFileName = input.nextLine().trim();
File deFile = new File(outputFileName);
PrintWriter out = new PrintWriter(deFile);
System.out.println("Reading file...\n");
while(scan.hasNext())
{
initial = scan.next();
}
scan.close();
System.out.println("Scanning Paragraph.....\n");
WordProcessor x = new WordProcessor();
x.addWord(initial);
I'm trying to pass the words in the file here:
import java.util.ArrayList;
import java.util.Collections;
public class WordProcessor
{
private ArrayList<WordType> words;
private int totSentences;
private int totUnique;
public WordProcessor()
{
words = new ArrayList<WordType>();
totSentences = 0;
totUnique = 0;
}
and here:
public class WordType implements Comparable
{
// instance data
private String word;
private int count;
private int syllables;
// Constructors
public WordType(String newWord)
{
word = newWord;
count = 1;
syllables = countSyllables();
}
I'm expecting that that words pass to the other classes but when I save the file it is blank. Sorry if I didn't post the code correctly
You're reading the file and getting the items it holds but discarding all but the last.
while(scan.hasNext()) {
initial = scan.next();
// You do **nothing** with the String read in
}
scan.close();
System.out.println("Scanning Paragraph.....\n");
WordProcessor x = new WordProcessor();
x.addWord(initial); // until here where you add the last one
Instead create the WordProcessor object before the while loop, and add words within the while loop
WordProcessor x = new WordProcessor();
while(scan.hasNext()) {
initial = scan.next();
x.addWord(initial);
}
scan.close();
There may be other errors, especially problems in your code not shown (addWord(...) comes to mind), but this error was immediately obvious.
Also what type of looping are you doing and why? You appear to have a do-while loop -- why? Again if this does not solve your problem, then you still will need to create and post a valid mcve so we don't have to guess what the problem truly is. Please understand that I am not asking for all your code but rather for something completely different -- please read the link and understand it fully if your problem has not been solved and you still need help.
So far, every time I have used a scanner object I have assigned the input to a new string variable like:
String word = reader.nextLine();
and then if I want to use the input in an if statement I would write:
if(word.isEmpty()){}
but this seems almost like an extra step instead of just doing:
if(reader.nextLine().isEmpty()){}
however, when I try this I usually get some kind of problem in my program function. Is there a way to do this by skipping the String that I will never use again?
This is the code that I am trying to use without the String objects:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class WordsInReverseOrder {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
while(true){
System.out.println("Type a word: ");
if(reader.nextLine().isEmpty()){
Collections.reverse(words);
for(String word1 : words){
System.out.println(word1);
}
break;
}
else{
words.add(reader.nextLine());
}
}
}
}
If you need to do something with the scanned word and want to check isEmpty() than you need a variable to access the word twice.
So, if you do more than one thing, you need a variable. If you do just one thing, you can 'inline' the variable.
The answer to your question is 'Yes'. When you do not need the content of the first word / line, the you can 'inline' your variable, which means that there is no need for a variable.
I'm struggling with a specific method which takes in a String parameter. The promptString method will print its parameter to the user as a prompt, and then return a String that is the result of reading the console via the nextLine() method. For this program you will use nextLine() exclusively.
I've prompted the user with a question using a parameter, and then used nextLine to read the string but after that I am a bit lost. How can I get the method to print to the console?
import java.util.*;
public class StarWarsName{
public static void main (String [] args) {
promptString("Enter your first name: ");
}
public static String promptString (String n) {
Scanner console = new Scanner(System.in);
String first = console.nextline();
return first.trim();
}
}
I think you are over-thinking this thing. Just print it to the console.
public static void main(String[]args){
String result = promptString("Enter your first name: ");
System.out.println(result);
}
This essentially is a small code I'm writting for practice that requires me to use StringTokenizer. I've done the same kind of programs before , but now when I store the strings in an array and try to print them it show's a null pointer exception. Any help?
import java.util.*;
public class board1
{
String key;
String m[];
//function to accept the sentence
void getsent()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter a sentence terminated by'.' or '?'");
String take=in.nextLine();
StringTokenizer taken=new StringTokenizer(take);
int numtokens=taken.countTokens();
String m[]=new String[numtokens];
for(int i=0;i<m.length;i++)
{
m[i]=taken.nextToken();
}
for(int i=0;i<m.length;i++)
{
System.out.print(m[i]);
}
}
// function to display
void display()
{
System.out.println("The words seperately right now are:");
for(int i=0;i<m.length;i++)
{
System.out.print(m[i]+"\t");
System.out.println();
}
}
// main to get functions
public static void main(String args[])
{
board1 ob= new board1();
ob.getsent();
ob.display();
}
}
You're shadowing the variable m. Replace
String m[] = new String[numtokens];
with
m = new String[numTokens];
I think because you are shading properties. You have an array called m into which you are putting tokens in getSent, but display is using the m array defined in the class to which you haven't added anything.
Print out the size of m in display, this will show you that you are not adding anything to the property called m.
I'm working on a class that will take user input to assign values to an object created in a source class. Those objects will then be added to an array, which then prints the values on it. However, the "list" under print : list is telling me that I need to initialize the variable. Why is it not recognizing that this is an array even though it seems to work fine in my do loop?
import java.util.Scanner;
import name.Names;
public class NameTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
String entry;
Scanner firstscan = new Scanner(System.in);
Scanner lastscan = new Scanner(System.in);
Scanner codescan = new Scanner(System.in);
Scanner entryscan = new Scanner(System.in);
String first;
String last;
int code;
System.out
.println("This program will prompt you to input first name, +"
+ "last name, and zip code for an individual. Hit \"x\" when finished\n");
do {
System.out.println("Enter first name:");
first = firstscan.nextLine();
System.out.println("Enter last name:");
last = lastscan.nextLine();
System.out.println("Enter zip code:");
code = codescan.nextInt();
Names nm = new Names(first, last, code);
Names[] list = new Names[25];
int count = 0;
list[count] = nm;
count++;
System.out
.println("To quit hit \"X\" or any other key followed by enter to continue:");
entry = entryscan.nextLine();
} while (!(entry.equalsIgnoreCase("x")));
for (Names print : list)
System.out.println(print + "");
}
}
For one, you are instantiating your array inside your loop, that means every time your loop runs through, it creates a new array instead of updating the old one. Then, once you leave your loop, you leave its "scope". That means everything you declare inside the loop is not available outside. The solution is to declare your array outside the loop.
Every block in java has its own scope (defined through brackets). While you can access variables that have been declared outside your block while inside it, it does not work the other way around; as you can see. Just google java scope, and you will understand more. Hope that helps ;)
You will need a method in the class Name that return the first, last name and the zip code because if you just use:
System.out.println(print + "")
You are printing the object Name and no the String that represents the attributes saved in the object.
For example you can have the method in the class Name:
String getFirst()
{
return this.first;
}
And the last line in your class Nametester can be
System.out.println(print.getFirst() + "");