Java program keeps exiting program prematurely - java

I need to build a simple automaton for my Automata class. I am using Java and I cannot figure out for the life of me why my program keeps exiting prematurely. I've tried debugging it, having print statements everywhere to figure out where it's stopping, and although I know where it stops, I do not see anything that would make the program stop working. The stoppage happens on line 27 (Right where I SOP "Enter a string of digits...".
Knowing me it's probably something simple, but I cannot figure this one out.
import java.util.*;
public class hw1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please indicate the number of states");
int numState = input.nextInt();
int[] state = new int[numState];
boolean[] accept = new boolean[numState];
for (int i = 0; i < numState; i++) {
System.out.println("Is the state q" + (i + 1) + " a final state? (Answer 1 for yes; 0 for no)");
int finalState = input.nextInt();
if (finalState == 1)
accept[i] = true;
} // for
System.out.println("Enter the number of symbols s: ");
int numSym = input.nextInt();
int[][] next = new int[numState][numSym];
for (int i = 0; i < numState; i++) {
for (int j = 0; j < numSym; j++) {
System.out.println("What is the number for the next state for q" + i + " when it gets symbol " + j);
next[i][j] = input.nextInt();
}//nested for
}//for
String digits = input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
int[] digitArray = new int[digits.length()];
for (int i = 0; i < digits.length(); i++) {
digitArray[i] = digits.charAt(i);
}
for (int i = 0; i < digits.length(); i++) {
System.out.print(digitArray[i] + " ,");
}
System.out.println("end of program");
}// main;
}// class

Change your code to :
input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
String digits = input.nextLine();
This will get and ignore the newline character left in the stream after call to nextInt()

Related

what to revise so that the final word can be print

I'm still learning Java and me and my classmate are working on this assignment code game hangman. We have a problem in the part printing the original word, because we want the word to be hidden, but we need the word to be printed, not hidden on the final output. What can we revise in our code to make it print properly??
import java.util.Scanner;
public class GameHangman {
public static void main(String[] args) {
System.out.println("Welcome! To the HANGMAN game.");
System.out.println("Guess the word by guessing each letter.");
System.out.println("LET'S START!");
String[] words = {"superman","batman","spiderman"};
int t = words.length;
int x, y, miss;
String w;
char l, c='y';
Scanner input = new Scanner(System.in);
while (c=='y')
{
x = (int)(Math.random()*(t));
w = words[x];
char[]chars = w.toCharArray();
var hidden = new char[w.length()];
for(int i = 0; i < hidden.length; i++)
{
hidden[i] = '*';
}
boolean z = false;
int count = 0;
miss = 0;
while(!z)
{
System.out.print("\n(guess) Enter a letter ("+new String(hidden)+"): ");
l = input.next().charAt(0);
y = 0;
for(int i = 0; i < hidden.length; i++)
{
if(chars[i]==l)
{
y++;
if(hidden[i]=='*')
{
hidden[i]=l;
count++;
y++;
}
}
}
if(y==1)System.out.println("\nOOPS!("+l+") already present, try other letters.");
else if (y==0)
{
miss++;
System.out.println("\nYIKES!("+l+") is not in the word, guess again.");
}
if(count==hidden.length) z = true;
}
System.out.println("\nGreat!! You guessed the word("+hidden+")!!!");
System.out.println("You were wrong "+miss+" tries.");
System.out.print("\nDo you want to continue with another game word? "
+ "\nEnter yes or no: ");
c = input.next().charAt(0);
}
}
}
in this part, we print our final word
System.out.println("\nGreat!! You guessed the word("+hidden+")!!!");
and this is what we are getting output. we need to print with not being hidden.
Here are two methods to convert your char array hidden into a String for printing out.
// First option: Create a String object
String str1 = new String(hidden);
System.out.println("\nGreat!! You guessed the word("+str1+")!!!");
// Second option: Using valueOf method
String str2 = String.valueOf(hidden);
System.out.println("\nGreat!! You guessed the word("+str2+")!!!");
Alternatively, you can also print your String variable w and avoid calling these methods.

Coin Flip Program With Mutiple Print Issue

