I'm taking some value with the scanner in class student : mat,name and surname. I want to finish the program when the insert of mat is == "" and not a code.
For exemple when i insert mat: 8293 the program go on but when i will insert "" a blank value the program will finish. I think the mat value should be converted to an Integer but don't work the if block.
public static void inserimento() {
Studente s=null;
do{
System.out.println("\nmatricola:");
Scanner mat = new Scanner(System.in);
int matricola = mat.nextInt();
Integer i = Integer.valueOf(matricola);
if(i.equals(null)){
break;
}
System.out.println("\ncognome:");
Scanner cog = new Scanner(System.in);
String cognome = cog.next();
System.out.println("\nnome:");
Scanner nom = new Scanner(System.in);
String nome = nom.next();
s = new Studente(matricola,cognome,nome);
} while(true);
System.out.println("fine inserimento");
}
You can read the input like string and parse it to an Integer. This allow you to check if the input value is empty.
public static void inserimento() {
Studente s=null;
do{
System.out.println("\nmatricola:");
Scanner mat = new Scanner(System.in);
try {
String matricola = mat.nextLine();
if(matricola.equals("")){
break;
}
Integer i = Integer.valueOf(matricola);
System.out.println("\ncognome:");
Scanner cog = new Scanner(System.in);
String cognome = cog.next();
System.out.println("\nnome:");
Scanner nom = new Scanner(System.in);
String nome = nom.next();
s = new Studente(matricola,cognome,nome);
}
catch(Exception e) {
System.out.println("the input value must be an Integer");
}
} while(true);
System.out.println("fine inserimento");
}
public static void inserimento() {
Studente s=null;
do{
System.out.println("\nmatricola:");
Scanner mat = new Scanner(System.in);
String matricolaString = mat.nextLine();
if(!matricolaString.equals(""))
{
int i = Integer.parseInt(matricolaString);
}
else{
break;
}
System.out.println("\ncognome:");
Scanner cog = new Scanner(System.in);
String cognome = cog.next();
System.out.println("\nnome:");
Scanner nom = new Scanner(System.in);
String nome = nom.next();
s = new Studente(matricola,cognome,nome);
} while(true);
System.out.println("fine inserimento");
}
Related
I'm writing JDBC in Java, my thought is to write a method called userInsertCruise, which can make user input the data, and these data will add a new row into my database table.
Here is my code look like:
public class Insert_Cruise {
public void userInsertCruise(Date sailingDate, Date returnDate,String departurePort,
String shipName, String portOfCalls, String cruiseSerialNumber, int passengerID){
while(true){
System.out.println("Input the sailing date:");
Scanner sc1 = new Scanner(System.in);
sailingDate = java.sql.Date.valueOf(sc1.next());
System.out.println("Input the return date :");
Scanner sc2 = new Scanner(System.in);
returnDate = java.sql.Date.valueOf(sc2.next());
System.out.println("Input the departure port:");
Scanner sc3 = new Scanner(System.in);
departurePort = sc3.next();
System.out.println("Input the ship name");
Scanner sc4 = new Scanner(System.in);
shipName = sc4.next();
System.out.println("Input the ports of calls:");
Scanner sc5 = new Scanner(System.in);
portOfCalls = sc5.next();
System.out.println("Input the cruise serial number:");
Scanner sc6 = new Scanner(System.in);
cruiseSerialNumber = sc5.next();
System.out.println("Input the passenger ID:");
Scanner sc7 = new Scanner(System.in);
passengerID = sc7.nextInt();
System.out.println("Are you finish establish your data? Y/N");
Scanner ans = new Scanner(System.in);
String answer = ans.next();
if(answer != "y"){
break;
}else{
continue;
}
public void insertCruise() throws SQLException
{
String url = ("org.apache.derby.jdbc.ClientDriver");
Connection conn = null;
Statement st = conn.createStatement();
try {
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/mydata");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
try {
st.executeUpdate("INSERT INTO CRUISE ("
+ "SAILING_DATE, RETURN_DATE, DEPARTURE_PORT, SHIP_NAME,
PORTS_OF_CALLS, CRUISE_SERIAL_NUMBER, PASSENGER_ID_NUMBER) "
+ "VALUES (?,?,?,?,?,?,?)");
} catch (SQLIntegrityConstraintViolationException e) {
System.out.println("Record Already exists.");
}
}
Then I want to call the method in main:
Insert_Cruise insert = new Insert_Cruise();
insert.userInsertCruise(sailingDate, returnDate, passward, username, passward, username, 0);
insert.insertCruise();
However, it does not work. Because I have no parameter to input in the userInsertCruise method.
The reason that I don't want to use Scanner in the main method is it would make the main method too long. And I have to make user can insert row in different tables in my database, if I write all the scanner in main, it would be very mess.
Is there any method to fix this problem?
I want to create a string ArrayList with input coming from user but inputs going to endless. How to stop it when user want.
public class SortingString {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
System.out.println("Enter the words:");
while (in.hasNext()) {
words.add(in.nextLine());
}
Collections.sort(words);
}
Edit: Thanks for all answers guys. It's working now.
What about?
public class SortingString {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
while (in.hasNext()) {
System.out.println("Enter the word:");
words.add(in.nextLine());
System.out.println("Do you want to continue? (y/n)");
in.hasNext();
if (!in.nextLine().equalsIgnoreCase("y")) {
break;
}
}
Collections.sort(words);
in.close(); // Don't forget to close the stream !!
}
}
A more elegant way: (EDIT Posted full code)
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
System.out.println("Enter the words or write STOP to exit:");
while (in.hasNext()) {
String inputLine = in.nextLine();
if (inputLine.equalsIgnoreCase("STOP")) {
break;
}
words.add(inputLine);
}
Collections.sort(words);
System.out.println("The words sorted:");
System.out.println(words);
in.close(); // Don't forget to close the stream !!
}
This would be a possible solution, where the "quit" word is not added to the words list.
public class SortingString {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
System.out.println("Enter the words:");
boolean isFinished = false;
while (!isFinished && in.hasNext()) {
String word = in.nextLine();
if ("q".equals(word)) {
isFinished = true;
} else {
words.add(word);
}
}
in.close();
Collections.sort(words);
}
Can someone tell me why my baggage won't print?
For passenger name I enter, say, John.
For country code I enter: BI
For flight number I enter: 095
For number of baggage I can enter any amount.
Let's say I enter: John, BI, 095, 3.
This is what I get: [John with baggage(s) [, , ]] when I should be getting
[John with baggage(s) [BI0950, BI0951, BI0952]]
Sorry if the code is quite messy.
It's amended. Thanks guys.
import java.util.*;
public class baggageSys{
public static String getUser_command(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter command B-baggage, n-next, q-quit");
String s = keyboard.nextLine();
return s;
}
public static String getUser_flight(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the flight number");
String s = keyboard.nextLine();
return s;
}
public static String getPassenger(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter passenger name");
String s = keyboard.nextLine();
return s;
}
public static String getUser_country(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the country code");
String s = keyboard.nextLine();
return s;
}
public static int getUser_number(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter number of baggage");
int s = keyboard.nextInt();
return s;
}
public static String next(ListIterator<Passenger> passenger){
String k = "";
passenger.next();
return k;
}
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
public static void main(String args[]) {
LinkedList<Passenger> passenger = new LinkedList<Passenger>();
ListIterator<Passenger> iterator = passenger.listIterator();
LinkedList<String> baggage = new LinkedList<String>();
String command = "";
while (!command.equals("q")){
command = getUser_command();
if(command.equals("B") || command.equals("b")){
String p = "";
p = getPassenger();
passenger.add(new Passenger(p));
// command = getUser_command();
String country = "";
country = getUser_country();
String flight = "";
flight = getUser_flight();
int amount = 0;
amount = getUser_number();
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i]);
passenger.getLast().setBaggages(baggage);
}
System.out.println(passenger);
} else if(command.equals("n")){
next(iterator);
}
else
System.out.println("Enter 'q' to end the program");
}
}
public static class Passenger {
String passengers;
List<String> baggage;
public Passenger(String passengers) {
this.passengers = passengers;
baggage = Collections.emptyList();
}
public void setBaggages(List<String> baggage) {
this.baggage = baggage;
}
#Override
public String toString() {
return passengers + " with baggage(s) " + baggage;
}
}
}
You're not returning anything in your makeBaggage method, as you can see after the loop it returns the x variable which is not either set inside the loop, in this case your loop is useless.
public static String makeBaggage(String country, String flight, int num){
String x = "";
for(int i = 0; i < num; i++){
String[] bgs = new String[num];
bgs[i] = country + flight + i;
// System.out.println(bgs[i]);
}
return x;
}
I think this is the one you're looking for:
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
For this specific line in your code:
for(int i = 0; i < amount; i++){
String[] bg = new String[amount];
bg[i] = makeBaggage(country, flight, amount);
baggage.add(bg[i]);
System.out.println(bg[i]);
...
Move the String[] bg = new String[amount]; declaration outside of the for loop and instead of supplying the amount in the makeBaggage method, use the loop counter instead as follows: bg[i] = makeBaggage(country, flight, i);
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i])
..
I think that should do it. Also, your code could be greatly improved, and that would be your tasks.
Hi guys please is there anyone can help me out with this program?
write a program that asks the user to enter a postcode and returns the city for that
postcode. If the postcode in not in the list then it should return city not found.
The find city code must be in a separate method findCity()
The user should be able to continue entering postcodes until they enter 9999 to indicate they
are complete (9999 should not appear as “city not found”)
================================================
in the txt file:
Dandenong 3175
Frankstone 3199
Berwick 3816
Cranbourne 3977
Rosebud 3939
Thats what i've done so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) throws FileNotFoundException
{
try
{
File f = new File("Files\\cities.txt");
Scanner input = new Scanner(f);
String text;
while(input.hasNextLine())
{
text = input.nextLine();
process(text);
}
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
public static void process(String text)
{ String name = null;
int id;
Scanner code = new Scanner(System.in);
System.out.println("enter the postcode");
id = code.nextInt();
Scanner data = new Scanner(text);
if(code.equals(0))System.out.println(name);
name = data.next();
id = data.nextInt();
while(data.hasNextDouble())
{
}
System.out.println(name+ " ");
// System.out.println(id+ " ");
}
}
File f = new File("d:\\cities.txt");
Scanner input = new Scanner(f);
Map<Integer,String> cityCode = new HashMap<Integer,String>();
String text;
while(input.hasNextLine())
{
text = input.nextLine();
Scanner data = new Scanner(text);
String name = data.next();
int id2 = data.nextInt();
cityCode.put(id2, name);
}
System.out.println("enter the postcode");
Scanner code = new Scanner(System.in);
int id = code.nextInt();
if(cityCode.containsKey(id)) {
System.out.println(cityCode.get(id));
} else {
System.out.println("City Not found");
}
Here's a straight forward approach:
First, you want user to enter a passcode. If passcode is lesser than 9999, you want to search the text file to find a city with that passcode. This thing can be implemented as:
int passcode = 5; // Suppose passcode is 5. You may suppose any value lesser than 9999
Scanner input = new Scanner(System.in);
// Ask user to enter a passcode. If user enters 9999 the while loop is exited
while(passcode < 9999)
{
System.out.println("Enter passcode: ");
passcode = input.nextInt();
// donot search if passcode is greater than or equal to 9999
if(passcode < 9999)
searchCity(passcode);
}
searchCity() method works like:
public static String searchCity(int passcode) {
Scanner citiesScanner = new Scanner(new File("Files\\cities.txt"));
while(citiesScanner.hasNext()) {
String city = citiesScanner.next();
String pass = citiesScanner.next();
if(Integer.parseInt(pass) == passcode) {
return city;
}
}
return "City not found";
}
Just try to break your problem into sub problems. Do some paper work before starting typing code. Things become a lot simpler this way.
I just started to learn Java a few days ago and i wanted to create a program that will create an account,stored it and then if we enter the exact username and password then it will say "login successful".Please don't mind my way of naming the variables and classes.My question is in my "crttacc" class,where i have set up 2 get method to get the un and pa variables.However,in my main method after running the create method in crttacc,the input data seem to gone away and not stored in the un,pa variables as when i try to print them out to check it,it would return "null".I'm a newbie so i'm not quite sure that my question was clear enough and i hope that u guys can help me.You have my gratitude.
Here's my codes:(please don't laugh :D)
import java.util.Scanner;
class crttacc {
String pa;
String un;
void create() {
Scanner unin = new Scanner(System.in);
Scanner passin = new Scanner(System.in);
System.out.println("enter the user name: ");
String l1 = unin.nextLine();
System.out.println("enter the password: ");
String l2 = passin.nextLine();
l1=un;
l2=pa;
}
String getpass(){
return un;
}
String getuser(){
return pa;
}
}
class loginn {
;
void logingin() {
crttacc acc1 = new crttacc();
String pass = acc1.getpass();
String user = acc1.getuser();
System.out.println(pass);
System.out.println(user);
Scanner passwordinput = new Scanner(System.in);
Scanner usernameinput = new Scanner(System.in);
System.out.println("username:");
String line1 = usernameinput.nextLine();
System.out.println("Password:");
String line2 = passwordinput.nextLine();
String d1=line1;
String d2=line2;
if(d1.equals(pass) && d2.equals(user)) {
System.out.println("login successfull");
}
else {
System.out.println("try again");
}
}
}
public class login3 {
public static void main(String[] args) {
Scanner com = new Scanner(System.in);
System.out.println("enter your command: create account or login");
String com1 = com.nextLine();
String l1=com1;
if(com1.equals("create account")) {
crttacc acc1 = new crttacc();
acc1.create();
}
Scanner com2 = new Scanner(System.in);
System.out.println("would you like to login now? y/n");
String cm2 = com2.nextLine();
String l2=cm2;
if(l2.equals("y")) {
loginn log1 = new loginn();
log1.logingin();
}
else{
}
}
}
it's :
un=l1;
pa=l2;
in the Create() method
The problem seems to be, that you store the input data you get through the scanner in l1 and l2. Then you give your l1 and l2 variables the value of un and pa (which is null at this point). At the end of your method the local variables l1 and l2 are thrown away and nothing changed for your un and pa.
You propably wanted something like this:
void create() {
Scanner scanner = new Scanner(System.in);
System.out.println("enter the user name: ");
String l1 = scanner.nextLine();
System.out.println("enter the password: ");
String l2 = scanner.nextLine();
this.un = l1;
this.pa = l2;
}
With this you stored the values of l1 and l2 in your fields un and pa and can access them through your getters.
Hint: you don't need a new Scanner for every input. You can reuse it :)