This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I am writing a TicTacToe program and for some reason it is skipping the scanner.nextLine() for player 1, but is stopping for player 2. Entire code is as follows: Method in question is called "Names"
package tictactoe;
import static java.lang.System.*;
import java.io.*;
import java.util.Scanner;
public class TicTacToe {
static String p1name;
static String p2name;
static String p1marker;
static String p2marker;
public static Scanner qwe = new Scanner(in);
public static void title(){
out.println("\tTicTacToe by Ryan Hosford");
out.print("\n\n\n");
out.println("1)Start"+"\t\t" + "2)How to play\t\t" + "3)Quit ");
int title = qwe.nextInt();
if(title == 1)
Names();
else if(title ==2)
Info();
else if(title ==3)
Quit();
else
title();
}
public static void Names(){
out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
out.println("Player 1, What is your name?");
Setp1Name(qwe.nextLine());
out.println("Nice to meet you " + Getp1Name());
out.println("");
out.println("Player 2, what is your name?");
Setp2Name(qwe.next());
out.println("Nice to meet you " + Getp2Name());
qwe.next();
Markers();
}
public static void Markers(){
out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
out.println(Getp1Name()+", Would you like to X's or O's?");
Setp1Marker(qwe.next());
if(Getp1Marker().equals("X") || Getp1Marker().equals("x")){
Setp2Marker("O");
}
else if(Getp1Marker().equals("O") || Getp1Marker().equals("o")){
Setp2Marker("X");
}
else{
Markers();
}
out.println(Getp1Name() + " is playing with: " +Getp1Marker());
out.println(Getp2Name() + " is playing with: " + Getp2Marker());
out.println("");
out.println("Press enter to continue...");
qwe.nextLine();
Game();
}
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
title();
}
public static void Setp1Name(String player1name){
p1name = player1name;
}
public static String Getp1Name(){
return p1name;
}
public static void Setp2Name(String player2name){
p2name = player2name;
}
public static String Getp2Name(){
return p2name;
}
////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void Setp1Marker(String p1Mark){
p1Mark.toUpperCase();
p1marker = p1Mark;
}
public static String Getp1Marker(){
return p1marker;
}
public static void Setp2Marker(String p2Mark){
p2Mark.toUpperCase();
p2marker = p2Mark;
}
public static String Getp2Marker(){
return p2marker;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void Info(){
out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
out.println("TicTacToe is a game where you have to try and get 3 of your markers in a row; Be that diagonally, vertically, or horizontally.");
out.println("The two markers in TicTacToe are X and O");
out.println("The two players take turns placing one of their markers, and the game is over once a player gets 3 in a row.");
out.println("");
out.println("Press enter to continue...");
qwe.next();
title();
}
public static void Quit(){
out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
out.println("Quitting game...");
exit(0);
}
}
Maybe try to change:
public static void Setp1Name(String player1name){
p1name = player1name;
}
to:
public static void Setp1Name(){
p1name = qwe.nextLine();
}
and same for the other setName method.
Related
I am making a PVP RPG game and the display box comes out with "null" instead of the variable I have already declared.
I have declared the variable as the user's next input and stored that information in the variable. Then when I try to display the variable, it only shows "null",
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
I already declared playerOne as a new character(different class)
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
This is the problem I'm coming up with. It is in the same main method and the variables are declared in the main method, and yes I imported scanner and declared the variable userInput
I expected it to be what the user typed in, but it came up with null. As I've said previous, it's in the same main method and nothing should go wrong, but it comes up with "null"
import java.util.Random;
import java.util.Scanner;
public class Arena {
Random generator = new Random();
public static void main(String[] args) {
Character playerOne = new Character(10,10,0);
Character playerTwo = new Character(10,10,0);
boolean P1hasClass = false;
boolean P2hasClass = false;
int p1Swordgo = 0;
int p2Alchgo = 0;
int p2Archgo = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome, Player One and Player Two!");
delay(1500);
System.out.println("What is your name, Player One?");
playerOne.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerOne.name +".");
delay(1000);
System.out.println("What is your name, Player Two?");
playerTwo.name = userInput.nextLine();
delay(1000);
System.out.println("Hello, " +playerTwo.name +".");
delay(1500);
countdown();
System.out.println("Your turn, " + playerOne.name+".");
if (p1Swordgo == 1) {
if (p2Archgo == 1 || p2Alchgo == 1) {
if (playerOne.move == 1){
System.out.println("What do you want to do?" +'\n' +"1 = Move into range of " +playerTwo.name +'\n' +"2 = Heal" +'\n' +"3 = Forfeit");
int P1Choice = userInput.nextInt();
if (P1Choice == 1) {
playerOne.move --;
System.out.println(playerOne.move);
}
}
}
}
}
public static void delay ( int time){
try {
Thread.sleep(time);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void countdown() {
delay(500);
System.out.println("Get ready to fight in 5,");
delay(1000);
System.out.println("4");
delay(1000);
System.out.println("3");
delay(1000);
System.out.println("2");
delay(1000);
System.out.println("1");
delay(1000);
System.out.println("Fight!");
delay(750);
}
}
And then in a class called Character
public class Character {
public int strength;
public double health;
public int move;
public String name;
public Character(double health, int strength, int move) {
this.health = health;
this.strength = strength;
this.name = name;
this.move = move;
}
}
And in a class called SwordFighter
public class SwordFighter extends Character {
public SwordFighter() {
super(60,15, 1);
}
}
And in a class called Archer
public class Archer extends Character{
public Archer() {
super(45,20, 0);
}
}
And finally, in a class called Alchemist
public class Alchemist extends Character {
public Alchemist() {
super(50,15, 0);
}
}
Thank you for your patience, by the way
Once the two players have chosen their name and you have set it using playerOne.name = userInput.nextLine();, you assign a different object, with a null name, to playerOne:
playerOne = new SwordFighter();
So, after this line has been executed, playerOne.name is null.
I am trying to create a chatbot program but my issue is that, when I run the program, it exits right after the sentence is typed.
import java.util.*;
public class Mina{
public static void main(String[]args){
ai();
}
public static void ai(){
greeting();
conversation();
}
public static void greeting(){
System.out.println("Hello. I am Mina.");
}
public static void conversation(){
Scanner console = new Scanner(System.in);
String chat = console.nextLine();
if(!chat.equalsIgnoreCase("\bBye\b") || !chat.equalsIgnoreCase("\bBye.\b")){
keywords(chat);
}
}
public static void keywords(String word){
if(word.equalsIgnoreCase("\bHello\b") || word.equalsIgnoreCase("\bHello.\b")){
System.out.println("What do you want to talk about?");
keywords(word);
}else if(word.equalsIgnoreCase("\bMr. Smith\b") || word.equalsIgnoreCase("\bMr. Smith.\b")){
System.out.println("I bet he is a nice teacher.");
keywords(word);
}else if(word.equalsIgnoreCase("\bBye\b") || word.equalsIgnoreCase("\bBye.\b")){
System.exit(0);
}
return;
This is what I get:
Mina's Run
I previously had my code loop by placing keyword(); at the end of the method.
}else if(word.equalsIgnoreCase("\bBye\b") || word.equalsIgnoreCase("\bBye.\b")){
System.exit(0);
}
keyword(word);
return;
If anyone has any ideas on what I can possibly do to fix this problem, please help.
I have modified your code to make it work in a fashion where it will ask the user to input a new line until they say "Bye". This is achieved by using the while loop as shown:
import java.util.*;
public class Mina{
public static void main(String[]args){
ai();
}
public static void ai(){
greeting();
conversation();
}
public static void greeting(){
System.out.println("Hello. I am Mina.");
}
public static void conversation(){
Scanner console = new Scanner(System.in);
String chat = console.nextLine();
while(!(chat.equalsIgnoreCase("Bye") || chat.equalsIgnoreCase("Bye."))){
keywords(chat);
chat = console.nextLine();
}
System.exit(0);
}
public static void keywords(String word){
if(word.equalsIgnoreCase("Hello") || word.equalsIgnoreCase("Hello.")){
System.out.println("What do you want to talk about?");
}else if(word.equalsIgnoreCase("Mr. Smith") || word.equalsIgnoreCase("Mr. Smith.")){
System.out.println("I bet he is a nice teacher.");
}
}
}
I am still a noob in object-oriented programming so I want to ask how to run this line in Main.java: Student.displayInfo(students); If I try to place a static modifier in the methods and variables, the conditional statements will react violently. Can you tell me how to do it?
Main.java
import java.util.Scanner;
public class Main {
public void main(String[] args) {
Scanner in = new Scanner(System.in);
Student[] students = new Student[3];
for (Student student : students) {
System.out.println("Can you code: (y/n) ");
student.canCode = (in.next().charAt(0) == 'y' || in.next().charAt(0) == 'Y');
}
Student.displayInfo(students);
}
}
Student.java
public class Student {
boolean canCode = false;
public boolean getCodingSkill() {
return canCode;
}
public void displayInfo(Student [] students) {
for (Student student : students) {
if (getCodingSkill())
System.out.println("I can code.");
else System.out.println("I can't code.");
System.out.println("\n====================");
}
}
}
If I have understood your question correctly, then this would be my answer:
StudentDetails.java:
package TrialPrograms;
public class StudentDetails {
private static String firstname = "";
private static String lastname = "";
private static boolean cancode = false;
private static boolean iscoding = false;
public void setFname(String name) {
this.firstname=name;
}
public String getFname() {
return this.firstname;
}
public void setLname(String name) {
this.lastname=name;
}
public String getLname() {
return this.lastname;
}
public void setCanCode(boolean cancode) {
this.cancode=cancode;
}
public boolean getCanCode() {
return this.cancode;
}
public void setIsCoding(boolean iscoding) {
this.iscoding=iscoding;
}
public boolean getIsCoding() {
return this.iscoding;
}
public void displayInfo(){
System.out.println("Student Records");
System.out.println("=========================================================");
//for (Student student : students) {
System.out.println("Name: " + firstname+ " " + lastname);
if (cancode==true) {
if (iscoding==true) {
System.out.println(firstname + " is coding!!!");
}
else System.out.println(firstname + " can code.");
}
System.out.println("\n=========================================================");
}
}
Main.java:
package TrialPrograms;
import java.util.Scanner;
class Main extends StudentDetails{
public static void main(String[] args) {
StudentDetails stud = new StudentDetails();
Scanner in = new Scanner(System.in);
int noofstudents=3;
for (int i=1;i<=noofstudents;i++) {
System.out.println("Please enter your first name: ");
stud.setFname(in.next());
System.out.println("Please enter your last name: ");
stud.setLname(in.next());
System.out.println("Can you code: (y/n) ");
if (in.next().charAt(0) == 'y' || in.next().charAt(0) == 'Y') {
stud.setCanCode(true);
System.out.println("Are you coding right now: (y/n) ");
if(in.next().charAt(0) == 'y' || in.next().charAt(0) == 'Y') {
stud.setIsCoding(true);
}else {
stud.setIsCoding(false);
}
}else {
stud.setCanCode(false);
}
System.out.println("Loop is over");
stud.displayInfo();
}
in.close();
}
}
Hope this code answers your question.
I asked this question but the way I worded it was considered a duplicate which was not similar. I am trying to print a separate String for my printAllFlights method which prints all of the user entered information. My other methods print just fine. Here is the output I am trying to achieve.
Choose action:
[1] Print planes
[2] Print flights
[3] Print plane info
[x] Quit
> 2
HA-LOL (42 ppl) (HEL-BAL)
HA-LOL (42 ppl) (BAL-HEL)
How my code is now I get the output null(0) (HEL-BAL). How can i change it to reflect the correct output. Any help would be appreciated.
public class Airport {
private String planeId;
private int capacity;
private String dest;
private String dep;
public Airport(String planeId,int capacity){
this.planeId= planeId;
this.capacity = capacity;
}
public Airport(String planeId, String dep, String dest){
this.dest= dest;
this.dep= dep;
}
public String getPlaneId(){
return this.planeId;
}
public void setPlaneId(String planeId){
this.planeId = planeId;
}
public int getCapacity(){
return this.capacity;
}
public void setCapacity(int capacity){
this.capacity = capacity;
}
public String getDestination(){
return this.dest;
}
public void setDestination(String dest){
this.dest = dest;
}
public String getDeparture(){
return this.dep;
}
public void setDeparture(String dep){
this.dep = dep;
}
public String toString(){
return planeId + " (" + capacity + ")";
}
public String secString(){
return planeId + " (" + capacity + ")" + "(" + dest + "-" + dep;
}
}
import java.util.ArrayList;
public class FlightServices {
private ArrayList<Airport> airport;
public FlightServices() {
airport = new ArrayList<Airport>();
}
public void add(String planeId, int capacity) {
airport.add(new Airport(planeId, capacity));
}
public void addFlight(String planeId, String dest, String dep) {
airport.add(new Airport(planeId, dest, dep));
}
public void printAllPlanes() {
for (Airport all : airport) {
System.out.println(all);
}
}
public void printAllFlights() {
for (Airport all : airport) {
System.out.println(all.secString());
}
}
public void printPlanesInfo(String planeId) {
for (Airport info : airport) {
if (planeId.equals(info.getPlaneId())) {
System.out.println(info);
}
}
}
}
import java.util.Scanner;
public class UserInput {
private Scanner reader;
private FlightServices air;
public UserInput(Scanner reader, FlightServices air) {
this.reader = reader;
this.air = air;
}
public void start() {
while (true) {
System.out.println("Choose operation: ");
System.out.println("[1] Add airplane");
System.out.println("[2] Add flight");
System.out.println("[3] Exit");
int input = Integer.parseInt(reader.nextLine());
if (input == 3) {
break;
} else if (input == 1) {
this.addPlane();
} else if (input == 2) {
this.addFlight();
}
}
}
public void addPlane() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give plane capacity: ");
int capacity = Integer.parseInt(reader.nextLine());
this.air.add(id, capacity);
}
public void addFlight() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give departure airport code: ");
String dep = reader.nextLine();
System.out.println("Give destination airport code: ");
String des = reader.nextLine();
this.air.addFlight(id,dep,des);
}
public void printing() {
while (true) {
System.out.println("Choose operation: ");
System.out.println("[1] Print planes");
System.out.println("[2] Print flights");
System.out.println("[3] Print plane info");
System.out.println("[4] Quit");
int command = Integer.parseInt(reader.nextLine());
if (command == 4) {
break;
} else if (command == 1) {
this.air.printAllPlanes();
} else if (command == 2) {
this.air.printAllFlights();
} else if (command == 3) {
this.addPlaneInfo();
}
}
}
public void addPlaneInfo() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
this.air.printPlanesInfo(id);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
FlightServices air = new FlightServices();
UserInput ui = new UserInput(reader,air);
ui.start();
System.out.println("Flight Service");
System.out.println("----------");
ui.printing();
}
}
Ok.
public void add(String planeId, int capacity) {
airport.add(new Airport(planeId, capacity));
}
public void addFlight(String planeId, String dest, String dep) {
airport.add(new Airport(planeId, dest, dep));
}
You're adding some Airportobjects to your airport using addFlight() and others using add(). The ones you add using addFlight() have no capacity values and the ones using add() have no dest or dep. Do you see? Simply making two entries with the same planeId will not combine them in your arraylist. When you try to print, some values will be null depending on how you had added the Airport objects.
EDIT:
One solution i can think of, while changing your code as less as possible-
public void add(String planeId, int capacity) {
int flag=0;
for(Airport air:airport) {
if(air.planeID.equals(planeID)) {
air.capacity=capacity;
flag=1;
}
}
if(flag==0)
airport.add(new Airport(planeId, capacity));
}
And similarly edit your add() function. This way, you can have all relevant fields filled in a single entry.
Of course, a much better idea would be to restructure your classes entirely, but this should work.
Ok, so for my java class's final project we're supposed to implement a simplified version of craps that runs for 10 rounds. Whenever I run this, I get the NoSuchElementsException for the line "int b=std.nextInt()". Why is that? I opened a scanner object and whatnot, but it wont let me enter the data to proceed with the game, throwing the exception instead. I also get the same exception for the "System.out.println(now.toString());" line in the main method. How could that not have any elements?
public class Player {
private int bet;//how much was bet
private boolean Pass;//they chose pass
private boolean DPass;//they chose dont pass
private boolean win;//did they win?
private int money=20;//how much they have
//private String continuity="initial";
//Modifier methods
public void newBet(int x){this.bet=x;}
public void Pass(boolean x){this.Pass=x;}
public void DPass(boolean x){this.DPass=x;}
public void didYouWin(boolean x){this.win=x;}
public void newMoney(int x){this.money+=x;}
//public void keepPlaying(String s){this.continuity=s;}
//Accessor methods
public int getBet(){return this.bet;}
public boolean getPass(){return this.Pass;}
public boolean getDPass(){return DPass;}
public boolean getResult(){return this.win;}
public int getMoney(){return this.money;}
public boolean isWinning(){return this.win;}
//public String playing(){return continuity;}
public String toString(){
return "Bet: $"+this.bet+"\nBet on Pass: "+this.Pass+"\nBet on Don't Pass: "+this.DPass+"\nMoney:S"+this.money;
}
//Constructor method
public Player(int bet, boolean pass, boolean dpass){
this.bet=bet;
this.Pass=pass;
this.DPass=dpass;
}
}
Actual game play code<<<<<<<<<<<<<<<<<<<<<<<<<<
import java.util.*;
public class trial1 {
public static int RollDice(){ //Method for Dice Roll
int[] die1={1, 2, 3, 4, 5, 6};
int[] die2={1, 2, 3, 4, 5, 6};
Random r=new Random();
int i1=r.nextInt(6-0);
int i2=r.nextInt(6-0);
int sum=die1[i1]+die2[i2];
System.out.println("\nDie 1: "+die1[i1]+"\nDie 2: "+die2[i2]+"\nTotal Sum: "+sum);
return sum;
}
public static int Roll7(){//roll for 7
if (RollDice()==7){
return 2;
}
else return Roll7();
}
public static int PointRoll(int x){//If person rolled 4,5,6,8,9,10...
int a=RollDice();
if (a==x){
return Roll7();
}
else if (a==7){
return 1;
}
else return PointRoll(x);
}
public static int ComeOutRoll(){//1 = pass loses, 2 = pass wins, 3 = pass loses and dont pass gets nothing
int x=RollDice();
if ((x==2)||(x==3)) {
return 1;
}
else if ((x==7)||(x==11)){
return 2;
}
else if (x==12){
return 3;
}
else return PointRoll(x);
}
public static Player InitializeGame(){
//initialize stats and player
System.out.println("Please enter how much you'd like to bet (max is $5)");
Scanner std=new Scanner(System.in);
int b=std.nextInt();
System.out.println("Please enter 1 if you bet PASS or 2 if you bet DON'T PASS");
int p=std.nextInt();
boolean betpass, betdpass;
if (p==1){
betpass=true;
betdpass=false;
}
else {
betpass=false;
betdpass=true;
}
Player name=new Player(b, betpass, betdpass);
System.out.print(name.toString());
std.close();
return name;
}
public static Player BeginGame(Player name){
//Start actual game process without the betting ie all the dice rolling and stat changing -->will return player's status
//boolean pass=name.getPass();
//boolean neutral=false;
int result=ComeOutRoll();
//find out if player won money or lost money
if (name.getPass()){//if player bet on pass
if (result==1){
name.newMoney(name.getMoney()-name.getBet());
}
else if (result==2){
name.newMoney(name.getMoney()+name.getBet());
}
else {
name.newMoney(name.getMoney()-name.getBet());
}
}
else {//if player bet dont pass
if (result==1){
name.newMoney(name.getMoney()+name.getBet());
}
else if (result==2){
name.newMoney(name.getMoney()-name.getBet());
}
else {
name.didYouWin(false);
}
}
if (name.getMoney()<=0){name.didYouWin(false);}//setting win data for yes or no. IF no money, u lose
else {name.didYouWin(true);}
public static Player Continue(Player name){//just like begin game, but adding the new bet
System.out.println("\nPlease enter how much you'd like to bet (max is $5)");
Scanner std=new Scanner(System.in);
int b=std.nextInt();
System.out.println("Please enter 1 if you bet PASS or 2 if you bet DON'T PASS");
int p=std.nextInt();
boolean betpass, betdpass;
if (p==1){
betpass=true;
betdpass=false;
}
else {
betpass=false;
betdpass=true;
}
name.Pass(betpass);
name.DPass(betdpass);
name.newBet(b);
System.out.println(name.toString());
return BeginGame(name);
}
public static void Loss(Player name){//losing message
System.out.println("YOU LOSE!!!!!!!! HAHAHAHAHAHA!!!!!\n"+name.toString());
}
public static void End(Player name){//End game message
System.out.println("Thank you for playing!");
}
public static Player Run(){
Player name = InitializeGame();
return BeginGame(name);
}
public static void main(String[] args){
System.out.println("Welcome to my version of craps!");
Player now=Run();
for (int i=1;i<=10;i++){
if (now.isWinning()){
System.out.println("ROUND "+i);
System.out.println(now.toString());
now=Continue(now);
i++;
}
else {
Loss(now);
System.out.print(now.toString());
End(now);
i=11;
}
}
}
}
The NoSuchElementsException means that you tried to get an int from the scanner, std, but there was no next int. So it throws this error to let you know your input was bad.
It would seem from the NoSuchElementException that you're not reading an int from the Scanner. It is interpreting your input as some other data type.