I'm just starting Java and this is a coin flip program that I've written recently. So it's supposed to produce sequences of coin flips that meet the requirements that the user sets, however when it gets to the end it should ask if the user wants to go again. I'm having an issue where it will print the question twice when it gets down to end. I really need to figuer this out so any suggestions/clarifications for my code would be greatly appreciated.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
outer: while (true) {
System.out.print("Ready to run a coin flip simulation. Enter the number of sequences: ");
int sequences = scan.nextInt();
System.out.print("How many heads should each sequence have? ");
int heads = scan.nextInt();
System.out.print("How many tails should each sequence have? ");
int tails = scan.nextInt();
System.out.println("Simulating Sequences");
int tFlips = 0;
int mFlips = 0;
for (int i = 1; i <= sequences; i++) {
int h = 0;
int t = 0;
String s = "";
while (t < tails || h < heads) {
if (Math.random() < 0.5) {
h++;
s += "H";
} else {
t++;
s += "T";
}
tFlips++;
}
if (t + h > mFlips) {
mFlips = t + h;
}
System.out.println(i + " - " + s);
h = 0;
t = 0;
s = "";
}
System.out.printf("The average number of flips was " + ((float) tFlips / sequences) + " and maximum was %d", mFlips);
System.out.println("\r\n");
boolean go = true;
while (go) {
System.out.print("Would you like to run another simulation? (y/n): ");
String c = scan.nextLine();
if (c.equalsIgnoreCase("y")) {
break;
} else if (c.equalsIgnoreCase("n")) {
break outer;
} else {
continue;
}
}
System.out.print("\r\n");
}
}
Your String c = scan.nextLine(); reads a new line from your scan.nextInt() calls. You can read more here Scanner is skipping nextLine() after using next() or nextFoo()?
It is good practice to call .nextLine() after every call to .nextInt() to always consume the newline character.
Change the String c = scan.nextLine(); to String c = scan.next();. And you don't really need the while(go) loop, it's more simple if you're doing this:
System.out.print("Would you like to run another simulation? (y/n): ");
String c = scan.next();
if (!c.equalsIgnoreCase("y"))
break;
P.S.: here is a good answer why the nextLine() isn't working correctly. (by #Rohit Jain)

asking for a name of each customer with array size in for loop

I'm a beginner and I've been really stuck on this problem. I'm not really sure how I can display the number of customer(in an arraySize) (customer #1, customer #2...) and ask for their name in a for loop.
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + arraySize + ": "
}
I've tried dinerArray.length and then i, arraySize with i, (i=0;i<=arraySize;i++) with arraySize/i.. but nothing seems to work. It would either only print once with customer#0 or print nothing at all
You need to change arraySize to i. That way it will produce customer#1,customer#2 etc....
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + i+ ": ");
}
If you just want to read them from the console, you can use a Scanner:
Scanner input = new Scanner(System.in);
int arraySize = 10;
String[] dinerArray = new String[arraySize];
for(int i = 0; i < arraySize; ++i)
{
System.out.print("Enter the name of customer#" + (i + 1) + ": ");
dinerArray[i] = input.nextLine();
}
input.close();
im no Java dev but this is pretty basic.
The problem is that your for loop is just running if i is equal to arraySize, but this never happen.
So, try to change your '==' to a '<='
My solution:
Scanner scan = new Scanner(System.in);
int arraySize = 5;
String[] dinerArray = new String[arraySize];
for(int i = 1; i <= dinerArray.length; i++) {
ystem.out.print("pleas enter name for customer#" + i);
dinerArray[i - 1] = scan.nextLine();
}
Im not sure about the scanner think.

Last word/sentence on an Array Java

I have an assignment, it looks pretty easy however I cannot figure it out how to solve it.
It says:
a) Ask the user: How many words/sentences do you want to write (at
least 5) ? (Use while loop)
b) Use for loop to make the user write the words/sentences
c) After the user's written the words/sentences, output which
word/sentence comes last alphabetically (using .compareTo() method )
This is what I came up with:
import java.util.Scanner;
import java.lang.String;
import java.util.Arrays;
public class LastString {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
final short MIN_NUM = 2;
int num = 0;
int count = 0;
String [] sentence = new String [0];
String last = "";
while (num < MIN_NUM){
System.out.println("How many words/sentences do you want to put? " + "\t\t\t\t\t\t\t\t --- at least " + MIN_NUM);
num = input.nextInt();
sentence = new String [num];
}
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
System.out.println("The word/sentence is: " + sentence[i]);
}
int i = 0;
int max;
for (i=0;i<num-1 ;i++ ) {
if(sentence[i].compareTo(sentence[i+1]) > 0){
last = sentence[i];
count ++;
}else if (sentence[i].compareTo(sentence[i+1]) < 0) {
last = sentence[i+1];
count++;
}
}
System.out.println("\n\n------------" +
"\nLast word/sentence is: " + last);
System.out.println(Arrays.toString(sentence));
}
}
I compiles and runs. I have two problems:
nextLine >>> it is skiping the first Sentence
I don't know how to make the algorithm to calculate which word/sentence has the biggest value or, using the compareTo() method which word/sentence has the value > 0 compared to each and every other value on the array.
Thank you.
Answer to Q1 : num = input.nextInt(); takes a number as the input but doesn't also consume the new-line, and hence the nextLine consumes the empty new line ... you could use input.nextLine also to get the first number instead of num = input.nextInt(); by reading a line, then parsing the int value as num = Integer.parseInt(input.nextLine());
Answer to Q2 :
You re-set the value of last everytime but you don't compare the value of the next biggest candidate with the last before re-assigning last ...
for example, look at the following :
for (int i = 0; i < num - 1; i++) {
String thisLast = "";
if (sentence[i].compareTo(sentence[i + 1]) > 0) {
thisLast = sentence[i];
count++;
} else if (sentence[i].compareTo(sentence[i + 1]) < 0) {
thisLast = sentence[i + 1];
count++;
}
if (thisLast.compareTo(last) > 0)
last = thisLast;
}
it will solve your problem....
int count = 0;
String [] sentence = new String[6];
String last = "";
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
count++;
if(count >= 2){
if(sentence[i].compareTo(last) > 0){
last = sentence [i] ;
}
}else{
last = sentence [i];
}
System.out.println("The word/sentence is: " + sentence[i]);
}

