I am tasked with making a word game that has 2 options, plus an exit option. I must make a separate method for each option and am currently working on the method that displays the menu options and gets the users input, then returns that input to the called methods.
This is where I'm at so far. My goal with this code is to get a user to select option 1, 2 or 3 with error checking to force the user to input 1, 2 or 3. Current problems are that inputting option 1, 2 or 3, will print the statement, followed by an extra print statement from both option 1, 2 and 3. Inputting a number outside of 1, 2 and 3 doesn't print the error statement, but does allow the user to input again. Also inputting anything other than a number will endlessly run the loop.
import java.util.Scanner;
public class Small_Programming_Assignment {
public static void main(String[] args) {
getSelection();
substringProblem();
pointsProblem();
}
public static void getSelection() {
int selection = -1;
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selection: ");
selection = scanner.nextInt();
while (selection < 1 || selection > 3) {
System.out.println("Enter your selection: ");
if(scanner.hasNextInt())
selection = scanner.nextInt();
}
switch(selection) {
case 1:
substringProblem();
break;
case 2:
pointsProblem();
break;
case 3:
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid option. Try again. ");
}
}
public static void substringProblem() {
System.out.println("Game 1");
}
public static void pointsProblem() {
System.out.println("Game 2");
}
}
2 problems.
public static void main(String[] args) {
getSelection();
// substringProblem();
// pointsProblem();
}
public static void getSelection() {
int selection = -1;
// Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selection: ");
// selection = scanner.nextInt();
boolean running = true;
// make sure running until the input is 3
while (running) {
Scanner scanner = new Scanner(System.in);
selection = scanner.nextInt();
while (selection < 1 || selection > 3) {
System.out.println("Enter your selection: ");
if(scanner.hasNextInt())
selection = scanner.nextInt();
}
switch(selection) {
case 1:
substringProblem();
break;
case 2:
pointsProblem();
break;
case 3:
System.out.println("Goodbye");
// stop
running = false;
break;
default:
System.out.println("Invalid option. Try again. ");
}
}
}
Related
This is the my code and the problem is using array i am taking names and their marks input and want to print then serially but the name accepting part is not working it is taking number inputs but not the names
import java.util.Scanner;
public class ST_test
{
public static void main(String[] args)
{
int i;
Scanner sc= new Scanner(System.in);
String a[]= new String[5];
int num[]= new int[5];
for(i=0;i<5;i++)
{
System.out.println("position mrks"+i);
num[i]=sc.nextInt();
System.out.println("position name "+i);
a[i]=sc.nextLine();
}
for(i=0;i<5;i++)
{
System.out.print(" "+a[i]+" ");
System.out.print(" "+num[i]+" ");
}
}
}
I used to encounter this error early on in my Java journey. The problem is with the Scanner class, probably a bug.
The solution that I used was to create 2 scanner class objects. One for the numeric values and the other for String values. Here is the modified code:-
import java.util.Scanner;
public class ST_test
{
public static void main(String[] args)
{
int i;
Scanner sc= new Scanner(System.in);
Scanner sc1 = new Scanner(System.in); // new scanner object for Strings
String a[]= new String[5];
int num[]= new int[5];
for(i=0;i<5;i++)
{
System.out.println("position mrks"+i);
num[i]=sc.nextInt();
System.out.println("position name "+i);
a[i]=sc1.nextLine();
}
for(i=0;i<5;i++)
{
System.out.print(" "+a[i]+" ");
System.out.print(" "+num[i]+" ");
}
}
}
While this helps, it would be better to switch to BufferedReader and BufferedWriter class :)
So I'm writing a code for a program with multiple menus that write different struct datas to a file and then with another menu that displays the data written in those files. Here's the code for the menu:
void displayall()
{
FILE *fp;
int choice=0;
struct depart loc = {0};
struct arrive loc1 = {0};
struct travel trav = {0};
fp=fopen("traveldat.dat","r");
while (1)
{
fread(&loc,sizeof(loc),1,fp);
fread(&loc1,sizeof(loc1),1,fp);
fread(&trav,sizeof(trav),1,fp);
double distance,time;
distance = sqrt(pow((loc1.x2-loc.x1),2)+pow((loc1.y2-loc.y1),2));
time = distance/trav.spd;
if (feof(fp))
{
break;
}
printf("\tYour departure location is : %s\n",loc.dep);
printf("\tWith the x-coordinate : %.2f\n",loc.x1);
printf("\tAnd the y-coordinate : %.2f\n\n",loc.y1);
printf("\tYour destination location is : %s\n",loc1.dest);
printf("\tWith the x-coordinate : %.2f\n",loc1.x2);
printf("\tAnd the y-coordinate : %.2f\n\n",loc1.y2);
printf("\tThe distance between these two locations is : %.2fkm\n\n",distance);
printf("\tYour preferred travel method is : %s\n",trav.mthd);
printf("\tWhich has a top speed of : %.2f km/h\n\n",trav.spd);
printf("\tYour expected travel time is : %.2f hours*\n\n",time);
printf("\t*Estimation,actual travel times may vary depending on certain conditions\n\n");
printf("\tThe system will now display the Main Menu\n\n");
}
fclose(fp);
}
The problem I'm facing is that if I go to the menu that writes loc1 or trav before the menu that writes loc, the display menu doesn't work, returns to the main menu, and then refuses to open whenver I try to access it. Is it because fread(&loc) is placed before the other freads? Or is there something I'm missing? Apologies in advance if this code is an eyesore or if I'm asking wrongly, I've only been learning programming for about a month.
Edit: loc1 and loc code as requested
void arrival_location_menu()
{
FILE *fp;
int choice=0;
struct arrive loc1;
fp=fopen("traveldat.dat","a");
printf("Please select your option (Destination location)\n");
printf("1.HOME\n");
printf("2.Andromeda Galaxy\n");
printf("3.The Library\n");
printf("4.Cprogramming.com\n");
printf("5.Return to main menu\n");
scanf("%d",&choice);
fflush (stdin);
switch (choice)
{
case 1: loc1.x2 = 3750;
loc1.y2 = 3450;
loc1.dest = "HOME";
system("CLS");
break;
case 2: loc1.x2 = 9870;
loc1.y2 = 5660;
loc1.dest = "Andromeda Galaxy";
system("CLS");
break;
case 3: loc1.x2 = 1367;
loc1.y2 = 3123;
loc1.dest = "The Library";
system("CLS");
break;
case 4: loc1.x2 = 2133;
loc1.y2 = 4767;
loc1.dest = "stackoverflow.com";
system("CLS");
break;
case 5: system("CLS");
break;
default: printf("Invalid option! Returning you to main menu...\n");
}
fwrite(&loc1,sizeof(loc1),1,fp);
fclose(fp);
return;
}
//DEPARTURE MENU
void departure_location_menu()
{
FILE *fp;
int choice=0;
struct depart loc;
fp=fopen("traveldat.dat","w");
printf("Please select your option (Departure location)\n");
printf("1.UTAR\n");
printf("2.PLUTO\n");
printf("3.IDK\n");
printf("4.UMM\n");
printf("5.Return to main menu\n");
scanf("%d",&choice);
fflush (stdin);
switch (choice)
{
case 1: loc.x1 = 1738;
loc.y1 = 1997;
loc.dep = "UTAR";
system("CLS");
break;
case 2: loc.x1 = 9850;
loc.y1 = 5675;
loc.dep = "PLUTO";
system("CLS");
break;
case 3: loc.x1 = 1363;
loc.y1 = 3125;
loc.dep = "IDK";
system("CLS");
break;
case 4: loc.x1 = 2130;
loc.y1 = 4785;
loc.dep = "UMM";
system("CLS");
break;
case 5:
system("CLS");
break;
default: printf("Invalied option!\n");
}
fwrite(&loc,sizeof(loc),1,fp);
fclose(fp);
return;
}
You seem to be asking if you can read data from anywhere in the file. Yes you can.
There is a function called fseek() to adjust the file pointer. The file pointer is the location next read from or written too.
There is also a function called ftell() to read the current file pointer. That's important if you're going to change the file pointer and want to restore it later.
I would also suggest you get into the habit of initializing variables ( even if it's to NULL or zero ), and of checking return values from functions. These two simple things can make debugging so much simpler.
I believe user #m-m has already explained the coding logic error.
I am trying to figure out how to use the scanner class with a loop. I cannot use break as part of my code. I am unsure how close I am, but any help would be much appreciated.
import java.util.Scanner;
public static void main(String[] args) {
Scanner i = new Scanner(System.in);
System.out.print("Please enter a number between 1 and 10: ");
int number = i.nextInt();
boolean value = number>=1 && number <=10;
while (number >=1 && number <=10){
System.out.println ("Good Job!");
}
if (number <=1 && number >=10 )
continue;
{System.out.print ("You have entered an incorrect number. Please try again");
System.out.println("Please try again:");
Scanner r = new Scanner(System.in);
return;
}
The Scanner class can be used like this:
import java.util.Scanner;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// now loop while the scanner is available
while(scanner.hasNext()) {
// print out every single number input from standard input
System.out.println("Scanner inputed from stdin is " + Integer.toString(scanner.nextInt());
}
}
You can do like this:
import java.util.Scanner;
import java.util.Stack;
public class ScannerDemo {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String next = scan.next();
if("quit".equals(next)) break;
System.out.println("Element: " + next);
}
scan.close();
}
}
Press quit to exit.
I am trying to return a variable 'i' which stores the position of a value in an array.I want to return the value of 'i' so that the other classes can use the value to access another value in an array(this might sound a little dumb).How do I do that ?
import java .io.*;
public class Login{
public int i;
public void Menu1()throws IOException
{
int flag=0;
int goal=0;
String p;
String Username[]={"Mohit","Rahul","Mehul","Kevin","Tony"};
String MNumber[]={"8720765181","8659133560","9869206216","9767445692","9967129878"};
String Password[]={"1234","5678","9012","3456","7890"};
int Balance[]={20,124,256,67,512};
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
do
{
System.out.println("Enter your Username");
String username=br.readLine();
for(i=0;i<5;i++)
{
if(username.equals(Username[i])){
flag=1;
break;
}}
if(flag==1)
{
System.out.println("Enter your password");
p=br.readLine();
if(p.equals(Password[i]))
{
goal=1;
}
if(goal==1)
{
System.out.println("Password matched");
System.out.println("Welcome Mr."+Username[i]+".Your Registired Mobile number is "+MNumber[i]);
System.out.println("It has a balance of Rs."+Balance[i]+" which will expire on 20th August 2025");
goal=1;
Second_Menu sm=new Second_Menu();
sm.main();
}
else
System.out.println("Incorrect password,please retry");
}
else
System.out.println("incorrect username,please retry");
}while(goal!=1);
}
}
This is the class in which I want to call the value.
import java.io.*;
public class Recharge
{
public void recharge()throws IOException {
int Balance[]={20,124,256,67,512};
int chcea;
double recAmt=0;
double u;
int i=0;
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Choose an option");
System.out.println("1.Recharge your account");
System.out.println("2.Return to Main Menu");
chcea=Integer.parseInt(br.readLine());
System.out.println("You choose option number "+chcea+".Proceed(y or n)");
String answ=br.readLine();
switch(answ)
{
case "y":
switch(chcea)
{
case 1:System.out.println("For the first time India a Mobile Service Provider gives you the freedom to recharge with a coustom amount");
System.out.println("Please enter a recharge amount");
recAmt=Double.parseDouble(br.readLine());
System.out.println("Your entered amount is Rs."+recAmt+".Proceed(y or n)");
String optyn=br.readLine();
switch(optyn)
{
case "y":System.out.print("Please wait");
for(int wait=0;wait<=5;wait++);
{for(int tmp=0;tmp<=999999999;tmp++){}
System.out.print(".");
}
System.out.println("Your account has been successfully recharged.");
System.out.println("Your new Balance is Rs."+(Balance[i]+recAmt));
break;
case "n":break;
default:System.out.println("Please enter a valid choice");
break;
}
case 2 :Second_Menu sm= new Second_Menu();
sm.main();
break;
}
case"n":break;
}
}
}
I want to return the value of 'i' from the first class so that the second class can use it to access the value in the array 'Balance[]' for the right user.I also want that after recharge the value of balance of that user(i) changes to the new recharged amount.
if you make the int i public other classes can use it and if you make it static, if a constructor or something changes it, it changes the value for the whole program
try to make the int i a
public static int i
I'm coding a contact manager using a doubly linked list that is manipulated by functions using pointers that reads in a contactList.txt.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<process.h>
#include<stdlib.h>
#include<dos.h>
//functions
listelement * getFirst(listelement *listpointer,string query[MAX]);
void getLast();
void getEmail();
void getCompany();
void getNumber();
void editCon();
void delCon();
void addCon();
void listAll();
void sortCon();
void Menu (int *choice);
#define MAX 20
//struct to order contactList
struct contact
{
string firstName[MAX],lastName[MAX],email[MAX],companyName[MAX];
long phoneNum[MAX];
struct listelement *link
struct contact *next;
struct contact *prev;
}list;
int main()
{
listelement listmember, *listpointer;
string query;int iChoice = 0;
listpointer = NULL;
Menu (&iChoice);
int iChoice;
fflush(stdin);
scanf_s("%d", &iChoice);
// user enters one of 9 values
// options are as follows: get first name,last name,list all contacts,search through contacts,add a new contact,edit/delete or sort contacts.
switch(iChoice)
{
case 1:
{
printf ("Enter contact first name to get details ");
scanf ("%d", &query);
listpointer = getFirst (listpointer, query);
break;
}
case 2:
{
getLast();
break;
}
case 3:
{
listAll();
break;
}
case 4:
{
getEmail();
break;
}
case 5:
{
getCompany();
break;
}
case 6:
{
getNumber();
break;
}
case 7:
{
addCon();
break;
}
case 8:
{
editCon();
break;
}
case 9:
{
delCon();
break;
}
case 10:
{
sortCon();
break;
}
case 11: // exit
{
printf("\n\nProgram exiting!...");
exit(0);//terminates program
break;
}
default:
printf ("Invalid menu choice - try again\n");
break;
}//end of switch
return(iChoice);
}//end of main
//menu function to test if invalid input was entered in a menu choice.
void Menu (int *iChoice)
{
char local;
system("cls");
printf("\n\n\t\\n\n");
printf("\n\n\t\tWelcome to my Contact Manager\n\n");
printf("\n\t\t1. First name");
printf("\n\t\t2. Last name");
printf("\n\t\t3. List all contacts");
printf("\n\t\t4. Search email");
printf("\n\t\t5. Search company name");
printf("\n\t\t6. Search number");
printf("\n\t\t7. Add contact");
printf("\n\t\t8. Edit contact");
printf("\n\t\t9. Delete contact");
printf("\n\t\t10. Sort contacts");
printf("\n\t\t11. Exit");
printf("\n\n\t\tEnter your menu choice: ");
do
{
local = getchar ();
if ( (isdigit(local) == FALSE) && (local != '\n') )
{
printf ("\nYou must enter an integer.\n");
printf ("");
}
} while (isdigit ((unsigned char) local) == FALSE);
*iChoice = (int) local - '0';
}
//function to get a contact by entering first name
listelement * getFirst (listelement *listpointer, string query)
{
//variables
char query[MAX],firstName[MAX];
FILE *fp, *ft;
int i,n,ch,l,found;
system("cls");
do
{
found=0;
l=strlen(query);
fp=fopen("ContactList.txt","r");
system("cls");
printf("\n\n..::Search result for '%s' \n===================================================\n",query);
while(fread(&list,sizeof(list),1,fp)==1)
{
for(i=0;i<=l;i++)
firstName[i]=list.firstName[i];
firstName[l]='\0';
if(stricmp(firstName,query)==0)
{
printf("\n..::First Name\t: %s\n..::Second Name\t: %ld\n..::Email\t: %s\n..::CompanyName\t: %s\n..::Number\t: %s\n",list.firstName,list.lastName,list.email,list.companyName.list.phoneNumber);
found++;
if (found%4==0)
{
printf("..::Press any key to continue...");
getch();
}
}
}
if(found==0)
printf("\n..::No match found!");
else
printf("\n..::%d match(s) found!",found);
fclose(fp);
printf("\n ..::Try again?\n\n\t[1] Yes\t\t[11] No\n\t");
scanf("%d",&ch);
}while(ch==1);
}
Anyone have any idea as to where I'm going wrong in the code?Thanks
Your errors are because:
1) you don't define listelement anywhere
2) you don't define string anywhere (and it's not a type in C)
3) You need to move the #define MAX up above before you use it.
4) You don't define FALSE anywhere (and it's not a type in C)
5) You're redefining elements too, in getFirst() you've passed in query as a "string", then you
define a new query as a char array
6) You get redefinition errors because you've got more than one define. That's somewhat #5 but there's more as well. In your main you declare iChoice here: string query;int iChoice = 0;
then you declare it again int iChoice; right after your Menu() call
7) Please don't do fflush(stdin) that's undefined behavior as per the C standard