I am creating an array using a while loop. (For reasons why I am creating an array this way, go to https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt) Though once my array (data) is created inside the while loop, I cannot access it outside of the while loop. I was hoping to make it so the user could put in the name of a country, say India, and get the number of mobile users in that country.
String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
while (in1.hasNextLine()){
line = in1.nextLine();
String[] data = line.split("\t");
if (data[1].contains(country) == true){
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return;
}
else{
System.out.println("No country found with that name!");
return;
}
}
The input works if it is inside the loop, but will only work with China because it is the first country in the list. I understand why it is not working correctly, thought I'm unsure how to fix it other than putting the if statement outside of the loop, but if I do that, the statement cannot reach my array. Any suggestions?
The issue is here :
if (data[1].contains(country) == true){
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return;
} else {
System.out.println("No country found with that name!");
return; //<-----ISSUE
}
When return is called in your else clause it terminates the program. What it really needs to do is iterate through the second run of the loop.
Remove the return in your else-statment.
Here's the revised code:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) throws IOException {
String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out
.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
while (in1.hasNextLine()) {
line = in1.nextLine();
String[] data = line.split("\t");
if (data[1].contains(country) == true) {
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return; //<--- will exit after printing ^
}
}
System.out.println("No country found with that name!");
}
}
Here's a sample run: {input} India
Please enter the name of the country you would like to see the mobile users for: India
Country name: India
Mobile phone subscribers: 893,862,000
You are not able to iterate to second line because you are returning the while after first iteration whether it found the country or not.
I would suggest to remove the return statement from the else condition.
I have also used a boolean variable found which will be set once the country is found and No country found message will be appear only if that country is not in list.
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class CountryName {
public static void main(final String[] args) throws IOException {
final String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
final URL pageLocation = new URL(address);
final Scanner in1 = new Scanner(pageLocation.openStream());
final Scanner in = new Scanner(System.in);
boolean found = false;
String line;
System.out
.print("Please enter the name of the country you would like to see the mobile users for: ");
final String country = in.next();
while (in1.hasNextLine()) {
line = in1.nextLine();
final String[] data = line.split("\t");
if (data[1].contains(country) == true) {
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
found = true;
return;
}
}
if (!found) {
System.out.println("No Country Found");
}
in.close();
in1.close();
}
}
On the other note, if you wants to use collections your program will become more concise and easy to read. Here is the same logic with HashMap
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CountryName {
public static void main(final String[] args) throws IOException {
final String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
final URL pageLocation = new URL(address);
final Scanner in1 = new Scanner(pageLocation.openStream());
final Scanner in = new Scanner(System.in);
final Map<String, String> countryMap = new HashMap<String, String>();
while (in1.hasNextLine()) {
final String[] line = in1.nextLine().split("\t");
countryMap.put(line[1], line[2]);
}
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
final String country = in.next();
if (countryMap.containsKey(country)) {
System.out.println("Country Name: " + country);
System.out.println("Mobile phone subscribers: "+ countryMap.get(country));
} else {
System.out.println("No Country found with that name");
}
in.close();
in1.close();
}
}
Try putting
String[] data;
before your loop. That will make its scope greater than just the loop.
Declare data outside "while" but assign it inside.
String address = "https://www.cia.gov/library/publications/the-world- factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
String[] data;
while (in1.hasNextLine()){
line = in1.nextLine();
data = line.split("\t");
if (data[1].contains(country) == true){
System.out.println("Country name: " + data[1]);
System.out.println("Mobile phone subscribers: " + data[2]);
return;
} else{
System.out.println("No country found with that name!");
return;
}
}
Objects.toString(data); // now its visible
Related
I have this code in Java,
package bookpurchased;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Book {
public static void getInputFromScanner() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the Number you want: ");
Short bookId = input.nextShort();
System.out.println("\nBook Price : ");
double bookPrice = input.nextDouble();
System.out.println("The Book Category is: " + bookId);
System.out.println("The Book Price is: " + bookPrice);
input.close();
}
public static void getInputFromReader() {
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
String bookTitle = "";
System.out.print("Enter book title");
here below it:
I want to change the bookCategory from String to char, but if I change, I have received a lots of error. It's like a string when in run but I have to change only a bookCategory from String to char.
String bookCategory = "";
System.out.print("Enter book title");
try {
bookTitle = dataIn.readLine();
bookCategory = dataIn.readLine();
}catch(IOException e) {
System.out.println("Error!");
}
System.out.println("The book title is: " + bookTitle);
System.out.println("The book category is: " + bookCategory);
}
public static void main(String[]args) {
getInputFromReader();
getInputFromScanner();
}
}
You can make of String.toCharArray() i.e., bookCategory.toCharArray() or dataIn.readLine().toCharArray() will give you char[] array.
But you have to intialize the bookCategory to char array or you can print directly the converted char[] array using Arrays.toString()
(I copy-pasted the whole code, but you just have to look at line 28 to 45)
We have to input the surname and the firstname to get the number of votes that the actual person got.
I wrote a code and if I type in the input the first row surname firstname it works nicely(I get 19, which on is the correct number), but every time when I try to write another name in the input field it doesn't work.
Inside the file there are 5 cloumns, (1st and the 5th is unnecessary in this problem)
2.cloumn we have votes that a person got
3.column we have surnames and obviously in the 4.cloumn we have first names.
kepviselok.txt
expected and actual output
package erettsegi2;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
var lista = Files.readAllLines(Paths.get("kepviselok.txt"));
var listak = new ArrayList<Lista>();
var input = new Scanner(System.in);
for (var valaszt : lista) {
String[] split = valaszt.split(" ");
var kerSzam = Integer.parseInt(split[0]);
var szavazottSzam = Integer.parseInt(split[1]);
var nev = split[2] + " " + split[3];
var part = split[4].equals("-") ? "Independent " : split[4];
listak.add(new Lista(kerSzam, szavazottSzam, nev, part));
}
System.out.println("2.");
System.out.println("Number of Representatives on Election: " + listak.size());
System.out.println("3.\nPlease write a surname!");
var surname = input.nextLine();
System.out.println("Please write a first name!");
var firstname = input.nextLine();
for (var i = 0; i < listak.size();i++) {
var actualCandidate = listak.get(i);
if (actualCandidate.name.equals(surname + " " + firstname)) {
System.out.println(actualCandidate.name);
System.out.println("Number of votes " + actualCandidate.votes);
break;
} else {
System.out.println("No candidate with this name");
break;
}
}
}
static class Lista {
int sorszam;
int votes;
String name;
String part;
public Lista(int sorszam, int szavazatokSzama, String nev, String part) {
this.sorszam = sorszam;
this.votes = szavazatokSzama;
this.name = nev;
this.part = part;
}
}
}
Take a look on your code, in the last cycle you have condition if-else and this condition will finish the cycle if first candidate name not equals (else executed, and you have break inside it) or this condition will finish the cycle because you found candidate in the first line (if block executed). It means that you are checking only first entry of your list, then cycle finishes because if or else block executed.
So, correct solution will be move print of "No candidate with this name" outside of cycle if you haven't found candidate (I added boolean candidateFound variable for this purpose), because only after check of whole list you can state that:
boolean candidateFound = false;
for (var i = 0; i < listak.size(); i++) {
var actualCandidate = listak.get(i);
if (actualCandidate.name.equals(surname + " " + firstname)) {
System.out.println(actualCandidate.name);
System.out.println("Number of votes " + actualCandidate.votes);
candidateFound = true;
break;
}
}
if (!candidateFound) {
System.out.println("No candidate with this name");
}
I am a beginner at Java and I am making a fun project for myself to learn more about java, I plan on randomizing videos from a preset list and displaying it to the user.
I am having trouble stopping the loop. Once you type in the kind of video you want to watch the program automatically re-loops, but i want it to ask you if you want to watch another video before relooping. Here is what I have so far:
import java.util.Scanner;
import java.util.Random;
public class YoutubeGenerator {
public static void main(String[] args) {
int randomstring = 0;
for ( ; ; ) {
System.out.println("\n ---------Youtube Video Generator 0.001 BETA------------------ \n");
System.out.println("\n ********* DISCLAIMER: WARNING - This program may direct you to violent, disturbing content, and/or vulgar language and is intended for a MATURE person only. ********* \n \n");
Scanner scan = new Scanner (System.in);
System.out.println("What kind of video from the list would you like to watch? \n");
System.out.println("Cute \n" + "Funny \n" + "WTF \n" + "Interesting \n" + "Documentary \n");
System.out.print("I want to watch: ");
String userString = scan.next();
Random rand = new Random();
if(userString.equalsIgnoreCase("cute")){
String cute1 = "https://www.youtube.com/watch?v=EdCVijVT7Wk";
String cute2 = "http://youtu.be/-XCvPptsfhI?t=7s";
String cute3 = "https://www.youtube.com/watch?v=-nkEPsSsH68";
String cute4= "https://www.youtube.com/watch?v=FZ-bJFVJ2P0";
String cute5 = "https://www.youtube.com/watch?v=argCvDpk_KQ";
System.out.println("Here's a cute video you can watch: " +cute5) ;
}
if(userString.equalsIgnoreCase("funny")){
System.out.println("Here's a funny you can watch:");
String funny1 = "https://www.youtube.com/watch?v=I59MgGlh2Mg";
String funny2 = "http://www.youtube.com/watch?v=HKMNKS-9ugY";
String funny3 = "https://www.youtube.com/watch?v=_qKmWfED8mA";
String funny4= "https://www.youtube.com/watch?v=QDFQYKPsVOQ";
String funny5 = "https://www.youtube.com/watch?v=ebv51QNm2Bk";
}
if(userString.equalsIgnoreCase("wtf")){
System.out.println("Here's a WTF video you can watch:");
String wtf1 = "https://www.youtube.com/watch?v=UfKIoSv2YEg";
String wtf2 = "https://www.youtube.com/watch?v=hcGvN0iBA5s";
String wtf3 = "http://www.youtube.com/watch?v=vxnyqvejPjI&feature=youtu.be&t=1m37s";
String wtf4= "https://www.youtube.com/watch?v=10NJnT6-sSE";
String wtf5 = "https://www.youtube.com/watch?v=DQeyjgSUlrk";
}
if(userString.equalsIgnoreCase("interesting")){
System.out.println("Here's an interesting video you can watch:");
String int1 = "https://www.youtube.com/watch?v=fYwRMEomJMM";
String int2 = "https://www.youtube.com/watch?v=1PmYItnlY5M&feature=youtu.be&t=32s";
String int3 = "https://www.youtube.com/watch?v=HgmnIJF07kg";
String int4= "https://www.youtube.com/watch?v=cUcoiJgEyag";
String int5 = "https://www.youtube.com/watch?v=BePoF4PrwHs";
}
if(userString.equalsIgnoreCase("documentary")){
System.out.println("Here's a space video you can watch: ");
String doc1 = "https://www.youtube.com/watch?v=wS_WlzdOc_A";
String doc22 = "https://www.youtube.com/watch?v=8n0SkIGARuo";
String doc33 = "https://www.youtube.com/watch?v=6LaSD8oFBZE";
String doc4= "https://www.youtube.com/watch?v=zvfLdg2DN18";
String doc5 = "https://www.youtube.com/watch?v=8af0QPhJ22s&hd=1";
}
}
}
}
Insert the following code right before the closing brace of your loop:
System.out.println("Do you want to watch another video? Enter yes or no");
String decision = scan.next();
if (decision.equalsIgnoreCase("no"))
break;
package michael.week.pkg5;
class Employee {
String Fname ;
String Lname;
String PhoneNum;
String Address;
void setFirst(String First){
Fname = First ;
}
void setlast(String Last){
Lname = Last ;
}
void setAddress (String address){
Address = address ;
}
void setPhone (String Phone){
PhoneNum = Phone ;
}
void display (){
System.out.println ("the Fist name is :"+ Fname + " , the last name is : " + Lname + " ,the address is : "+ Address+ " ,the phone is : "+ PhoneNum);
}
}
package michael.week.pkg5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MichaelWeek5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
class Stck {
Employee stck [] = new Employee[10];
int x ;
void stck (){
x= -1 ;
}
Employee push (Employee item){
if (x == 9){
System.out.println ("Stack is full");
}else stck[++x] = item ;
return stck[x];
}
Employee pop (){
if (x <0){
System.out.println (" Stack underflow");
return stck [x];
}else
return stck[x++];
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
String info2 = null ;
Stck obj = new Stck();
Employee obj2 = new Employee ();
int w = -1 ;
for (int r=1 ;r>0; ){
System.out.println("please enter add to add new employee");
System.out.println("please enter pop to pop the last added employee");
System.out.println("please enter exit to exit");
String choice = br.readLine();
if(choice.equals("add")){
System.out.println(w);
if (w >= 9){
System.out.println("you reached the maxmum number !");
continue ;
}
else {
w++;
obj.stck ();
String info ;
System.out.println ("please enter Employee first name :");
info = br.readLine();
System.out.println ("please enter Employee last name name :");
info = br.readLine();
System.out.println ("please enter Employee address :");
info = br.readLine();
System.out.println ("please enter Employee phone number :");
info = br.readLine();
}
} else if(choice.equals("pop")){
obj.pop();
w--;
}else if(choice.equals("exit"))
break ;
else {System.out.println (choice + " is wrong choice !") ;
}
}
}
}
Greetings,
i am new to java and i am working on this program....... i need to know how can i push the data to the stck ?
note : the push's parameter is type employee, and Employee contains First , Last, Phone , and address. how i can push each of them ?
here is what i did , and my instructor refused it
package week.pkg5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Week5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
class Employee {
String [] Fname = new String [10];
String[] Lname= new String [10];
String[] PhoneNum= new String [10];
String[] Address = new String [10];
int x= -1 ;
void increment(){
x++;
}
void PushFirst(String First){
Fname[x] = First ;
}
void Pushlast(String Last){
Lname [x] = Last ;
}
void PushPhone (String Phone){
PhoneNum [x] = Phone ;
System.out.println ("the Fist name is :"+ Fname [x]+ " , the last name is : " + Lname [x] + " ,the address is : "+ Address[x] + " ,the phone is : "+ PhoneNum[x]);
}
void PushAddress (String address){
Address [x] = address ;
}
void pop (){
if (x < 0){
System.out.println (" No Empolyee !");
}
else {
System.out.println ("the Fist name is :"+ Fname [x]+ " , the last name is : " + Lname [x] + " ,the address is : "+ Address[x] + " ,the phone is : "+ PhoneNum[x]);
x--;
}
}
void display (){
if (x < 0){
System.out.println (" No Empolyee !");
}
else {
for (int q = 0 ; q <=x ; q++){
System.out.println ((q+1)+"- "+"the First name is :"+ Fname [q]+ " , the last name is : " + Lname [q] + " ,the address is : "+ Address[q] + " ,the phone is : "+ PhoneNum[q]);
}
}
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
Employee obj = new Employee();
int w = -1 ;
for (int r=1 ;r>0; ){
System.out.println("please enter add to add new employee");
System.out.println("please enter display to display all employees list");
System.out.println("please enter pop to pop the last added employee");
System.out.println("please enter exit to exit");
String choice = br.readLine();
if(choice.equals("add")){
System.out.println(w);
if (w >= 9){
System.out.println("you reached the maxmum number !");
continue ;
}
else {
w++;
obj.increment();
String info ;
System.out.println ("please enter Employee first name :");
info = br.readLine();
obj.PushFirst(info);
System.out.println ("please enter Employee last name name :");
info = br.readLine();
obj.Pushlast(info);
System.out.println ("please enter Employee address :");
info = br.readLine();
obj.PushAddress(info);
System.out.println ("please enter Employee phone number :");
info = br.readLine();
obj.PushPhone(info);}
} else if(choice.equals("display")){
obj.display();
} else if(choice.equals("pop")){
obj.pop();
w--;
}else if(choice.equals("exit"))
break ;
else {System.out.println (choice + " is wrong choice !") ;
}
}
}
}
You would need to create a stack of employees and then you can push the whole employee object on to the stack.
import java.util.Stack;
...
Employee emp = new Employee();
Stack<Employee> stack = new Stack<Employee>();
stack.push(emp);
after creating an object to the class say (here stck) which will hold the data by calling method ex shown below
class std
{
int id;
string name;
public:
void set_id(int i)
{
id=i;
}
void set_name(string n)
{
name = n;
}
void disp()
{
system.out.println("name"+name+" and id = "+id);
}
};
main()
{
std s = new std();
s.set_id(1);
s.set_name("sunmoon");
s.disp();
}
so here you can observe that s is considered as stack and we pushed one person details as like you can create array of object and push n number of person details.
You have several issues in how you've modeled the data.
Issue #1 (The biggest issue of all):
An Employee should not have any internal representation of the stack. Think objects in the real world. In your example, each Employee should have:
a first name
last name
address
phone number
So the member fields :
String [] Fname = new String [10];
String[] Lname= new String [10];
String[] PhoneNum= new String [10];
String[] Address = new String [10];
int x= -1 ;
do not belong. This leads us to...
Issue #2 : The way you've modeled the Stack only allows for a fixed number of entries - 10 in your case). This is not how a stack should work. Read up on what a Stack is if you are uncertain. You can model a Stack in Java using a LinkedList - or use the built in Stack that Java provides. If you decide to create your own version, the important operations that need to be created are:
push
pop
isEmpty
My advice is to start by modelling the employee and pratice by pushing and popping them off of a built in Stack from the JDK until you really understand the operations before you try to create your own.
I want to use the MaxFriends method to find the person with the most friends. Printing the number of friends from the linked list is easy enough but since I clear it after each iteration of the while loop I don't know how to compare the values at the end...
I think the problem could be simplified if I just found the line with the most 'tokens' or in this case strings. Is there a way to do this?
I'm reading in a text file (to create a linked list).
Text file looks like this:
john, peter, maria, dan, george, sonja
maria, nell, ted, don, matthew, ann, john, george
fred, steve
ann, tom, maria
Code thus far:
import java.util.*;
import java.io.*;
import javax.swing.JFileChooser;
public class Test {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
LinkData ld1 = new LinkData();
JFileChooser chooser = new JFileChooser(".");
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: ");
// open and read file:
Scanner scanner = null;
try {
scanner = new Scanner(chooser.getSelectedFile());
} catch (IOException e) {
System.err.println(e);
error();
}
if (scanner == null)
error();
while (scanner.hasNextLine()) {
int friendCount = 0;
String line = scanner.nextLine();
Scanner lineScan = new Scanner(line);
lineScan.useDelimiter(", ");
// System.err.println("The line that was scanned: " + line);
String leader = lineScan.next(); {
while (lineScan.hasNext()) {
list.add(lineScan.next());
friendCount++;
}
System.out.println("Friend Leader: " + leader + "\n" +
"\tFriends include: " + list.toString() + "\n" +
"\tNumber of Friends: " + list.size() + "\n");
} list.clear();
}
}
}
private static void error() {
System.err.println("An error has occurred: bad data");
System.exit(0);
}
public void maxFriends() {
}
}
If I understand the problem correctly, you just need to keep track of who has the most friends so far, and compare that to the next candidate for each line. Stuffing everything into a map or heap seems unnecessary.
By the way, the parsing you're doing is very simple and doesn't need a scanner:
String[] friends = line.split(",\\s*");
System.out.printf("%s has %d friends\n", friends[0], friends.length - 1);
I changed portion of your code into somewhat like below:
int maxFriendCount = 0; // added by me
String maxLeader = null; // added by me
while (scanner.hasNextLine()) {
int friendCount = 0;
String line = scanner.nextLine();
Scanner lineScan = new Scanner(line);
lineScan.useDelimiter(", ");
// System.err.println("The line that was scanned: " + line);
String leader = lineScan.next();
while (lineScan.hasNext()) {
list.add(lineScan.next());
friendCount++;
}
// Added by me
if(friendCount > maxFriendCount)
{
maxFriendCount = friendCount;
maxLeader = leader;
}
System.out.println("Friend Leader: " + leader + "\n" +
"\tFriends include: " + list.toString() + "\n" +
"\tNumber of Friends: " + list.size() + "\n");
list.clear();
}
After while loop terminates, you can get the leader with the most friends.
Why not use a Hashmap for storing the information on a per friend basis
Map<String, List<String>> friends = new HashMap<String, List<String>>();
After each iteration use the friends name as the key in the hashmap and then add the linked list to the map as the value.
Then in maxFriends you will be able to go through the keys and get the values and verify which list had the greatest size and thus the most friends.