Arrays showing vertically instead of horizontally

I am sort of new to programming and I am working on a school assignments on arrays
I am suppose to write a program that stores statistics using arrays.
import java.io.*;
public class HockeyLeague {
static final int Rows = 7;
static final int Cols = 8;
static double HockeyChart [][] = new double[Rows][Cols];
static HockeyLeague HL = new HockeyLeague();
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[])throws IOException {
while(true){
System.out.println("Welcome to the NHL statistic program");
System.out.println("Would you like to proceed to the program? <y for yes, n for no>");
final String menuDecision = br.readLine();
if (menuDecision.equals("n")) {
System.out.println("Goodbye");
System.exit(0);
}
if (menuDecision.equals("y")) {
while(true) {
System.out.println("The 8 teams are Toronto Maple Leafs, Montreal Canadiens, Ottawa Senators, Detroit Red Wings, Boston Bruins,"+
" Chicago Blackhawks, New York Islanders, and Pitsburg Penguins");
System.out.println("To input statistics for Toronto, enter '0' ");
System.out.println("To input statistics for Montreal, enter '1' ");
System.out.println("To input statistics for Ottawa, enter '2' ");
System.out.println("To input statistics for Detroit, enter '3' ");
System.out.println("To input statistics for Boston, enter '4' ");
System.out.println("To input statistics for Chicago, enter '5' ");
System.out.println("To input statistics for New York, enter '6' ");
System.out.println("To input statistics for Pitsburg, enter '7' ");
int numString = Integer.parseInt(br.readLine());
Info (numString);
}
}
}
}
public static double[][] Info(int teamInput)throws IOException{
System.out.println("Enter the amount of games played");
int games = Integer.parseInt(br.readLine());
HockeyChart [0+teamInput][1] = games;
System.out.println("Enter the amount of wins");
int wins = Integer.parseInt(br.readLine());
HockeyChart [0+teamInput][2] = wins;
System.out.println("Enter the amount of ties");
int ties = Integer.parseInt(br.readLine());
HockeyChart [0+teamInput][3] = ties;
System.out.println("Enter the amount of losses");
int losses = Integer.parseInt(br.readLine());
HockeyChart [0+teamInput][4] = losses;
System.out.println("Enter the amount of goals scored");
int goals = Integer.parseInt(br.readLine());
HockeyChart [0+teamInput][5] = goals;
for (int i = 0; i < Rows; i ++) {
for (int j = 0; j < Cols;j ++) {
System.out.println(HockeyChart[i][j] + " ");
}
System.out.println(" ");
}
return HockeyChart;
}
}
This is the program I came up with. I dont understand why I get an output that is a long vertical row of numbers instead of row of numbers side by side.
Any help would be appreciated! thanks
In your Info method, while iterating over arrays, you are using System.out.println(), instead of that you will need to use System.out.print() method.
for (int i = 0; i < Rows; i ++) {
for (int j = 0; j < Cols;j ++) {
System.out.print(HockeyChart[i][j] + " ");
}
System.out.println();
}
Second println statement will help you to move to next line after one row is printed.
Take a look at your loop:
for (int j = 0; j < Cols;j ++) {
System.out.println(HockeyChart[i][j] + " ");
}
println is short for Print Line - it prints the given string, and then moves on to the next line. If you want to print all the contents of the array in a single line, you could use System.out.print instead:
for (int j = 0; j < Cols;j ++) {
System.out.print(HockeyChart[i][j] + " ");
}
You are using System.out.println which means print in new line.
You can use System.out.print for same line i.e horizontal row.
Code will be like this
for (int i = 0; i < Rows; i ++)
{
for (int j = 0; j < Cols;j ++) {
System.out.print(HockeyChart[i][j] + " ");
}
System.out.println(" ");
}
return HockeyChart;

Categories

Resources