I have written the following piece of code:
import java.util.Scanner;
public class Congress {
public static int age;
public static int ctzn;
public static boolean eligibleForSenate() {
if ( age >= 25 && ctzn >= 7) {
return true;
} else {
return false;
}
}
public static boolean eligibleForHouse() {
if ( age >= 30 && ctzn >= 9) {
return true;
} else {
return false;
}
public static void main(String[] args) {
System.out.print("Enter age of candidate: ");
Scanner sc = new Scanner(System.in);
age = sc.nextInt();
System.out.println();
System.out.print("Enter years of U.S. Citizenship: ");
ctzn = sc.nextInt();
}
}
}
It gives me an error on the main line. I believe it has something to do with the global variables. How can I fix it?
There is a typo ::
Change code as follow ::
import java.util.Scanner;
public class Congress {
public static int age;
public static int ctzn;
public static boolean eligibleForSenate() {
if ( age >= 25 && ctzn >= 7) {
return true;
} else {
return false;
}
}
public static boolean eligibleForHouse() {
if ( age >= 30 && ctzn >= 9) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
System.out.print("Enter age of candidate: ");
Scanner sc = new Scanner(System.in);
age = sc.nextInt();
System.out.println();
System.out.print("Enter years of U.S. Citizenship: ");
ctzn = sc.nextInt();
}
}
Your braces are not matching, add one closing brace } before your main and remove one from the last line.
Related
I have been learning Java for a week, I have no other experiences. The program keeps crashing, I would like to be automatically asked again in the event of an incorrect entry.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
boolean error;
Scanner scan = new Scanner(System.in);
do {
error = false;
System.out.print("Tell me the Year: ");
if (scan.hasNextInt()) {
int jahr = scan.nextInt();
scan.close();
if (schaltjahre(jahr)) {
System.out.println("Please enter the leap year ");
} else {
System.out.println("It is not a leap year");
}
} else {
System.err.println("enter an integer year!");
error = true;
scan.close();
}
}while (error);
}
public static boolean schaltjahre(int jahr) {
// Aufgabe 1
if (jahr % 400 == 0) {
return true;
} else if (jahr % 100 == 0) {
return false;
} else if (jahr % 4 == 0) {
return true;
}
return false;
}
You should instantiate the scanner inside the loop and don't close it in the else statement.
Your code should be something like this :
public static void main(String[] args) {
boolean error;
Scanner scan ;
do {
error = false;
scan = new Scanner(System.in);
System.out.print("Tell me the Year: ");
if (scan.hasNextInt()) {
int jahr = scan.nextInt();
scan.close();
if (schaltjahre(jahr)) {
System.out.println("Please enter the leap year ");
} else {
System.out.println("It is not a leap year");
}
} else {
System.err.println("enter an integer year!");
error = true;
}
} while (error);
}
So I'm doing this exercise and my teacher says that he wants the num/10 in this line:System.out.print(numDigits(num/10)); in the method (so that if the original number is 0 then it will return 1 digit rather than 0), but I have no idea where he wants it.
(*must be done with recursion to count the number of digits of a number)
To me this way is simple, but I guess if you're writing a lot of code you don't want to keep typing x/10.
import java.util.*;
public class NumDigits
{
public static void main(String[]args)
{
int num;
Scanner input = new Scanner(System.in);
num = input.nextInt();
input.close();
System.out.print(numDigits(num/10));
}
public static int numDigits(int x)
{
if (x == 0)
{return 1;}
else
{
return 1 + numDigits(x/10);
}
}
}
I guess I could do this, but it takes more code... : /
import java.util.*;
public class NumDigits
{
public static void main(String[]args)
{
int num;
Scanner input = new Scanner(System.in);
num = input.nextInt();
input.close();
System.out.print(numDigits(num, num));
}
public static int numDigits(int x, int num)
{
if (num == 0)
{return 1;}
else if (x == 0)
{return 0;}
else
{
return 1 + numDigits(x/10, num);
}
}
}
I am assuming that numDigits returns the number of decimal digits in a number
Here is a straightforward solution:
public static int numDigits(int x) {
return Integer.toString(x).length();
}
Worried about locales/radix/speed/negatives? Try this one:
public static int numDigits(int x) {
if (x == 0) {
return 1;
} else {
return (int) (Math.log10(Math.abs(x))) + 1;
}
}
However, if recursion is required:
public static int numDigits(int x) {
if (x > -10 && x < 10) {
return 1;
} else {
return numDigits(x / 10) + 1;
}
}
Well, that first division is removed rather easily.
public class NumDigits
{
public static void main(String[]args)
{
int num;
Scanner input = new Scanner(System.in);
num = input.nextInt();
input.close();
System.out.print(numDigits(num));
}
And now your check for 0 still works in the numDigits function, and even more it does for the first '0' as well. Only thing you need to tweak now is the recursive call itself, left as an exercise, as it is still homework.
Using a recursion method you can achieve SuperDigit By this way
public class SuperDigit
{
//static int sum = 0;
public static void main(String[] args)
{
int n = 8596854;
System.out.println(sum(n));
}
static int sum (int num)
{
if (num != 0)
{
return (num % 10 + sum (num / 10));
}
else
{
return 0;
}
}
}
well Im an idiot. the answer is:
import java.util.*;
public class NumDigits
{
public static void main(String[]args)
{
long num;
Scanner input = new Scanner(System.in);
num = input.nextInt();
input.close();
System.out.print(numDigits(num));
}
public static long numDigits(long x)
{
if (x/10 == 0)
{return 1;}
else
{
return 1 + numDigits(x/10);
}
}
}
I assumed that it wouldn't work so I didn't try it
why don't you just do this:
import java.util.*;
public class NumDigits
{
public static void main(String[]args)
{
int num;
Scanner input = new Scanner(System.in);
num = input.nextInt();
input.close();
System.out.print(numDigits(num));
}
public static int numDigits(int num)
{
if ((num/10) == 0)
{return 1;}
else
{
return 1 + numDigits(num/10);
}
}
}
this way the "num/10" is in the recursive method not the main method, and the zero problem is solved.
My Java 1.7 program performs various mathematical functions. I have separated the functions into methods and they work ok on their own. I also made a prompt method that asks the users if they want to continue. However, I keep on getting NoSuchElement exception after inputting a number. "Try again? (n/y) " prints, but it doesn't wait for user input and errors automatically. Eclipse Luna highlights this line:
String response = scanner.next();
Here's the main method:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Please input a number: ");
int x = scanner.nextInt();
System.out.println(chooseOperation(x));
do_Continue();
if (do_Continue() == false) {
break;
}
}
scanner.close();
}
Here's the operation chooser method:
public static int chooseOperation(int n) {
Scanner scanner = new Scanner(System.in);
System.out.print("Factorial, Fibonacci, or Pisano? ");
String response = scanner.next();
scanner.close();
if (response.equalsIgnoreCase("factorial")) {
return factorial(n);
} else if (response.equalsIgnoreCase("fibonacci")) {
return fibonacci(n);
} else if (response.equalsIgnoreCase("pisano")) {
return pisano(n);
} else {
System.out.print("Invalid response. ");
chooseOperation(n);
return n;
}
}
And here's the prompt method:
public static boolean do_Continue() {
Scanner scanner = new Scanner(System.in);
System.out.print("Try again? (n/y): ");
String response = scanner.next();
scanner.close();
if (response.equalsIgnoreCase("n")) {
return false;
} else if (response.equalsIgnoreCase("y")){
return true;
} else {
System.out.print("Invalid response. ");
do_Continue();
}
return false;
}
If this helps, here are the methods for the math functions:
public static int factorial(int n) {
if (n==1 || n==0) {
return 1;
} else {
return n*factorial(n-1);
}
}
public static int fibonacci(int n) {
if (n==1 || n==0) {
return n;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
public static int pisano(int n) {
if (n==1 || n==0) {
return n;
} else {
return (fibonacci(n-1) + fibonacci(n-2)) % 7;
}
}
As you can see, except for the main method, all my methods are recursive.
Thanks! :)
Do not call
scanner.close();
When you do that, you close() System.in! Then when you attempt to construct your new Scanner(System.in); it doesn't work (because System.in is closed).
I am trying to build "simple" guessing game :D The idea is that the while loop will check everytime if the anwer was right and if not then user should try to guess one more time. But How can i make it so that the method random number generated by method suvaline would be accessable to both check and gameplay methods.
package AlsoGame;
import java.util.Random;
import java.util.Scanner;
public class AlsoGame {
public static void main(String[] args) {
System.out.println("Please try to guess a number in range from 1 to 10");
AlsoGame mainObject = new AlsoGame ();
int katse = mainObject.suvaline();
System.out.println(katse);
mainObject.check(katse);
mainObject.gameplay(katse);
}
public int InsertNum(){
System.out.println("Bitte, bitte enter a number");
Scanner input = new Scanner(System.in);
int inputNumber = input.nextInt();
return inputNumber;
}
public static int suvaline(){
Random number = new Random();
int x = 1 + number.nextInt(10);
return x;
}
public void gameplay(int katse){
boolean check = false;
int inputNumber = InsertNum();
while(check == false){
check = check(inputNumber);
if (check == true){
System.out.println("You guessed correctly, you win");
return;
}
else{
if (inputNumber > 10 || inputNumber <= 0 ){
System.out.println("Cant you read, you fool, I said guess a number in range from 1 to 10");
if (inputNumber > katse){
System.out.println("you guessed to high");
if (inputNumber < katse){
System.out.println("You guessed to low");
}
}
}
}
}
}
public boolean check(int randomNum){
System.out.println();
final int thresholdVal = randomNum ;
System.out.println(thresholdVal);
if (randomNum == thresholdVal){
return true;
}else{
return false;
}
}
}
I edit it and now the else statement in gameplay method is not executed :D
package AlsoGame;
import java.util.Random;
import java.util.Scanner;
public class AlsoGame {
public final int bla = suvaline();
public static void main(String[] args) {
System.out.println("Please try to guess a number in range from 1 to 10");
AlsoGame mainObject = new AlsoGame ();
mainObject.gameplay();
}
public int InsertNum(){
System.out.println("Bitte, bitte enter a number");
Scanner input = new Scanner(System.in);
int inputNumber = input.nextInt();
return inputNumber;
}
public int suvaline(){
Random number = new Random();
int x = 1 + number.nextInt(10);
return x;
}
public void gameplay(){
int katse = bla;
System.out.println(katse);
boolean check = false;
while(check == false){
int inputNumber = InsertNum();
check = check(inputNumber);
if (check == true){
System.out.println("You guessed correctly, you win");
}
else{
if (inputNumber > 10 || inputNumber <= 0 ){
System.out.println("Cant you read, you fool, I said guess a numbEr in range from 1 to 10");
if (inputNumber > katse){
System.out.println("you guessed to high");
if (inputNumber < katse){
System.out.println("You guessed to low");
}
}
}
}
}
}
public boolean check(int randomNum){
int thresholdval = bla;
if (randomNum == thresholdval){
return true;
}else{
return false;
}
}
}
I don't see why you asked the question, since you're already accessing the variable as a parameter. But to make it accessible in all methods you can do this:
public class AlsoGame {
private int katse = suvaline();
public boolean check(){
int thresholdval = bla;
if (this.katse == thresholdval){
return true;
}else{
return false;
}
}
public void some_other_method(){
//do something with this.katse
}
}
I am supposed to write a program that will prompt the user to enter the hotel rooms that are occupied. Once that is done the user enters -1 and is prompted to enter a random hotel number. If the hotel room is occupied, it prints occupied. If the room is unoccupied, it printer unoccupied. I can't seem to figure out why the unoccupied won't print. Suggestions?
import java.util.Arrays;
import java.util.Scanner;
public class GoughAndreaChapter9
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int [] arr=new int[100];
int counter=0;
int currval=0;
System.out.println("Please enter an occupied hotel room number, -1 to quit ");
do
{
currval = sc.nextInt();
if(currval==-1)
break;
if(currval>0)
arr[counter++]=currval;
}
while(currval !=-1);
// sort using java API
int [] temparr=new int[counter];
for(int i = 0; i<counter; i++)
{
temparr[i] = arr[i];
}
arr = temparr;
Arrays.sort(arr);
//binary search.
int low=0;
int high = counter-1;
System.out.println("Please enter a room to search for: ");
currval = sc.nextInt();
int status=0;
int mid;
while(low<high)
{
if(arr[low]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
else if(arr[high]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
mid = low+high/2;
if(arr[mid]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
else if(arr[mid]<currval)
{
low=mid;
}
else if(arr[mid]<currval)
{
high = mid;
}
}
if(status==0)
System.out.println("Unoccupied");
}
}
Don't ofuscate! Do this:
Room.java
public class Room {
private boolean isOccupied;
public Room() {
this.isOccupied = false;
}
public boolean obtainTheRoom() {
if(!isOccupied) this.isOccupied = true;
return !isOccupied;
}
}
Main.java
import java.util.Scanner;
public final class Main {
private static final int ROOM_AMOUNT = 50;
private static int actualRoom;
private static Scanner cmdin = new Scanner(System.in);
public static void main(String[] args) {
Room[] rooms = new Room[ROOM_AMOUNT];
// Select some random, but static rooms to be occupied
for(int i = 1; i <= ROOM_AMOUNT; i++) {
if(i % 3 - 1 == 0 || i * 2 % i + 10 - 2 == 2) {
rooms[i - 1].obtainTheRoom();
}
}
for(;;) {
System.out.print("Enter a room number:\t");
try {
actualRoom = Integer.parseInt(cmdin.next());
} catch(NumberFormatException nfe) {
loopRoomNumber();
}
if(rooms[actualRoom - 1].obtainTheRoom()) {
System.out.println("Got the room " + actualRoom + "! Now it's occupied -_-");
} else {
System.out.println("Room Occupied!");
}
}
}
private static void loopRoomNumber() {
System.out.print("That's not a valid room number!\n\n");
try {
actualRoom = Integer.parseInteger(cmdin.next());
} catch(NumberFormatException nfe) {
loopRoomNumber();
}
}
}
That should work. Good luck!
I would change your last else if statements as follows. This will work. Because otherwise you will go in an endless loop;
else if (arr[mid] < currval)
{
low = mid;
--high;
}
else if (arr[mid] > currval)
{
high = mid;
++low;
}
Note that i have decremented the high when the mid value is less than the current value, and incremented the low value when the mid value is greater than the current value