Reputation: 7
I cant seem to figure out why the below code won't compile. I get up an error for the line saying: if ((number % 2) == 0) {
. The error message says: "illegal character". The program is supposed to take a number n. If the n == to 1, the program stops. If n is odd it, then the new n == (n*3)+1. If n is even, new n == n/2.
import java.util.Scanner;
import java.lang.Math.*;
public class HasseAlgoritme {
public static void main(string [] args) {
Scanner tastatur = new Scanner(System.in);
System.out.print("Input the first starting number");
int number = tastatur.next();
while (number != 1) {
System.out.print(number);
if ((number % 2) == 0) {
System.out.println(number);
}
else {
number = (number*3)+1;
System.out.print(number);
}
}
}}
Upvotes: 0
Views: 516
Reputation: 5531
this will compile.I have closed the scanner. and You are running infinite while loop
import java.util.Scanner;
public class HasseAlgoritme {
public static void main(String [] args) {
Scanner tastatur = new Scanner(System.in);
System.out.print("Input the first starting number");
int number = Integer.valueOf(tastatur.next());
while (number != 1) {
System.out.print(number);
if ((number % 2) == 0) {
System.out.println(number);
}
else {
number = (number*3)+1;
System.out.print(number);
}
}
tastatur.close();
}
}
Upvotes: 0
Reputation: 95968
public static void main(string[] args)
Should be
↓
public static void main(String[] args)
Java is case sensitive!
Also number
should be String and not an int
, this won't compile (or use nextInt
instead of next
).
Upvotes: 5
Reputation: 22720
Also tastatur.next();
returns String
, you might want to use tastatur.nextInt();
instead
Upvotes: 0
Reputation: 94479
If a number is being entered the scanner should use nextInt()
int number = tastatur.nextInt();
tastatur.nextLine();
Upvotes: 0
Reputation: 10497
Read integer using this : int number = tastatur.nextInt();
or
this : int number = Integer.parseInt(tastatur.next());
.
Upvotes: 0