I can't run the following piece of code. I would like to know why I keep getting the .noSuchElementException error. I've seen in another post is due to the fact I'm using the same Input stream for both inputs, but creating a new Scanner or using the .close method doesn't seem to fix my problem.
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
int tooBig = 0; // parts too big
int tooSmall = 0; // parts too small
int perfectParts= 0; // perfect parts
int a = scanner.nextInt();
scanner.close();
for (int i = 0; i <= a ; i++) {
int j = scanner.nextInt();
if(j == 1) {
tooBig++;
} else if (j == -1) {
tooSmall++;
} else if (j == 0) {
perfectParts++;
}
scanner.close();
}
System.out.println(perfectParts + " " + tooBig
+ " " + tooSmall);
}
}
Edit after having removed the scanner.close() method. I still get the same error:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
int tooBig = 0; // parts too big
int tooSmall = 0; // parts too small
int perfectParts= 0; // perfect parts
int a = scanner.nextInt();
for (int i = 0; i <= a ; i++) {
int j = scanner.nextInt();
if(j == 1) {
tooBig++;
} else if (j == -1) {
tooSmall++;
} else if (j == 0) {
perfectParts++;
}
}
System.out.println(perfectParts + " " + tooBig
+ " " + tooSmall);
}
}
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int tooBig = 0; // parts too big
int tooSmall = 0; // parts too small
int perfectParts= 0; // perfect parts
int a = scanner.nextInt();
for (int i = 0; i <= a ; i++) {
int j = scanner.nextInt();
if(j == 1) {
tooBig++;
} else if (j == -1) {
tooSmall++;
} else if (j == 0) {
perfectParts++;
}
}
System.out.println(perfectParts + " " + tooBig
+ " " + tooSmall);
scanner.close();
}
}
scanner.close(); Should only be called at the very end. It's also not even necessary in your specific case and likely the reason why you're getting that exception.
Related
import java.util.*;
public class NFA {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//The number of states
int states;
System.out.println("Enter the number of states:");
states = s.nextInt();
System.out.println("Enter the number of transition states:");
int transitions = s.nextInt();
//current state
int q[][] = new int [states][transitions];
System.out.println("Enter the transitions:");
for(int i=0; i<states; i++) {
System.out.println("State " + (i));
for(int j=0; j<transitions; j++) {
q[i][j] = s.nextInt();
}
}
System.out.println("Type in input:");
String state1;
state1 = s.next();
String in[] = state1.split("");
System.out.println("Transitions:");
System.out.println(" a b");
for(int i=0; i<states; i++) {
System.out.print("State:" + (i) + " ");
for(int j=0; j<transitions; j++) {
System.out.print("q" + q[i][j] + " ");
}
System.out.println("");
}
//Our input
int input[] = new int[in.length];
for(int i=0; i<in.length; i++) {
if(in[i].equals("a")) {
input[i] = 0;
}
if(in[i].equals("b")) {
input[i] = 1;
}
}
System.out.println("____________________________________________________________________________________________________");
int initial = 0;
int finalState = (states-3);
int currentState = initial;
int ip;
int nextState;
for(int i=0; i<in.length; i++) {
System.out.print("q" + currentState + "--" + input[i] + "-->");
ip = input[i];
nextState = q[currentState][ip];
currentState = nextState;
if(i==(in.length-1)) {
System.out.println("q" + currentState);
}
}
if(currentState==finalState) {
System.out.println("Accepted");
}else {
System.out.println("Rejected");
}
}
}
I need to have my program accept multiple final states. I have tried multiple options but can't seem to figure it out.
I tried changing "int finalState = (states-3);" to "int finalState = (states-1);" to see if it changed anything but the issue remains regardless.
I want my program to be flexible in implementing any NFA's.
This program is to reserve time available from three different games. So far in the program, I had printed the two different menus on that shows the game and the other one shows the available time Slots. the Program is set to be an infinite loop so other users have the chance to pick a game and reserve time as well. This is where my problem comes, the second time the program runs it stills displays the time that was previously picked.
import java.util.Scanner;
public class GameReservationSystem {
public static Scanner input = new Scanner(System.in);
static String[] timeSlots = {"1-2pm", "2-3pm", "3-4pm", "4-5pm"};
static String[] Games = {"Backganmon", "Chess", "Dominoes"};
static boolean avaliableTime[][] = new boolean[Games.length][timeSlots.length];
static int userChoice;
public static void main(String[] args) {
for (int i = 0; i < Games.length; i++) {
for (int j = 0; j < timeSlots.length; j++) {
avaliableTime[i][j] = true;
}
}
mainMenu();
}
public static void mainMenu() {
while (true) {
characterPrint('-');
for (int i = 0; i < Games.length; i++) {
System.out.print(i + ". ");
System.out.println(Games[i]);
}
characterPrint('-');
System.out.println("input a number to choose your game!");
userChoice = input.nextInt();
reserveMenu(userChoice);
}
}
public static void reserveMenu(int userChoice) {
int reserveTime = 0;
if (userChoice >= 0 && userChoice < Games.length) {
characterPrint('-');
System.out.println("This are the avaliable times to play" + Games[userChoice]);
for (int i = 0; i < timeSlots.length; i++) {
System.out.print(i + ". ");
System.out.println(timeSlots[i]);
}
characterPrint('-');
System.out.println("Input a number to reserve a time: ");
reserveTime = input.nextInt();
}
if (reserveTime >= 0 && reserveTime < timeSlots.length) {
avaliableTime[userChoice][reserveTime] = false;
System.out.println("You have succesfully reserve a time to play " + Games[userChoice] + " at" + timeSlots[reserveTime]);
}
}
public static void characterPrint(char c) {
for (int i = 0; i < 30; i++) {
System.out.print(c);
}
System.out.println();
}
}
In fact, your problem isn't that you didn't change the boolean values in your table from true to false. Instead, your problem is that you didn't use information in the table before you make reservations. What you were doing is to always set that value to false and print "succesfully reserve", without checking whether that time has already been reserved by someone else.
Try the following code. I also add some codes to handle invalid input number.
By the way, "avaliableTime" looks like a typo, so I changed it to "availableTime".
import java.util.Scanner;
public class GameReservationSystem {
public static Scanner input = new Scanner(System.in);
static String[] timeSlots = {"1-2pm", "2-3pm", "3-4pm", "4-5pm"};
static String[] Games = {"Backganmon", "Chess", "Dominoes"};
static boolean availableTime[][] = new boolean[Games.length][timeSlots.length];
static int userChoice;
public static void main(String[] args) {
for (int i = 0; i < Games.length; i++) {
for (int j = 0; j < timeSlots.length; j++) {
availableTime[i][j] = true;
}
}
mainMenu();
}
public static void mainMenu() {
while (true) {
characterPrint('-');
for (int i = 0; i < Games.length; i++) {
System.out.print(i + ". ");
System.out.println(Games[i]);
}
characterPrint('-');
System.out.println("input a number to choose your game!");
userChoice = input.nextInt();
reserveMenu(userChoice);
}
}
public static void reserveMenu(int userChoice) {
int reserveTime = 0;
if (userChoice >= 0 && userChoice < Games.length) {
characterPrint('-');
System.out.println("This are the avaliable times to play" + Games[userChoice]);
for (int i = 0; i < timeSlots.length; i++) {
if (availableTime[userChoice][i]) {
//if false, this time is not available and should not be displayed.
System.out.print(i + ". ");
System.out.println(timeSlots[i]);
}
}
characterPrint('-');
System.out.println("Input a number to reserve a time: ");
reserveTime = input.nextInt();
}else {
//handle unexpected game number.
System.out.println("Invalid game number, please try again.");
}
if (reserveTime >= 0 && reserveTime < timeSlots.length) {
//what if someone typed 0 although 0 wasn't displayed? (0 wasn't displayed, for example, because it has been reserved by someone else.)
//So you should check whether it is available by the following line.
if (availableTime[userChoice][reserveTime]) {
//if true, this time hasn't been reserved, so it is a valid input.
availableTime[userChoice][reserveTime] = false;
System.out.println("You have succesfully reserve a time to play " + Games[userChoice] + " at" + timeSlots[reserveTime]);
}else {
//if already false, this time has already been reserved by someone else,
//thus it is an invalid input.
System.out.println("This time has already been reserved, please try again.");
}
}else {
System.out.println("Invalid time number, please try again.");
}
}
public static void characterPrint(char c) {
for (int i = 0; i < 30; i++) {
System.out.print(c);
}
System.out.println();
}
}
I'm trying to add spaces and a counter between consecutive runs in a simple java coin toss program.
I want this output: HHHHTHTTTTTTTHTTTHHHTTTTHTTHHHTTTTHHTHHHHHTTTTTTHT
to look print like this: HHHH4 T1 H1 TTTTTTT7 H1 TTT3 HHH3 TTTT4 H1 TT2 HHH3 TTTT4 HH2 T1 HHHHH5 TTTTTT6 H1 T1
I am not sure how to position the conditions in the loop so that spaces and a counter are printed between the consecutive 'T's and 'H's. Do I need to use a different kind of loop? I have tried rearranging the loop and using break; and continue; but haven't gotten the result to print correctly.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
Random randomNum = new Random();
for (int i=0; i < timesFlipped; i++) {
int currentflip = randomNum.nextInt(2);
int previousFlip = 0;
int tailsCount = 0;
int headsCount = 0;
if (currentflip == 0) {
System.out.print("H");
previousFlip = 0;
headsCount++;
}
else if (currentflip == 1) {
System.out.print("T");
previousFlip = 1;
tailsCount++;
}
if (previousFlip == 0 && currentflip == 1) {
System.out.print(headsCount + " ");
headsCount = 0;
}
else if (previousFlip == 1 && currentflip == 0) {
System.out.print(tailsCount + " ");
tailsCount = 0;
}
}
}
You can just store the last flip and a counter like
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
Random randomNum = new Random();
int counter = 1;
int previousFlip = randomNum.nextInt(2);
printFlip(previousFlip);
for (int i=1; i < timesFlipped; i++) {
int currentflip = randomNum.nextInt(2);
if (currentflip == previousFlip) {
counter++;
} else {
System.out.print(counter + " ");
counter = 1;
previousFlip = currentflip;
}
printFlip(currentflip);
}
System.out.print(counter);
}
private static void printFlip(int currentflip) {
if (currentflip == 0) {
System.out.print("H");
}
else if (currentflip == 1) {
System.out.print("T");
}
}
Via a single method:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many times do you want to flip the coin? ");
int timesFlipped = scnr.nextInt();
if (timesFlipped <= 0)
return;
Random randomNum = new Random();
boolean isHeads = false;
int sequence = 0;
for (int i = 0; i < timesFlipped; i++) {
boolean prevFlip = isHeads;
isHeads = randomNum.nextBoolean();
if (i > 0 && isHeads != prevFlip) {
System.out.print(sequence + " ");
sequence = 0;
}
sequence++;
System.out.print(isHeads ? "H" : "T");
}
System.out.println(sequence);
}
I want make like this:
input number[0][0]=201
input number[0][1]=202
input number[1][0]=203
input number[1][1]=204
input last = 203
then find if last input same with above, if true, s.o.p find, else not found
my code:
import java.util.Scanner;
public class array_input {
public static void main(String[] args) {
int a[][];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print("input number[" + i + "][" + j + "]");
int b = scan.nextInt();
a[i][j] = b;
}
}
System.out.print("input what u want");
if (a[i][j] == b) {
System.out.print("found");
} else {
System.out.print("not found");
}
}
}
Maybe you mean something like this ?
import java.util.Scanner;
public class array_input
{
public static void main(String [] args){
int a [][] = new int[2][2];
Scanner scan = new Scanner(System.in);
for(int i = 0;i < 2; i++){
for(int j = 0; j < 2; j++){
System.out.printf("input number[%d][%d]=", i, j);
int b = scan.nextInt();
a[i][j]=b;
}
}
System.out.print("input last = ");
int needle = scan.nextInt();
for (int[] row : a){
for (int col : row){
if(col == needle){
System.out.println("found");
return;
}
}
}
System.out.print("not found");
}
}
Ok, I guess that this is what you want. This checks if the last input of the array is in the array (excluding the last input).
boolean valueInArray = false;
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
if(a[i][j]==b && (i != 2 || j != 2)){
valueInArray = true;
}
}
}
if(valueInArray){
System.out.print("found");
} else {
System.out.print("not found");
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the array "prevScore" not print the value "points"?
I want it to print out points for prevScore [0], and then null 0
This is the array, after the // is something I thought I could use.
int [] prevScore = new int[10]; //{ 0 };
String [] prevScoreName = new String[10]; //{"John Doe"};
public static int[] scoreChange (int prevScore[], int points)
{
for(int i = 9; i > 0; i--){
prevScore[i] = prevScore[i-1];
}
prevScore[0]= points;
return prevScore;
}
I dont know if the print of prevScore is needed.
//a method that prints high scores
public static void printScores (int prevScore[], String prevScoreName[])
{
for (int i = 10; i > 0; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}
}
Here is the rest of my program I am working on... currently only i get one, 0 John Doe.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
do {
int menuchoice = 0;
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1){
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2){
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName); }
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR"); }
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct){
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ){
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Use this loop:
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
I think it should solve your problem.
Update
based on your updated program. Move the following code above the start of the 'do' loop.
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
That is you are moving these lines out of the loop. It should work now.
That is the start of your 'main' method should look something like this:
public static void main(String args[]) throws IOException {
int press = 0;
int[] prevScore = new int[] { 0 };
String[] prevScoreName = new String[] { "John Doe" };
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions," + "3 prev score");
Your printScore() method is trying to access element [10] of an array whose index range is 0 - 9, and is never accessing element [0]. You may want to print the most recent score first:
for (int i = 0; i < 10; i++) {
Or conversely, to print the most recent score last:
for (int i = 9; i >= 0; i--) {
Thank you so much! It Works! The only problem still is that the scorelist prints backwards.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
int[] prevScore = new int[10];
String[] prevScoreName = new String[10];
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1) {
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2) {
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName);
}
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR");
}
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct) {
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ) {
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
System.out.println("Scores: ");
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}